<?php
declare(strict_types=1);
require_once __DIR__ . '/../db/config.php';

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

// Biometric devices usually send data via POST
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !is_array($data)) {
    echo json_encode(['success' => false, 'error' => 'Invalid JSON input']);
    exit;
}

/*
Expected format:
[
    {"biometric_id": "101", "timestamp": "2026-02-17 08:05:00", "type": "in"},
    {"biometric_id": "101", "timestamp": "2026-02-17 17:05:00", "type": "out"}
]
*/

$db = db();
$success_count = 0;
$errors = [];

try {
    foreach ($data as $log) {
        $biometric_id = $log['biometric_id'] ?? null;
        $device_id = $log['device_id'] ?? null;
        $timestamp = $log['timestamp'] ?? null;
        $type_input = $log['type'] ?? 'unknown';
        $type = 'unknown';
        if (in_array(strtolower($type_input), ['in', 'check_in', 'entry'])) $type = 'check_in';
        if (in_array(strtolower($type_input), ['out', 'check_out', 'exit'])) $type = 'check_out';

        if (!$biometric_id || !$timestamp) {
            continue;
        }

        // Find employee
        $stmt = $db->prepare("SELECT id FROM hr_employees WHERE biometric_id = ?");
        $stmt->execute([$biometric_id]);
        $employee_id = $stmt->fetchColumn() ?: null;

        // Insert into raw logs
        $stmt = $db->prepare("INSERT INTO hr_biometric_logs (biometric_id, device_id, employee_id, timestamp, type) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$biometric_id, $device_id, $employee_id, $timestamp, $type]);
        $log_id = $db->lastInsertId();

        if ($employee_id) {
            $date = date('Y-m-d', strtotime($timestamp));
            $time = date('H:i:s', strtotime($timestamp));

            // Logic to update hr_attendance
            // If it's the first log of the day, it's clock_in. 
            // If it's another log, it might be clock_out.
            
            $stmt = $db->prepare("SELECT id, clock_in, clock_out FROM hr_attendance WHERE employee_id = ? AND attendance_date = ?");
            $stmt->execute([$employee_id, $date]);
            $attendance = $stmt->fetch();

            if (!$attendance) {
                // First entry of the day
                $stmt = $db->prepare("INSERT INTO hr_attendance (employee_id, attendance_date, status, clock_in) VALUES (?, ?, 'present', ?)");
                $stmt->execute([$employee_id, $date, $time]);
            } else {
                // Update existing entry. 
                // Simple logic: if new time is earlier than clock_in, update clock_in.
                // If new time is later than clock_out (or clock_out is null), update clock_out.
                
                $current_in = $attendance['clock_in'];
                $current_out = $attendance['clock_out'];

                if ($time < $current_in) {
                    $stmt = $db->prepare("UPDATE hr_attendance SET clock_in = ? WHERE id = ?");
                    $stmt->execute([$time, $attendance['id']]);
                } elseif (!$current_out || $time > $current_out) {
                    $stmt = $db->prepare("UPDATE hr_attendance SET clock_out = ? WHERE id = ?");
                    $stmt->execute([$time, $attendance['id']]);
                }
            }
            
            // Mark log as processed
            $db->prepare("UPDATE hr_biometric_logs SET processed = 1 WHERE id = ?")->execute([$log_id]);
            $success_count++;
        } else {
            $errors[] = "Employee with Biometric ID $biometric_id not found.";
        }
    }

    echo json_encode([
        'success' => true,
        'message' => "Processed $success_count logs.",
        'errors' => $errors
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
