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

if (isset($_POST['clients']) && isset($_GET['work_id']) && isset($_GET['vendor_id'])) {
    $clients   = $_POST['clients'];
    $work_id   = mysqli_real_escape_string($con, $_GET['work_id']);
    $vendor_id = mysqli_real_escape_string($con, $_GET['vendor_id']);
    $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'];

    foreach ($clients as $clientVal) {
        // Split "uid|batch_id"
        list($uid, $batch_id) = explode("|", $clientVal);

        $uid      = mysqli_real_escape_string($con, $uid);
        $batch_id = mysqli_real_escape_string($con, $batch_id);

        // Insert into work_student (with batch)
        $insert_ws = mysqli_query($con, "INSERT INTO work_student 
            (ws_student, ws_vendorId, ws_workId, ws_batchId, ws_cDate, ws_date, ws_time) 
            VALUES 
            ('$uid', '$vendor_id', '$work_id', '$batch_id', '$currentTime', '$wl_date', '$wl_time')"
        );
        
        if ($insert_ws) {
            $ws_id = mysqli_insert_id($con);

            // Insert attendance row for that work date
            mysqli_query($con, "INSERT INTO work_attendance 
                (wa_student, wa_wsId, wa_vendorId, wa_workId, wa_date, wa_time, wa_attendance) 
                VALUES 
                ('$uid', '$ws_id', '$vendor_id', '$work_id', '$wl_date', '$wl_time', 0)"
            );
        }
    }

    echo "Selected Students and attendance record saved successfully!";
} else {
    echo "No Students selected!";
}
?>