<?php
    session_start();
    include "../db.php";
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>
<style>
.date-label-group {
    position: relative;
}

.date-label-group label {
    position: absolute;
    top: -6px;
    left: 3px;
    background: #fff;
    font-size: 0.55rem;
    padding: 0 4px;
    color: #6c757d;
    z-index: 1;
}

.date-label-group input[type="date"] {
    padding-bottom: 4px;
}
</style>

<body>
    <!--  Header -->
    <?php include "include/header.php";?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <ul class="search-details">
                            <li>
                                <h4 class="text-gray-800 m-0">Work List</h4>
                            </li>
                            <li>
                                <div class="date-label-group">
                                    <label for="startDate">Start Date</label>
                                    <input type="date" class="form-control form-control-sm" id="startDate"
                                        placeholder="Start Date">
                                </div>
                            </li>
                            <li>
                                <div class="date-label-group">
                                    <label for="endDate">End Date</label>
                                    <input type="date" class="form-control form-control-sm" id="endDate"
                                        placeholder="End Date">
                                </div>
                            </li>
                            <li>
                                <select name="status" class="form-control form-control-sm" id="pststus">
                                    <option value="">Status</option>
                                    <option value="0">Pending</option>
                                    <option value="1">Running</option>
                                    <option value="2">Pass Out</option>
                                    <option value="3">Leave Course</option>
                                </select>
                            </li>
                            <li>
                                <select name="college" class="form-control form-control-sm" id="college">
                                    <option value="">Select College</option>
                                    <?php 
                                        $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE utype = 'College' AND uStatus = '1' AND udisplay != 'disable' ORDER BY uname ASC");
                                        while($clg_row = mysqli_fetch_assoc($clg_sql)){
                                    ?>
                                    <option value="<?php echo $clg_row["uid"]; ?>"><?php echo $clg_row["uname"]; ?>
                                    </option>
                                    <?php } ?>
                                </select>
                            </li>
                            <li>
                                <div class="form-group">
                                    <select name="course" class="form-control form-control-sm" id="course">
                                        <option value="">Select College First</option>
                                        <!-- Courses will be dynamically loaded here -->
                                    </select>
                                </div>
                            </li>
                            <li>
                                <div class="form-group">
                                    <input type="text" list="First" class="form-control form-control-sm"
                                        id="FirstFilterValue" placeholder="Search By Associate">
                                    <datalist id="First">
                                        <?php 
                                            $sql = "SELECT DISTINCT uname FROM users  WHERE utype = 'Associate'  AND udisplay !='disable' AND admin_ref = '$_SESSION[uref]' ORDER BY uname ASC";
                                            $res = mysqli_query($con,$sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option value="<?php echo $row['uname']; ?>">
                                            <?php echo $row['uname']; ?></option>
                                        <?php } ?>
                                    </datalist>
                                </div>
                                <input type="hidden" class="form-control" value="" id="FirstFilterValue">
                            </li>
                            <li>
                                <div class="d-flex">
                                    <div class="form-group">
                                        <input type="text" list="Second" class="form-control form-control-sm"
                                            id="SecondFilterValue" placeholder="Employee">
                                        <datalist id="Second">
                                            <?php 
                                                $esql = "SELECT DISTINCT uname 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['uname']; ?>">
                                                <?php echo $erow['uname']; ?></option>
                                            <?php } ?>
                                        </datalist>
                                    </div>
                                    <input type="hidden" class="form-control" value="" id="SecondFilterValue">
                                    <button type="button" id="filter" class="btn btn-primary mb-2 btn-sm"><i
                                            class="fa fa-search"></i>
                                    </button>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div class="card-body">
                        <div class="row justify-content-center">
                            <div class="col-md-12">
                                <div class="row justify-content-center d-none"
                                    style="font-weight: bold; margin-bottom: 10px;" id="summary-section">
                                    <div class="col-md-10 d-flex justify-content-between">
                                    </div>
                                    <div class="col-md-2">
                                        <div class="text-end mb-3">
                                            <a href="export-productList.php" class="btn btn-success">Download Excel</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                        <div class="ph-item">
                                        <div cl ass="ph-test">
                                        <div class="ph-row">
                                        <div class="ph-col-12 big"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        </div>
                                        </div>
                                        </div>
                                        </li>';
                                        }
                                    ?>
                                </ul>
                            </div>

                            <!-- loader -->
                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="text-center mt-3" id="load-more-container">
                                <button id="loadMoreBtn" class="btn btn-info btn-sm text-white">Load More</button>
                                <div id="endMessage" class="text-muted mt-2" style="display: none;">End of result</div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>


    <?php include "include/js.php"; ?>


    <!-- Final Document Modal -->
    <div class="modal fade" id="finalDocumentModal" tabindex="-1" role="dialog"
        aria-labelledby="finalDocumentModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Upload Final Document</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- Content will be loaded dynamically here -->
                </div>
            </div>
        </div>
    </div>

    <!-- View Product Modal -->
    <div class="modal fade" id="viewProductModal" tabindex="-1" role="dialog" aria-labelledby="viewProductModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Course Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- Content will be loaded dynamically here -->
                </div>
            </div>
        </div>
    </div>

    <script>
    // For Final Document Modal
    function loadFinalDocumentModal(pid) {
        $.ajax({
            url: 'get-final-document.php',
            type: 'POST',
            data: {
                pid: pid
            },
            dataType: 'json',
            success: function(response) {
                if (response.html) {
                    $('#finalDocumentModal .modal-body').html(response.html);
                    const modal = new bootstrap.Modal(document.getElementById('finalDocumentModal'));
                    modal.show();
                } else {
                    alert('No content returned.');
                }
            },
            error: function() {
                alert('Error loading document.');
            }
        });
    }

    // For View Product Modal
    function loadViewProductModal(pid) {
        $.ajax({
            url: 'get-view-product.php',
            type: 'POST',
            data: {
                pid: pid
            },
            dataType: 'json',
            success: function(response) {
                if (response.html) {
                    $('#viewProductModal .modal-body').html(response.html);
                    const modal = new bootstrap.Modal(document.getElementById('viewProductModal'));
                    modal.show();
                } else {
                    alert('No content returned.');
                }
            },
            error: function() {
                alert('Error loading product details.');
            }
        });
    }
    </script>
    <script>
    $(document).ready(function() {
        window.updateStatus = function(productId, statusValue) {
            console.log("Updating status:", productId, statusValue); // Debug
            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);
                }
            };
            xhr.send("product_id=" + productId + "&status=" + statusValue);
        };
    });
    </script>


    <script>
    $(document).ready(function() {
        $('#college').change(function() {
            var college_id = $(this).val();

            if (college_id != '') {
                $.ajax({
                    url: 'fetch_courses_by_college.php',
                    type: 'POST',
                    data: {
                        college_id: college_id
                    },
                    success: function(response) {
                        $('#course').html(response);
                    }
                });
            } else {
                $('#course').html('<option value="">Select College First</option>');
            }
        });
    });
    </script>

    <script>
    $(document).ready(function() {
        let load_filter_flag = 0;
        let load_flag = 0;

        let FirstFilterValue = '';
        let SecondFilterValue = '';
        let StatusValue = '';
        let college = '';
        let course = '';
        let StartDate = '';
        let EndDate = '';

        // Load filtered data
        function loadFilteredData(start, scrollToNew = false) {
            $.ajax({
                url: 'view-productList-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    SecondFilterValue,
                    StatusValue,
                    StartDate,
                    EndDate,
                    college,
                    course,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    result = result.trim();
                    const tempContainer = $('<div>').html(result);
                    const newItems = tempContainer.find('li');

                    if (result === '__NO_MORE_DATA__' || newItems.length === 0) {
                        $('#filter-table-data').html(`
                        <li class="text-center text-muted py-3">
                            <i class="fa fa-info-circle"></i> No results match your filters.
                        </li>
                    `);
                        $('#full-table').remove();
                        $('#filter-table').show();
                        $('#loadMoreBtn').hide();
                        $('#endMessage').hide();
                        $('#summary-section').addClass('d-none'); // hide summary
                        return;
                    }

                    if (start === 0) {
                        $('#filter-table-data').html(newItems);
                        $('#full-table').remove();
                        $('#filter-table').show();
                        $('#calculation').show();

                        $('#summary-section').removeClass('d-none'); // show summary
                    } else {
                        $('#filter-table-data').append(newItems);
                        if (scrollToNew && newItems.length > 0) {
                            $('html, body').animate({
                                scrollTop: newItems.first().offset().top - 100
                            }, 600);
                        }
                    }

                    load_filter_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        // Load unfiltered data
        function loadMore(start, scrollToNew = false) {
            $.ajax({
                url: 'view-productList-Ajax.php',
                type: 'POST',
                data: {
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    result = result.trim();
                    const tempContainer = $('<div>').html(result);
                    const newItems = tempContainer.find('li');

                    if (result === '__NO_MORE_DATA__' || newItems.length === 0) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                        return;
                    }

                    $('#full-table-data').append(newItems);

                    if (scrollToNew && newItems.length > 0) {
                        $('html, body').animate({
                            scrollTop: newItems.first().offset().top - 100
                        }, 600);
                    }

                    load_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        // Initial load
        loadMore(load_flag);

        // Filter button click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            StatusValue = $('#pststus').val();
            StartDate = $('#startDate').val();
            EndDate = $('#endDate').val();
            college = $('#college').val();
            course = $('#course').val();

            load_filter_flag = 0;
            load_flag = 0;

            $('#loadMoreBtn').show();
            $('#endMessage').hide();
            $('#summary-section').addClass('d-none'); // hide initially

            if (
                FirstFilterValue || SecondFilterValue || StatusValue ||
                StartDate || EndDate || college || course
            ) {
                loadFilteredData(load_filter_flag);
            } else {
                alert('Please select at least one filter option.');
                $('#full-table').show();
                $('#filter-table').hide();
                $('#summary-section').addClass('d-none');
            }
        });

        // Load More button click
        $("#loadMoreBtn").click(function() {
            if (load_filter_flag > 0 || $('#filter-table').is(":visible")) {
                loadFilteredData(load_filter_flag, true);
            } else {
                loadMore(load_flag, true);
            }
        });
    });
    </script>


</body>

</html>