<?php
session_start();
include "../db.php";
include "include/php-functions.php"; 

if (isset($_POST['start'])) {
    $start = mysqli_real_escape_string($con, $_POST['start']);
    $AndWhere = '';

    // Initialize an array to hold filter conditions
    $conditions = [];

    include("include/productListFilter.php");

    // Build the WHERE clause
    if (count($conditions) > 0) {
        $AndWhere = 'WHERE ' . implode(' AND ', $conditions);
    }
    $_SESSION['export_conditions'] = $conditions; // Store conditions for export use
    
    $total_pricing_sum = 0; 
    $total_payment_sum = 0;  
    $total_discount = 0;

    ?>
<!-- Displaying Total Pricing Sum and Total Payment Sum before the list item -->


<?php
    $sql = "SELECT * FROM product $AndWhere ORDER BY pid DESC LIMIT $start, 10";

    $res = mysqli_query($con, $sql);

    if (mysqli_num_rows($res) === 0) {
        header('Content-Type: text/plain');
        echo '__NO_MORE_DATA__';
        exit;
    } else{

        $c = $start + 1;

        while ($rows = mysqli_fetch_assoc($res)) {
            $client_name = fetchUserName($con, $rows['pClient']);
            $fran_name = fetchUserName($con, $rows['pFranchiee']);
            $subFran_name = fetchUserName($con, $rows['pSubFranchiee']);
            $employee_name = !empty($rows['pEmployee']) && $rows['pEmployee'] != 0 ? fetchUserName($con, $rows['pEmployee']) : '';

            $clg_name = "";
            $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$rows["pCollege"]}'");
            if($clg_row = mysqli_fetch_assoc($clg_sql)){
                $clg_name = $clg_row["uname"];
            }

            $course_name = "";
            $course_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '{$rows["product"]}' ");
            while($course_row = mysqli_fetch_assoc($course_sql)){
                $course_name = $course_row["course_name"];
            }

            $pCat = "";
            $cat_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE sl_no = '{$rows["pCat"]}' ");
            while($cat_row = mysqli_fetch_assoc($cat_sql)){
                $pCat = $cat_row["cat_name"];
            }

            $pStatus = $rows["pStatus"];
            $statusName = '';

            if ($pStatus == 0) {
                $statusName = 'Pending';
            } elseif ($pStatus == 1) {
                $statusName = 'Running';
            } elseif ($pStatus == 2) {
                $statusName = 'Pass Out';
            } elseif ($pStatus == 3) {
                $statusName = 'Leave Course';
            } 
            
?>

<li class='clearfix' style='float: none;' id="<?php echo $rows['pid']; ?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-9 col-12 mb-2'>
                <div class="row">
                    <div class="col-md-7 col-12">
                        <a style='color:orange;font-size:17px;cursor:pointer;text-decoration:none;'
                            data-product='<?php echo $clg_name;?>' data-cat='<?php echo $pCat;?>'
                            data-fran='<?php echo $fran_name;?>' data-subFran='<?php echo $subFran_name;?>'
                            data-employee='<?php echo $employee_name;?>' data-date='<?php echo $rows["pCreateDate"];?>'
                            data-status='<?php echo $statusName;?>'>
                            <i class='fa fa-school' aria-hidden='true'></i> <b><?php echo $clg_name;?></b>
                        </a> (<b class="small"><i class='fa fa-chalkboard' style="color:orange;"></i>
                        </b><?php echo $course_name . ' (<i class="fa fa-shapes" style="color:orange;"></i>:' . $pCat . ')';?>)
                        <br>
                        <b class="small"><i class="fa fa-user" style="color:orange;"></i> <?php echo $client_name;?></b>
                        <br>
                        <b class="small"><i class="fa fa-network-wired" style="color:orange;"></i>
                            <?php echo $fran_name;?></b>
                        <?php if($subFran_name != ""){
                            ?>
                        <b class="small">|| <i class="fa fa-timeline" style="color:orange;"></i>
                            <?php echo $subFran_name;?></b>
                        <?php }?>
                        <br>
                        <b class="small"><i class='fa fa-clock' style="color:orange;"></i>
                        </b><?php echo $rows["pCreateDate"];?>
                    </div>
                    <div class="col-md-5 col-12">
                        <div class="row">
                            <div class="col-6">
                                <label for="status">Update Status:</label>
                                <select name="status" class="form-control form-control-sm"
                                    onchange="updateStatus(<?php echo $rows['pid']; ?>, this.value)">
                                    <option value="0" <?php if($pStatus == 0) echo 'selected'; ?>>Pending</option>
                                    <option value="1" <?php if($pStatus == 1) echo 'selected'; ?>>Running</option>
                                    <option value="2" <?php if($pStatus == 2) echo 'selected'; ?>>Pass Out</option>
                                    <option value="3" <?php if($pStatus == 3) echo 'selected'; ?>>Leave Course</option>
                                </select>
                            </div>
                            <!--<div class="col-6">
                                <label for="employee">Update Employee:</label>
                                <select name="employee" class="form-control form-control-sm" id="pemployee"
                                    onchange="updateEmployee(<?php echo $rows['pid']; ?>, this.value)">
                                    <?php if(!empty($employee_name)){?>
                                    <option value="<?php echo $rows['pEmployee'];?>"><?php echo $employee_name;?>
                                    </option>
                                    <?php }else{?>
                                    <option value="">Select Employee</option>
                                    <?php }?>
                                    <?php 
                                        $esql = "SELECT DISTINCT uname, uid FROM users WHERE utype = 'Employee' AND udisplay != 'disable' AND admin_ref = '$_SESSION[uref]' ORDER BY uname ASC";
                                        $eres = mysqli_query($con, $esql);
                                        while ($erow = mysqli_fetch_assoc($eres)) {
                                    ?>
                                    <option value="<?php echo $erow['uid']; ?>"><?php echo $erow['uname']; ?></option>
                                    <?php } ?>
                                </select>
                            </div>-->
                        </div>
                    </div>
                </div>
            </div>

            <div class='col-md-3 col-12'>
                <form action="" mehod="POST">
                    <div class="d-flex justify-content-between">
                        <button type="button" class="btn btn-primary btn-sm" data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadFinalDocumentModal(<?php echo $rows['pid']; ?>)">
                            Final Document
                        </button>

                        <button type="button" class="btn btn-secondary btn-sm" data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadViewProductModal(<?php echo $rows['pid']; ?>)">
                            <i class='fa fa-eye' aria-hidden='true'></i> View Course
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</li>

<?php
            $c++;
        }
        // mysqli_close($con);
    }
}
?>


<script>
document.getElementById('finalDocumentModal').addEventListener('hidden.bs.modal', function() {
    this.querySelector('.modal-body').innerHTML = '';
});

document.getElementById('viewProductModal').addEventListener('hidden.bs.modal', function() {
    this.querySelector('.modal-body').innerHTML = '';
});
</script>

<script>
// function updateStatus(productId, statusValue) {
//     console.log("Updating status:", productId, statusValue); // Debug line
//     var xhr = new XMLHttpRequest();
//     xhr.open("POST", "updateStatus.php", true);
//     xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//     xhr.onreadystatechange = function() {
//         if (xhr.readyState == 4) {
//             console.log("Response:", xhr.responseText); // Debug
//         }
//     };
//     xhr.send("product_id=" + productId + "&status=" + statusValue);
// }


function updateEmployee(productId, employeeValue) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "updateEmployee.php", true); // This is the PHP file that will update the employee
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Optionally show success message
            console.log(xhr.responseText);
        }
    };
    xhr.send("product_id=" + productId + "&employee=" + employeeValue);
}
</script