<?php
require_once(__DIR__ . "/../../public/connection.php");

// Fetch attendance settings
$settings = $connection->query("SELECT * FROM attendance_settings LIMIT 1")->fetch_assoc();
$absent_penalty = (float)($settings['absent_penalty'] ?? 0);

// Today's date
$today = date('Y-m-d');

// Fetch all staff
$staff_list = $connection->query("SELECT id FROM staff")->fetch_all(MYSQLI_ASSOC);

// Fetch holidays and closures
$holidays = $connection->query("SELECT holiday_date FROM school_holidays")->fetch_all(MYSQLI_ASSOC);
$closures = $connection->query("SELECT start_date, end_date FROM school_closed_days")->fetch_all(MYSQLI_ASSOC);

// Helper arrays
$holiday_dates = array_column($holidays, 'holiday_date');
$closure_dates = [];
foreach ($closures as $c) {
    $start = strtotime($c['start_date']);
    $end   = strtotime($c['end_date']);
    for ($d = $start; $d <= $end; $d += 86400) {
        $closure_dates[] = date('Y-m-d', $d);
    }
}

// Skip if today is holiday or closure
if (in_array($today, $holiday_dates) || in_array($today, $closure_dates)) {
    exit; // Nothing to do
}

// Loop through all staff
foreach ($staff_list as $staff) {
    $staff_id = $staff['id'];

    // Check if staff already has attendance for today
    $exists = $connection->query("
        SELECT id FROM staff_attendance 
        WHERE staff_id = {$staff_id} AND date = '{$today}'
        LIMIT 1
    ")->fetch_assoc();

    if (!$exists) {
        // Mark as absent
        $stmt = $connection->prepare("
            INSERT INTO staff_attendance (staff_id, date, absent_flag, absence_fee)
            VALUES (?, ?, 1, ?)
        ");
        $stmt->bind_param("isd", $staff_id, $today, $absent_penalty);
        $stmt->execute();
    }
}
?>
