<?php
/**
 * Get existing attendance record via AJAX
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

header('Content-Type: application/json');

$employeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;
$date = isset($_GET['date']) ? sanitize($_GET['date']) : date('Y-m-d');
$siteId = getCurrentSiteId();

if (!$employeeId || !$date || !$siteId) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT attendance_id, check_in_time, check_out_time, attendance_status, total_hours
        FROM attendance 
        WHERE employee_id = ? AND attendance_date = ? AND site_id = ?
    ");
    $stmt->execute([$employeeId, $date, $siteId]);
    $attendance = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($attendance) {
        echo json_encode([
            'success' => true,
            'attendance' => [
                'check_in_time' => $attendance['check_in_time'],
                'check_out_time' => $attendance['check_out_time'],
                'attendance_status' => $attendance['attendance_status'],
                'total_hours' => $attendance['total_hours']
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'attendance' => null]);
    }
} catch (Exception $e) {
    error_log("Error fetching attendance: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error fetching attendance']);
}

