<?php
/**
 * Cron Job Script - Reset Attendance Daily
 * 
 * Fungsi: Reset semua status kehadiran ke 'absent' setiap hari
 * Jadwal: Jalankan setiap hari jam 00:00 (tengah malam)
 * 
 * Cara Setup Cron Job di cPanel:
 * 1. Buka cPanel > Cron Jobs
 * 2. Tambah Cron Job baru
 * 3. Minute: 0, Hour: 0, Day: *, Month: *, Weekday: *
 * 4. Command: /usr/bin/php /path/to/your/project/cron/reset_attendance.php
 * 
 * Atau via URL (jika server support):
 * Command: wget -q -O - https://yourdomain.com/cron/reset_attendance.php
 */

// Prevent direct browser access (optional security)
$allowed_ips = ['127.0.0.1', '::1']; // Localhost only, atau tambahkan IP server Anda
$client_ip = $_SERVER['REMOTE_ADDR'] ?? '';

// Uncomment baris di bawah jika ingin restrict akses hanya dari localhost
// if (!in_array($client_ip, $allowed_ips)) {
//     http_response_code(403);
//     die('Access denied');
// }

require_once __DIR__ . '/../config/database.php';

// Logging function
function logMessage($message) {
    $logFile = __DIR__ . '/reset_attendance.log';
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[{$timestamp}] {$message}\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
    echo $logEntry; // Output untuk cron log
}

try {
    logMessage("=== Starting Daily Attendance Reset ===");
    
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("Database connection failed");
    }
    
    logMessage("Database connected successfully");
    
    // Get today's date
    $today = date('Y-m-d');
    logMessage("Reset date: {$today}");
    
    // Check if today's attendance records already exist
    $checkQuery = "SELECT COUNT(*) as count FROM attendance WHERE attendance_date = :today";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bindParam(':today', $today);
    $checkStmt->execute();
    $result = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result['count'] > 0) {
        logMessage("Today's attendance records already exist ({$result['count']} records). Skipping reset.");
        logMessage("=== Reset Completed (No Action Needed) ===");
        exit(0);
    }
    
    // Get all positions
    $positionsQuery = "SELECT id FROM positions ORDER BY order_index";
    $positionsStmt = $db->query($positionsQuery);
    $positions = $positionsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($positions)) {
        throw new Exception("No positions found in database");
    }
    
    logMessage("Found " . count($positions) . " positions");
    
    // Insert default 'absent' status for all positions for today
    $insertQuery = "
        INSERT INTO attendance (position_id, attendance_date, status, updated_by)
        VALUES (:position_id, :today, 'absent', NULL)
    ";
    
    $insertStmt = $db->prepare($insertQuery);
    $successCount = 0;
    
    foreach ($positions as $position) {
        $insertStmt->bindParam(':position_id', $position['id']);
        $insertStmt->bindParam(':today', $today);
        
        if ($insertStmt->execute()) {
            $successCount++;
        } else {
            logMessage("Failed to insert attendance for position_id: {$position['id']}");
        }
    }
    
    logMessage("Successfully created {$successCount} attendance records with 'absent' status");
    
    // Optional: Clean up old attendance records (older than 30 days)
    $cleanupDays = 30;
    $cleanupDate = date('Y-m-d', strtotime("-{$cleanupDays} days"));
    
    $cleanupQuery = "DELETE FROM attendance WHERE attendance_date < :cleanup_date";
    $cleanupStmt = $db->prepare($cleanupQuery);
    $cleanupStmt->bindParam(':cleanup_date', $cleanupDate);
    
    if ($cleanupStmt->execute()) {
        $deletedRows = $cleanupStmt->rowCount();
        if ($deletedRows > 0) {
            logMessage("Cleaned up {$deletedRows} old attendance records (older than {$cleanupDays} days)");
        }
    }
    
    logMessage("=== Daily Attendance Reset Completed Successfully ===");
    
} catch (Exception $e) {
    logMessage("ERROR: " . $e->getMessage());
    logMessage("=== Reset Failed ===");
    exit(1);
}
?>
