<?php

ini_set('display_errors', 1);

error_reporting(E_ALL);



require_once "db.php";

header("Content-Type: application/json; charset=UTF-8");



date_default_timezone_set("Asia/Kuala_Lumpur");



$today = date("Y-m-d");

$nowTime = date("H:i:s");

$cutoff = "14:30:00"; // 2:00 PM



if ($nowTime < $cutoff) {

    echo json_encode([

        "success" => false,

        "error" => "Auto absent can only run after 2:30 PM",

        "server_time" => $nowTime,

        "cutoff_time" => $cutoff

    ]);

    exit();

}



// Get all employees who do not yet have attendance for today

$sql = "

    SELECT e.emp_id

    FROM employee e

    WHERE NOT EXISTS (

        SELECT 1

        FROM attendance_log a

        WHERE a.emp_id = e.emp_id

          AND a.att_date = ?

    )

";



$stmt = $conn->prepare($sql);

if (!$stmt) {

    echo json_encode([

        "success" => false,

        "error" => "Prepare failed (select): " . $conn->error

    ]);

    exit();

}



$stmt->bind_param("s", $today);



if (!$stmt->execute()) {

    echo json_encode([

        "success" => false,

        "error" => "Execute failed (select): " . $stmt->error

    ]);

    exit();

}



$result = $stmt->get_result();

if (!$result) {

    echo json_encode([

        "success" => false,

        "error" => "get_result failed (select)"

    ]);

    exit();

}



$inserted = 0;



$insertSql = "

    INSERT INTO attendance_log

    (emp_id, att_date, check_in_time, check_out_time, status, remark)

    VALUES (?, ?, NULL, NULL, 'Absent', 'Auto-marked absent after 2:00 PM')

";



$insertStmt = $conn->prepare($insertSql);

if (!$insertStmt) {

    echo json_encode([

        "success" => false,

        "error" => "Prepare failed (insert): " . $conn->error

    ]);

    exit();

}



while ($row = $result->fetch_assoc()) {

    $emp_id = (int)$row["emp_id"];



    $insertStmt->bind_param("is", $emp_id, $today);



    if (!$insertStmt->execute()) {

        echo json_encode([

            "success" => false,

            "error" => "Execute failed (insert): " . $insertStmt->error,

            "emp_id" => $emp_id

        ]);

        exit();

    }



    $inserted++;

}



echo json_encode([

    "success" => true,

    "message" => "Absent marking completed",

    "date" => $today,

    "server_time" => $nowTime,

    "inserted_absent_count" => $inserted

]);