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

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

    if (!empty($_POST['FirstFilterValue'])) {
        $AndWhere .= "AND product ='" . mysqli_real_escape_string($con, $_POST['FirstFilterValue']) . "' ";
    }

    $sql = "SELECT * FROM product WHERE pClient = '{$clientId}' $AndWhere ORDER BY pid DESC LIMIT $start, 10";
    $res = mysqli_query($con, $sql);

    if ($total_rows = mysqli_num_rows($res) > 0) {
        $c = $start + 1;

        while ($rows = mysqli_fetch_assoc($res)) {
            $m_sql = "SELECT uname, uref FROM users WHERE uref_code = '" . mysqli_real_escape_string($con, $rows['pFranchiee']) . "'";
            $m_run = mysqli_query($con, $m_sql);
            $m_rows = mysqli_fetch_assoc($m_run);

            $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_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '$rows[pBatch]'");
            if($batch_row = mysqli_fetch_assoc($batch_sql)){
                $batch_name = $batch_row["batch_title"];
            } else{
                $batch_name = "No Batch Found";
            }

            $paymentStyle = '';

            //Get docunent upload status
            $docStyle = '';
            // $doc_sql = mysqli_query($con, "SELECT * FROM documents WHERE dProduct = '$rows[pid]' ");
            // if(mysqli_num_rows($doc_sql) == 0){
            //     $docStyle = "btn-danger blink_me";
            // }

            $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;'>
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-5'>
                <a style='color:orange;font-size:17px;cursor:pointer;' class='viewDetails' data-toggle='modal'>
                    <i class='fa fa-user' aria-hidden='true'></i> <b><?php echo $clg_name;?></b>
                </a>
                <br>
                <b><i class='fa fa-list-alt'></i> </b><?php echo $course_name . ' (' . $pCat . ') [ Batch: ' . $batch_name. ']';?>
                <br>
                <b class="small">Status : <?php echo $statusName;?></b>
            </div>
            <div class="col-md-5">
                <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-2'>
                <div class="d-flex justify-content-between align-items-center">
                    <a href='view-product.php?client_id=<?php echo $rows["pClient"];?>&view_id=<?php echo $rows["pid"];?>'
                        class='m-2 btn btn-primary btn-sm' title='Click to View'><i class='fa fa-eye'
                            aria-hidden='true'></i>
                    </a>
                    <?php
                    if(empty($rows["pFinalDocument"])){
                    ?>
                    <a href='view-product.php?client_id=<?php echo $rows["pClient"];?>&edit_id=<?php echo $rows["pid"];?>'
                        class='m-2 btn btn-success btn-sm' title='Click to Edit'><i class='fa fa-edit'
                            aria-hidden='true'></i>
                    </a>
                    <a href='view-product.php?client_id=<?php echo $rows["pClient"];?>&del_id=<?php echo $rows["pid"];?>'
                        class='delete m-2 btn btn-danger btn-sm' title='Click to Delete'><i class='fa fa-trash'
                            aria-hidden='true'></i>
                    </a>
                    <?php } else { ?>
                    <!-- Button to trigger modal -->
                    <button class='m-2 btn btn-primary btn-sm' title='Click to View' data-bs-toggle="modal"
                        data-bs-target="#documentModal"
                        onclick="viewDocument('<?php echo $rows['pFinalDocument']; ?>')">
                        <i class='fa fa-download' aria-hidden='true'></i> Final Document
                    </button>

                    <!-- Modal structure -->
                    <div class="modal fade" id="documentModal" tabindex="-1" aria-labelledby="documentModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="documentModalLabel">View Final Document</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                        aria-label="Close"></button>
                                </div>
                                <div class="modal-body" id="documentContent">
                                    <!-- Content (image, PDF, etc.) will be dynamically loaded here -->
                                </div>
                                <div class="modal-footer">
                                    <a id="downloadButton" href="#" class="btn btn-success" download>Download</a>
                                    <button type="button" class="btn btn-secondary"
                                        data-bs-dismiss="modal">Close</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <script>
                    function viewDocument(fileName) {
                        const filePath = `../upload/finalDoc/${fileName}`; // Path to the file in the upload folder
                        const fileExtension = fileName.split('.').pop().toLowerCase();
                        let content = '';

                        // Dynamically determine file type
                        if (fileExtension === 'pdf') {
                            content = `<embed src="${filePath}" type="application/pdf" width="100%" height="500px" />`;
                        } else if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension)) {
                            content = `<img src="${filePath}" alt="Document Image" class="img-fluid" />`;
                        } else {
                            content = `<p>Cannot preview this file type: ${fileExtension}</p>`;
                        }

                        // Set the content inside the modal body
                        document.getElementById('documentContent').innerHTML = content;

                        // Update download link
                        document.getElementById('downloadButton').setAttribute('href', filePath);
                    }
                    </script>

                    <?php }?>
                </div>
            </div>
        </div>
    </div>
</li>

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


<script>
$(document).ready(function() {
    $('.viewDetails').on('click', function(e) {
        e.preventDefault(); // Prevent default anchor tag action

        var name = $(this).data('name');
        $('#modalName').text(name);

        var state = $(this).data('state');
        $('#modalState').text(state);

        var dist = $(this).data('dist');
        $('#modalDist').text(dist);

        var pin = $(this).data('pin');
        $('#modalPin').text(pin);

        var userid = $(this).data('userid');
        $('#modalId').text(userid);

        var pass = $(this).data('pass');
        $('#modalPass').text(pass);

        var classs = $(this).data('classs');
        $('#modalClasss').text(classs);

        var qualification = $(this).data('qualification');
        $('#modalqualification').text(qualification);

        var address = $(this).data('address');
        $('#modalAddress').text(address);

        var date = $(this).data('date');
        $('#modalDate').text(date);

        $('#studentDetailsModal').modal('show'); // Open the modal
    });

});
</script>