<?php
/**
 * Biometric terminal push endpoint (ZKTeco ADMS / "iclock" protocol).
 *
 * ZKTeco push-SDK devices (SpeedFace, F18/F22, MB460, …) talk to this URL over
 * wired Ethernet or Wi-Fi. Point the device's "Cloud Server / ADMS" setting at:
 *     http(s)://<host>/edutrack/attendance/device_endpoint.php
 *
 * Handled requests:
 *   GET  ...?SN=XXXX&options=all         → handshake / config
 *   POST ...?SN=XXXX&table=ATTLOG        → attendance punches (tab-separated rows)
 *   GET  ...?SN=XXXX  (getrequest)       → command poll (we issue none)
 *
 * Authentication is by device serial (SN) — the SN must be registered under
 * Biometric → Devices. Unknown serials are rejected.
 *
 * This endpoint is device-facing (no user session).
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/biometric_lib.php';

header('Content-Type: text/plain');

// The add-on must be licensed for the endpoint to accept data.
if (!function_exists('hasModule') || !hasModule('biometric_attendance')) {
    http_response_code(403);
    echo 'Biometric add-on not licensed';
    exit;
}

$conn = getDBConnection();
biometric_ensure_tables($conn);

$sn = trim($_GET['SN'] ?? $_GET['sn'] ?? '');
if ($sn === '') { http_response_code(400); echo 'SN required'; exit; }

$device = biometric_device_by_serial($conn, $sn);
if (!$device) { http_response_code(401); echo 'Unregistered device'; exit; }

// Heartbeat.
$conn->query("UPDATE biometric_devices SET last_seen=NOW() WHERE id=" . (int) $device['id']);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path   = strtolower($_SERVER['REQUEST_URI'] ?? '');

// ── Handshake / config (device asks what to do) ───────────────────────────
if ($method === 'GET' && (isset($_GET['options']) || strpos($path, 'getrequest') !== false || strpos($path, 'cdata') !== false)) {
    // Minimal ADMS reply: accept logs, no pending commands.
    echo "GET OPTION FROM: {$sn}\r\n";
    echo "Stamp=0\r\n";
    echo "OpStamp=0\r\n";
    echo "ErrorDelay=30\r\n";
    echo "Delay=30\r\n";
    echo "TransTimes=00:00;12:00\r\n";
    echo "TransInterval=1\r\n";
    echo "TransFlag=1111000000\r\n";
    echo "Realtime=1\r\n";
    echo "Encrypt=0\r\n";
    exit;
}

// ── Attendance upload (ATTLOG) ────────────────────────────────────────────
if ($method === 'POST') {
    $table = strtoupper($_GET['table'] ?? '');
    $body  = file_get_contents('php://input');

    if ($table === 'ATTLOG' || $table === '') {
        $deviceDir = $device['direction'] ?? 'auto';
        $rows = preg_split('/\r\n|\n|\r/', trim($body));
        $accepted = 0;
        foreach ($rows as $line) {
            $line = trim($line);
            if ($line === '') continue;
            // ATTLOG format: userid \t timestamp \t status \t verify \t workcode ...
            $cols = preg_split('/\t/', $line);
            $userId = trim($cols[0] ?? '');
            $ts     = trim($cols[1] ?? '');
            if ($userId === '' || $ts === '') continue;
            $punchTime = date('Y-m-d H:i:s', strtotime($ts) ?: time());
            // verify col: 1=fingerprint, 15=face (ZK); default fingerprint.
            $verify = (int) ($cols[3] ?? 1);
            $capMethod = ($verify === 15) ? 'face' : 'fingerprint';
            // status col: 0=check-in, 1=check-out (device-configured).
            $statusCol = (int) ($cols[2] ?? 0);
            $direction = $deviceDir !== 'auto' ? $deviceDir : ($statusCol === 1 ? 'out' : 'in');

            $person = biometric_resolve_user($conn, $userId);
            biometric_record_punch($conn, (int) $device['id'], $userId, $person, $capMethod, $direction, $punchTime, 'device');
            $accepted++;
        }
        echo "OK: {$accepted}\r\n";
        exit;
    }

    // Other tables (OPERLOG, etc.) — acknowledge without storing.
    echo "OK: 0\r\n";
    exit;
}

echo "OK\r\n";
