<?php
    include "../db.php";
    require '../auth.php';
    restrictAccess(['master_admin']);
    date_default_timezone_set('Asia/Kolkata');

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

    $vendor = "";
    if(isset($_GET["vendor_id"])){
        $vendor_id = $_GET["vendor_id"];
        $vendor_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_id = '$vendor_id'");
        if($vendor_row = mysqli_fetch_assoc($vendor_sql)){
            $vendor = $vendor_row["wp_name"];
        }
    }
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <?php include "include/header.php"; ?>

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">

                <?php 
                $getDetails_sql = mysqli_query($con, "SELECT * FROM work_student WHERE ws_vendorId = '$vendor_id' AND ws_workId = '{$_GET['work_id']}'");

                if(mysqli_num_rows($getDetails_sql) > 0){
                    $batch_ids = [];
                    $assigned_students = [];
                    while($ws = mysqli_fetch_assoc($getDetails_sql)){
                        $batch_ids[] = $ws['ws_batchId'];
                        $assigned_students[] = $ws['ws_student'] . "|" . $ws['ws_batchId'];
                    }
                    $batch_ids = array_unique($batch_ids);
                ?>

                <div class="card my-3">
                    <div class="card-header">Student List</div>
                    <div class="card-body">

                        <?php foreach($batch_ids as $batch_id): ?>
                        <?php 
                            // Fetch course + batch details
                            $batch_q = mysqli_query($con, "
                                SELECT pBatch, cc.course_name 
                                FROM product p
                                JOIN clg_course cc ON cc.sl_no = p.product
                                WHERE p.pBatch = '$batch_id'
                                LIMIT 1
                            ");
                            $batch_info = mysqli_fetch_assoc($batch_q);
                            $batch_name = $batch_info['pBatch'] ?? $batch_id;
                            $course_name = $batch_info['course_name'] ?? "Unknown Course";

                            $batch_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '$batch_name' ");
                            if($batch_row = mysqli_fetch_assoc($batch_sql)){
                                $batch_name = $batch_row["batch_title"];
                            }

                            $query = mysqli_query($con, "SELECT DISTINCT pClient FROM product WHERE pBatch='$batch_id'");
                            if(mysqli_num_rows($query) > 0): 
                        ?>
                        <form class="clientForm_existing mb-4" action="update_clients.php" method="POST">
                            <input type="hidden" name="work_id" value="<?= $_GET['work_id'] ?>">
                            <input type="hidden" name="vendor_id" value="<?= $vendor_id ?>">
                            <input type="hidden" name="batch_id" value="<?= $batch_id ?>">

                            <!-- New Course + Batch header -->
                            <div class="mb-3">
                                <h5 class="text-primary">
                                    Course: <?= htmlspecialchars($course_name) ?> &nbsp; <span class="h6 text-muted">
                                        (Batch: <?= htmlspecialchars($batch_name) ?>)
                                    </span>
                                </h5>

                            </div>

                            <div class="row">
                                <?php while($row = mysqli_fetch_assoc($query)): 
                                    $client_id = $row['pClient'];
                                    $client_q = mysqli_query($con, "SELECT uid, uname, uemail, ucontact FROM users WHERE uid='$client_id'");
                                    $client = mysqli_fetch_assoc($client_q);
                                    if(!$client) continue;
                                    $checked = in_array($client['uid'] . "|" . $batch_id, $assigned_students) ? "checked" : "";
                                ?>
                                <div class="col-md-3 mb-3">
                                    <div class="card p-2 shadow-sm">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="clients[]"
                                                value="<?= $client['uid'].'|'.$batch_id ?>"
                                                id="client_<?= $client['uid'] ?>" <?= $checked ?>>
                                            <label class="form-check-label fw-bold" for="client_<?= $client['uid'] ?>">
                                                <?= $client['uname'] ?>
                                            </label>
                                        </div>
                                        <p class="mb-0"><strong>Email:</strong> <?= $client['uemail'] ?></p>
                                        <p class="mb-0"><strong>Mobile:</strong> <?= $client['ucontact'] ?></p>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>

                            <button type="submit" class="btn btn-primary my-2">Update Students</button>
                        </form>
                        <?php endif; ?>
                        <?php endforeach; ?>



                        <!-- Add More Students Section -->
                        <button type="button" id="addMoreBtn" class="btn btn-success mt-2"><i class="fa fa-plus"></i>
                            Add
                            More Students</button>

                        <div id="addMoreSection" class="mt-3" style="display:none;">
                            <div class="row g-2 mb-3">
                                <div class="col-md-3">
                                    <input type="text" list="third" id="course_search"
                                        class="form-control form-control-sm" placeholder="Enter Course Name">
                                    <input type="hidden" id="selected_pid">
                                    <datalist id="third">
                                        <?php
                                        $res = mysqli_query($con, "SELECT cc.course_name, MIN(p.pid) AS pid FROM product p JOIN clg_course cc ON cc.sl_no = p.product GROUP BY cc.course_name ORDER BY cc.course_name ASC");
                                        $coursePidMap = [];
                                        while ($row = mysqli_fetch_assoc($res)) {
                                            $course_name = htmlspecialchars($row['course_name']);
                                            $pid = htmlspecialchars($row['pid']);
                                            $coursePidMap[$course_name] = $pid;
                                            echo '<option value="'.$course_name.'">'.$course_name.'</option>';
                                        }
                                        ?>
                                    </datalist>
                                </div>
                                <div class="col-md-3">
                                    <select name="batch" id="batch" class="form-control form-control-sm">
                                        <option value="">Select Course First</option>
                                    </select>
                                </div>
                            </div>

                            <form id="clientForm">
                                <input type="hidden" id="work_id" name="work_id" value="<?= $_GET['work_id'] ?>">
                                <input type="hidden" id="vendor_id" name="vendor_id" value="<?= $_GET['vendor_id'] ?>">
                                <div id="clientTable"></div>
                                <p id="displayed-text">Select Course and batch to add students.</p>
                                <button type="submit" id="submit_btn" class="btn btn-primary mt-2"
                                    style="display:none;">Submit Selected</button>
                            </form>
                        </div>
                    </div>
                </div>

                <?php } else { ?>
                <!-- First-time Add Student (no existing students) -->
                <div class="card mt-3 mb-3">
                    <div class="card-header">Add Student</div>
                    <div class="card-body">
                        <div class="row g-2 mb-3">
                            <div class="col-md-3">
                                <input type="text" list="third" id="course_search" class="form-control form-control-sm"
                                    placeholder="Enter Course Name">
                                <input type="hidden" id="selected_pid">
                                <datalist id="third">
                                    <?php
                                    $res = mysqli_query($con, "SELECT cc.course_name, MIN(p.pid) AS pid FROM product p JOIN clg_course cc ON cc.sl_no = p.product GROUP BY cc.course_name ORDER BY cc.course_name ASC");

                                    $coursePidMap = [];
                                    while ($row = mysqli_fetch_assoc($res)) {
                                        $course_name = htmlspecialchars($row['course_name']);
                                        $pid = htmlspecialchars($row['pid']);
                                        $coursePidMap[$course_name] = $pid;
                                        echo '<option value="'.$course_name.'">'.$course_name.'</option>';
                                    }
                                    ?>
                                </datalist>
                            </div>
                            <div class="col-md-3">
                                <select name="batch" id="batch" class="form-control form-control-sm">
                                    <option value="">Select Course First</option>
                                </select>
                            </div>
                        </div>

                        <form id="clientForm">
                            <input type="hidden" id="work_id" name="work_id" value="<?= $_GET['work_id'] ?>">
                            <input type="hidden" id="vendor_id" name="vendor_id" value="<?= $_GET['vendor_id'] ?>">
                            <div id="clientTable"></div>
                            <p id="displayed-text">Select Course and batch to add students.</p>
                            <button type="submit" id="submit_btn" class="btn btn-primary mt-2"
                                style="display:none;">Submit Selected</button>
                        </form>
                    </div>
                </div>
                <?php } ?>

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

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

    <script>
    const coursePidMap = <?= json_encode($coursePidMap ?? []) ?>;

    document.getElementById("addMoreBtn")?.addEventListener("click", () => {
        let section = document.getElementById("addMoreSection");
        section.style.display = (section.style.display === "none") ? "block" : "none";
    });

    document.getElementById('course_search')?.addEventListener('input', function() {
        const selectedCourse = this.value;
        const pid = coursePidMap[selectedCourse] || '';
        document.getElementById('selected_pid').value = pid;
        if (pid) {
            fetchBatches(pid);
        } else {
            document.getElementById('batch').innerHTML = '<option value="">Select Course First</option>';
        }
    });

    function fetchBatches(course_id) {
        $.post("fetch_batch.php", {
            course_id
        }, function(response) {
            $("#batch").html(response);
        }).fail(() => {
            $("#batch").html('<option value="">Failed to load batches</option>');
        });
    }

    $("#batch").change(function() {
        let b_id = $(this).val();
        if (b_id) {
            $.post("fetch_clients.php", {
                batch_id: b_id
            }, function(response) {
                $("#clientTable").html(response);
                $("#submit_btn").show();
                $("#displayed-text").hide();
            });
        } else {
            $("#clientTable").html("");
            $("#submit_btn").hide();
        }
    });

    $("#clientForm").on("submit", function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        $.post("save_clients.php?work_id=" + $("#work_id").val() + "&vendor_id=" + $("#vendor_id").val(),
            formData,
            function(res) {
                alert(res);
                location.reload();
            }).fail(() => alert("Something went wrong!"));
    });
    </script>
</body>

</html>