<?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
    
    // Initial calculations
    $total_pricing_sum = 0;
    $total_payment_sum = 0;
    $total_discount = 0;

    // Only fetch and display summary values if it's the first load
    if ($start == 0) {
?>

<?php
    }
    
    // Fetch product data
    $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_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"];
            }

            $pStatus = $rows["pStatus"];
            $statusName = '';
            switch ($pStatus) {
                case 0: $statusName = 'Pending'; break;
                case 1: $statusName = 'Running'; break;
                case 2: $statusName = 'Pass Out'; break;
                case 3: $statusName = 'Leave Course'; break;
            }
?>
<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-10 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>
                        <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-list-alt' style="color:orange;"></i> </b>
                        <?php echo $course_name . ' (' . $pCat . ')'?>
                        &nbsp; &nbsp;
                        &nbsp;
                        <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="mb-2">
                            <b class="small">Work Status : <?php echo $statusName;?></b>
                        </div>
                    </div>
                </div>
            </div>

            <div class='col-md-2 col-12'>
                <form action="" method="POST">
                    <div class="text-center d-flex d-lg-block justify-content-between">
                        <?php if($statusName == 'Completed'){ ?>
                        <button type="button" class="btn btn-primary btn-sm mb-2" data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadFinalDocumentModal(<?php echo $rows['pid']; ?>)">
                            Final Document
                        </button> <br>
                        <?php } ?>

                        <button type="button" class="btn btn-secondary btn-sm mb-2"
                            data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadViewProductModal(<?php echo $rows['pid']; ?>)">
                            <i class='fa fa-eye' aria-hidden='true'></i> View Details
                        </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>