<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Employee']);
    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();
    }
    // Get the status from the URL, if available
    $statusFromUrl = isset($_GET['status']) ? $_GET['status'] : '';
    
    if($statusFromUrl == 'Pending'){
        $statusId = '0';
    }elseif($statusFromUrl == 'Running'){
        $statusId = '1';
    }elseif($statusFromUrl == 'Pass Out'){
        $statusId = '2';
    }elseif($statusFromUrl == 'Leave Course'){
        $statusId = '3';
    }


    $statusOptions = [
        '0' => 'Pending',
        '1' => 'Running',
        '2' => 'Pass Out',
        '3' => 'Leave Course'
    ];
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

<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 Activity List</h4>
                            </li>
                            <br class="d-sm-block d-lg-none">
                            <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="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="d-flex">
                                    <div class="form-group">
                                        <input type="text" list="First" class="form-control form-control-sm"
                                            id="FirstFilterValue" placeholder="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">

                                    <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">
                            <!-- Status Navbar -->
                            <div class="col-12">
                                <div class="row p-2">
                                    <div class="col-md-4">
                                        <ul class="status-nav mb-3">
                                            <?php foreach ($statusOptions as $statusValue => $statusName): ?>
                                            <li>
                                                <a class="btn btn-warning <?php echo ($statusId === (string)$statusValue) ? 'active' : ''; ?>"
                                                    href="productList-status.php?status=<?php echo $statusName; ?>">
                                                    <?php echo $statusName; ?>
                                                </a>
                                            </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </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 my-3">
                                <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;">
                                    <i class="fa fa-check-circle"></i> No more data to load.
                                </div>
                                <div id="loader" style="display:none;">
                                    <i class="fa fa-spinner fa-spin"></i> Loading...
                                </div>
                            </div>

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

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

    <!-- Modal Structure -->
    <div class="modal fade" id="adminDetailsModal" data-bs-backdrop="static" tabindex="-1" role="dialog"
        aria-labelledby="modelTitleId" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 style="color:orange;font-size: 20px"> <i class="fa fa-school"></i> <span id="modalName"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 col-6 text-end">
                            <h5 class="modal-css">Product Name:</h5>
                            <h5 class="modal-css">Category:</h5>
                            <h5 class="modal-css">Associte Name:</h5>
                            <h5 class="modal-css">Sub Associte Name:</h5>
                            <h5 class="modal-css">Employee Name:</h5>
                            <h5 class="modal-css">Student Name:</h5>
                            <h5 class="modal-css">Status:</h5>
                            <h5 class="modal-css">Date:</h5>
                            <h5 class="modal-css">Referred By:</h5>
                        </div>
                        <div class="col-md-6 col-6">
                            <h5 class="modal-id" id="modalProductName"></h5>
                            <h5 class="modal-id" id="modalPCat"></h5>
                            <h5 class="modal-id" id="modalFranName"></h5>
                            <h5 class="modal-id" id="modalSubFranName"></h5>
                            <h5 class="modal-id" id="modalEmployeeName"></h5>
                            <h5 class="modal-id" id="modalClientName"></h5>
                            <h5 class="modal-id" id="modalStatusName"></h5>
                            <h5 class="modal-id" id="modalDate"></h5>
                            <h5 class="modal-id" id="modalRef"></h5>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 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">Courses 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>

    <?php include "include/js.php"; ?>
    <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() {
        var load_filter_flag = 0;
        var load_flag = 0;

        var FirstFilterValue = '';
        var college = '';
        var course = '';
        var CategoryValue = '';
        var StatusValue = '<?php echo $statusId; ?>';
        var StartDate = '';
        var EndDate = '';

        // Load initial unfiltered data
        loadMore(load_flag);

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

            load_filter_flag = 0;
            load_flag = 0;

            if (FirstFilterValue || college || course || StatusValue || StartDate || EndDate) {
                $.ajax({
                    url: 'productList-status-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue,
                        college,
                        course,
                        StatusValue,
                        CategoryValue,
                        StartDate,
                        EndDate,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);

                        const newItems = $('<div>').html(result).find('li');
                        load_filter_flag += newItems.length;

                        if (newItems.length < 10) {
                            $('#loadMoreBtn').hide();
                            $('#endMessage').show();
                        } else {
                            $('#loadMoreBtn').show();
                            $('#endMessage').hide();
                        }
                    },
                    complete: function() {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select at least one option.');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        // Load More Filtered
        function loadMoreFilter(start) {
            $.ajax({
                url: 'productList-status-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    college,
                    course,
                    StatusValue,
                    CategoryValue,
                    StartDate,
                    EndDate,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    const newItems = $('<div>').html(result).find('li');
                    $('#filter-table-data').append(newItems);
                    load_filter_flag += newItems.length;

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

        // Load More Unfiltered
        function loadMore(start) {
            $.ajax({
                url: 'productList-status-Ajax.php',
                type: 'POST',
                data: {
                    StatusValue: StatusValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    const newItems = $('<div>').html(result).find('li');
                    $('#full-table-data').append(newItems);
                    load_flag += newItems.length;

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

        // Load More Button
        $('#loadMoreBtn').click(function() {
            if ($('#filter-table').is(':visible')) {
                loadMoreFilter(load_filter_flag);
            } else {
                loadMore(load_flag);
            }
        });
    });
    </script>
    <script>
    function updateStatus(productId, statusValue) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "updateStatus.php", true); // This is the PHP file that will update the database
        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 + "&status=" + statusValue);
    }
    </script>

</body>

</html>