<?php
/**
 * Auto-Reset Helper API
 * 
 * Fungsi: Cek apakah perlu reset attendance untuk hari baru
 * Dipanggil otomatis oleh frontend saat aplikasi dibuka
 * 
 * Cara kerja:
 * 1. Cek tanggal terakhir reset di session/cache
 * 2. Jika hari berbeda, insert data baru untuk hari ini
 * 3. Return status apakah reset dilakukan atau tidak
 */

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("Database connection failed");
    }
    
    $today = date('Y-m-d');
    
    // Check if today's attendance records 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);
    
    $needsReset = ($result['count'] == 0);
    
    if ($needsReset) {
        // 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");
        }
        
        // Insert default 'absent' status for all positions
        $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++;
            }
        }
        
        echo json_encode([
            'success' => true,
            'reset_performed' => true,
            'date' => $today,
            'records_created' => $successCount,
            'message' => 'Attendance reset for new day'
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'reset_performed' => false,
            'date' => $today,
            'existing_records' => $result['count'],
            'message' => 'Attendance records already exist for today'
        ]);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
