<?php
require_once __DIR__ . '/../../db/config.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $sn = $_GET['SN'] ?? '';
    if (empty($sn)) {
        http_response_code(400);
        exit('Error: SN missing');
    }
    
    // Respond to device init
    echo "GET OPTION FROM: {$sn}\n";
    echo "Stamp=9999\n";
    echo "OpStamp=9999\n";
    echo "ErrorDelay=60\n";
    echo "Delay=30\n";
    echo "TransTimes=00:00;14:00\n";
    echo "TransInterval=1\n";
    echo "TransFlag=1111000000\n";
    echo "TimeZone=74\n"; // local timezone config
    echo "Realtime=1\n";
    echo "Encrypt=0\n";
    exit;
} elseif ($method === 'POST') {
    $sn = $_GET['SN'] ?? '';
    $table = $_GET['table'] ?? '';
    
    if ($table === 'ATTLOG') {
        $body = file_get_contents('php://input');
        $lines = explode("\n", trim($body));
        
        $empStmt = db()->query("SELECT id, zkteco_uid FROM hr_employees WHERE zkteco_uid IS NOT NULL AND zkteco_uid != '' AND status = 'active'");
        $empMap = [];
        while ($emp = $empStmt->fetch()) {
            $empMap[(string)$emp['zkteco_uid']] = $emp['id'];
        }
        
        $insertedCount = 0;
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) continue;
            
            $parts = explode("\t", $line);
            if (count($parts) >= 2) {
                $uid = trim($parts[0]);
                $datetime = trim($parts[1]);
                
                if (strlen($datetime) >= 19 && isset($empMap[$uid])) {
                    $emp_id = $empMap[$uid];
                    $date = substr($datetime, 0, 10);
                    $time = substr($datetime, 11, 8);
                    
                    $chkStmt = db()->prepare("SELECT id, check_in, check_out FROM hr_attendance WHERE employee_id = ? AND date = ?");
                    $chkStmt->execute([$emp_id, $date]);
                    $existing = $chkStmt->fetch();
                    
                    if ($existing) {
                        $upd_in = $existing['check_in'];
                        $upd_out = $existing['check_out'];
                        $changed = false;
                        
                        if (empty($upd_in) || $time < $upd_in) { $upd_in = $time; $changed = true; }
                        if ($time > $upd_in && (empty($upd_out) || $time > $upd_out)) { $upd_out = $time; $changed = true; }
                        
                        if ($changed) {
                            $uStmt = db()->prepare("UPDATE hr_attendance SET check_in = ?, check_out = ?, status = 'present' WHERE id = ?");
                            $uStmt->execute([$upd_in, $upd_out, $existing['id']]);
                        }
                    } else {
                        $iStmt = db()->prepare("INSERT INTO hr_attendance (employee_id, date, check_in, status) VALUES (?, ?, ?, 'present')");
                        $iStmt->execute([$emp_id, $date, $time]);
                    }
                    $insertedCount++;
                }
            }
        }
        
        echo "OK: " . $insertedCount;
        exit;
    } else {
        // Acknowledge OPERLOG or other tables to keep device happy
        echo "OK";
        exit;
    }
}