<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';

try {
    $pdo = db();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed']);
    exit;
}

// Read input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

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

// Basic Auth (API Key)
// In production, check against biometric_devices table
$api_key = $data['api_key'] ?? '';
if ($api_key !== 'test_key') {
    // Check DB
    $stmt = $pdo->prepare("SELECT id FROM biometric_devices WHERE api_key = ? AND status = 1");
    $stmt->execute([$api_key]);
    if (!$stmt->fetch()) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid API Key']);
        exit;
    }
}

// Validate Data
$employee_id = $data['employee_id'] ?? null;
$timestamp = $data['timestamp'] ?? date('Y-m-d H:i:s'); // ISO 8601 or Y-m-d H:i:s
$type = $data['type'] ?? 'check_in'; // check_in or check_out

if (!$employee_id) {
    echo json_encode(['success' => false, 'error' => 'Missing employee_id']);
    exit;
}

// Determine status based on time (simple logic)
$time = date('H:i:s', strtotime($timestamp));
$date = date('Y-m-d', strtotime($timestamp));
$status = 'Present';
if ($type === 'check_in' && $time > '09:00:00') {
    $status = 'Late';
}

// Insert
try {
    $stmt = $pdo->prepare("INSERT INTO attendance_logs (employee_id, date, check_in, check_out, status, source) VALUES (?, ?, ?, ?, ?, 'Biometric Device')");
    
    $check_in = ($type === 'check_in') ? date('Y-m-d H:i:s', strtotime($timestamp)) : null;
    $check_out = ($type === 'check_out') ? date('Y-m-d H:i:s', strtotime($timestamp)) : null;

    // Check if entry exists for this date to update instead of insert?
    // For simplicity, we just insert logs. A real system might merge them.
    // Let's try to find an existing log for today
    $existing = $pdo->prepare("SELECT id FROM attendance_logs WHERE employee_id = ? AND date = ? ORDER BY id DESC LIMIT 1");
    $existing->execute([$employee_id, $date]);
    $log = $existing->fetch(PDO::FETCH_ASSOC);

    if ($log) {
        if ($type === 'check_in') {
             // Maybe they checked in again? Update check_in if null
             $upd = $pdo->prepare("UPDATE attendance_logs SET check_in = ? WHERE id = ? AND check_in IS NULL");
             $upd->execute([$check_in, $log['id']]);
        } else {
             // Check out
             $upd = $pdo->prepare("UPDATE attendance_logs SET check_out = ? WHERE id = ?");
             $upd->execute([$check_out, $log['id']]);
        }
        $msg = "Updated existing log";
    } else {
        $stmt->execute([$employee_id, $date, $check_in, $check_out, $status]);
        $msg = "Created new log";
    }

    echo json_encode(['success' => true, 'message' => $msg]);

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