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

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

    $emp_id = $_SESSION["uid"];

    // Initialize an array to hold filter conditions
    $conditions = [];
    
    $conditions[] = "pStatus = '" . $_POST['StatusValue'] . "'";

    $conditions[] = "pEmployee = '" . $emp_id . "'";

    include("include/productListFilter.php");

    // Build the WHERE clause
    $whereClause = !empty($conditions) ? " AND " . implode(' AND ', $conditions) : "";
    
    $_SESSION['export_conditions'] = $conditions; // Store conditions for export use
    
    $total_pricing_sum = 0; 
    $total_payment_sum = 0;  
    $total_discount = 0;

    // Secure the session user ID
    $userId = mysqli_real_escape_string($con, $_SESSION['uid']);
    
    // Ensure $start is an integer to prevent SQL injection
    $start = isset($start) ? (int) $start : 0;
    ?>

<?php
    $sql = "SELECT * FROM product WHERE pEmployee = '$userId' $whereClause 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_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_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"];
            }
            $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"];
            }
            
            $batch_name = '';
            $batch_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '{$rows["pBatch"]}' ");
            while($batch_row = mysqli_fetch_assoc($batch_sql)){
                $batch_name = $batch_row["batch_title"];
            }

            $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';
            }

            
            $paid = 0;
            $paid_sql = mysqli_query($con, "SELECT sb_amount FROM student_bill WHERE sb_college = '{$rows["pCollege"]}' AND sb_course = '{$rows["pid"]}' AND sb_dept = '{$rows["pCat"]}' AND sb_for = '$clientId' AND (sb_type = 'Bill' OR sb_type = '') AND sb_recycle = '1'");

            if (mysqli_num_rows($paid_sql) > 0) {
                while ($paid_row = mysqli_fetch_assoc($paid_sql)) {
                    $paid += floatval($paid_row["sb_amount"]);
                }
            }

            // Ensure pAmount is numeric
            $pAmount = isset($rows["pAmount"]) && is_numeric($rows["pAmount"]) ? floatval($rows["pAmount"]) : 0;

            $pending = $pAmount - $paid;
            
?>

<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-5 col-12 mb-2'>
                <div class="row">
                    <div class="col-md-12 col-12">
                        <a style='color:orange;font-size:17px;cursor:pointer;text-decoration:none;'
                            data-product='<?php echo $course_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-chalkboard' aria-hidden='true'></i>
                            <b><?php echo $course_name . '[ ' . $batch_name . '] ';?></b>
                        </a>
                        <br>
                        <b><i class='fa fa-shapes' style="color:orange;"></i>
                        </b><?php echo $pCat . ' [<i class="fa fa-school" style="color:orange;"></i>' . $clg_name . ']';?>
                        <br>
                        <i class="fa fa-user" style="color:orange;"></i> <?php echo $client_name;?>
                        <br>
                        <b><i class="fa fa-network-wired" style="color:orange;"></i> <?php echo $fran_name;?></b>
                        <?php if($subFran_name != ""){
                            ?>
                        <b>|| <i class="fa fa-timeline" style="color:orange;"></i> <?php echo $subFran_name;?></b>
                        <?php }?>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card p-1 rounded">
                    <div class="d-flex justify-content-between">
                        <b class="small">Enrolement Date: <?php echo $rows["pCreateDate"];?></b>
                        <b class="small">Course Fees: <i class="fa fa-inr"></i> <?= $pAmount?></b>
                    </div>
                    <div class="d-flex justify-content-between">
                        <b class="small">Paid Fees: <i class="fa fa-inr"></i> <?= $paid?></b>
                        <b class="small">Due: <i class="fa fa-inr"></i> <?= $pending?></b>
                    </div>
                </div>
            </div>

            <div class='col-md-3 col-12'>
                <form action="" mehod="POST">
                    <div class="mb-2 d-flex">
                        <select name="status" class="form-control form-control-sm" id="pststus"
                            onchange="updateStatus(<?php echo $rows['pid']; ?>, this.value)">
                            <option value="<?php echo $pStatus;?>"><?php echo $statusName;?></option>
                            <option value="0" <?php if($pStatus == 0) echo 'disabled'; ?>>Pending</option>
                            <option value="1" <?php if($pStatus == 1) echo 'disabled'; ?>>Running</option>
                            <option value="2" <?php if($pStatus == 2) echo 'disabled'; ?>>Pass Out</option>
                            <option value="3" <?php if($pStatus == 3) echo 'disabled'; ?>>Leave Course</option>
                        </select>
                    </div>
                    <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 Courses
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</li>

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


<script>
$('#finalDocumentModal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal').find('.modal-body').empty();
});

$('#viewProductModal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal').find('.modal-body').empty();
});

// Load Final Document Modal
function loadFinalDocumentModal(pid) {
    $.ajax({
        url: 'get-final-document.php',
        type: 'POST',
        data: {
            pid: pid
        },
        dataType: 'json',
        success: function(response) {
            $('#finalDocumentModal .modal-body').html(response.html);
            $('#finalDocumentModal').modal('show');
        },
        error: function() {
            alert('Error loading document.');
        }
    });
}

// Load View Product Modal
function loadViewProductModal(pid) {
    $.ajax({
        url: 'get-view-product.php',
        type: 'POST',
        data: {
            pid: pid
        },
        dataType: 'json',
        success: function(response) {
            $('#viewProductModal .modal-body').html(response.html);
            $('#viewProductModal').modal('show');
        },
        error: function() {
            alert('Error loading product details.');
        }
    });
}
</script>

