<?php
include "../db.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['work_id']) || !isset($_POST['vendor_id']) || !isset($_POST['batch_id'])) {
        die("Invalid Request");
    }

    $work_id   = mysqli_real_escape_string($con, $_POST['work_id']);
    $vendor_id = mysqli_real_escape_string($con, $_POST['vendor_id']);
    $batch_id  = mysqli_real_escape_string($con, $_POST['batch_id']);

    // ✅ Always ensure clients is an array (even if nothing is selected)
    $clients   = isset($_POST['clients']) ? $_POST['clients'] : [];

    $currentTime = date("Y-m-d H:i:s");

    // ✅ Get work date & time
    $work_query = mysqli_query($con, "SELECT wl_date, wl_time 
                                      FROM work_list 
                                      WHERE wl_id = '$work_id'");
    if (!$work_query || mysqli_num_rows($work_query) == 0) {
        die("Invalid Work ID or Work not found.");
    }
    $work = mysqli_fetch_assoc($work_query);
    $wl_date = $work['wl_date'];
    $wl_time = $work['wl_time'];

    // ✅ Extract new student IDs
    $new_students = [];
    foreach ($clients as $c) {
        $parts = explode("|", $c);
        if (!empty($parts[0])) {
            $new_students[] = mysqli_real_escape_string($con, $parts[0]);
        }
    }

    // ✅ Fetch old students for this work & batch
    $old_students = [];
    $sql = mysqli_query($con, "SELECT ws_student, ws_id 
                               FROM work_student 
                               WHERE ws_vendorId='$vendor_id' 
                               AND ws_workId='$work_id' 
                               AND ws_batchId='$batch_id'");
    $old_map = [];
    while ($row = mysqli_fetch_assoc($sql)) {
        $old_students[] = $row['ws_student'];
        $old_map[$row['ws_student']] = $row['ws_id'];
    }

    // ✅ Compare lists
    $to_delete = array_diff($old_students, $new_students);
    $to_insert = array_diff($new_students, $old_students);

    // ---- DELETE section ----
    if (!empty($to_delete)) {
        foreach ($to_delete as $student_id) {
            $ws_id = $old_map[$student_id];

            // delete from work_student
            mysqli_query($con, "DELETE FROM work_student WHERE ws_id='$ws_id'");

            // delete from work_attendance
            mysqli_query($con, "DELETE FROM work_attendance WHERE wa_wsId='$ws_id'");
        }
    }

    // ---- INSERT section ----
    foreach ($to_insert as $student_id) {
        $insert_ws = mysqli_query($con, "INSERT INTO work_student 
            (ws_student, ws_vendorId, ws_workId, ws_batchId, ws_cDate, ws_date, ws_time) 
            VALUES 
            ('$student_id', '$vendor_id', '$work_id', '$batch_id', '$currentTime', '$wl_date', '$wl_time')");

        if ($insert_ws) {
            $ws_id = mysqli_insert_id($con);

            mysqli_query($con, "INSERT INTO work_attendance 
                (wa_student, wa_wsId, wa_vendorId, wa_workId, wa_batchId, wa_date, wa_time, wa_attendance) 
                VALUES 
                ('$student_id', '$ws_id', '$vendor_id', '$work_id', '$batch_id', '$wl_date', '$wl_time', 0)");
        }
    }

    echo "<script>
        alert('✅ Student list updated successfully!');
        window.location.href = 'work-add-student.php?vendor_id={$vendor_id}&work_id={$work_id}';
    </script>";
}
?>