<?php
// Is file ko server par cron job ke roop mein set karna hoga.
require_once 'config.php';

// Kal ki tarikh
$yesterday = date('Y-m-d', strtotime('-1 day'));

echo "Starting Attendance Marking for: " . $yesterday . "\n";

// Sabhi active users ko select karein (Admins ko chhodkar)
$users_result = $conn->query("SELECT u.id FROM users u LEFT JOIN user_roles ur ON u.id = ur.user_id LEFT JOIN roles r ON ur.role_id = r.id WHERE r.name != 'Admin' OR r.name IS NULL");

while ($user = $users_result->fetch_assoc()) {
    $user_id = $user['id'];

    // 1. Check karein ki kal ke liye koi approved leave hai ya nahi
    $leave_stmt = $conn->prepare("SELECT leave_type, half_day_period FROM leave_requests WHERE user_id = ? AND status = 'Approved' AND ? BETWEEN start_date AND end_date");
    $leave_stmt->bind_param("is", $user_id, $yesterday);
    $leave_stmt->execute();
    $leave_result = $leave_stmt->get_result();
    
    $attendance_status = 'Present'; // Default status
    $half_day_period = NULL;

    if ($leave_result->num_rows > 0) {
        $leave = $leave_result->fetch_assoc();
        if ($leave['leave_type'] == 'Full Day') {
            $attendance_status = 'CL';
        } elseif ($leave['leave_type'] == 'Half Day') {
            $attendance_status = 'Half Day';
            $half_day_period = $leave['half_day_period'];
        }
    }
    $leave_stmt->close();

    // 2. Attendance ko database mein insert ya update karein
    $att_stmt = $conn->prepare("INSERT INTO attendance (user_id, attendance_date, status, half_day_period, marked_by) VALUES (?, ?, ?, ?, 'System') ON DUPLICATE KEY UPDATE status = VALUES(status), half_day_period = VALUES(half_day_period), marked_by = VALUES(marked_by)");
    $att_stmt->bind_param("isss", $user_id, $yesterday, $attendance_status, $half_day_period);
    $att_stmt->execute();
    $att_stmt->close();

    echo "Marked " . $attendance_status . " for user ID: " . $user_id . "\n";
}

echo "Attendance marking finished.\n";
$conn->close();
?>