<?php
session_start();
include 'config.php';
require_once("zklib/zklib.php");

// Device details
$ip   = "192.168.10.55";          // your X2008 IP
$port = 4370;
$serial = "cGKK231062032";        // your device serial

$zk = new ZKLib($ip, $port);

if ($zk->connect()) {
    echo "<h3>✅ Connected to device $ip (Serial: $serial)</h3>";

    $attendance = $zk->getAttendance();
    $count = 0;

    if (!empty($attendance)) {
        foreach ($attendance as $att) {
            $user_id   = $att[1]; // matches users.id (e.g., A001)
            $status    = ($att[2] == 0) ? 'IN' : 'OUT';
            $timestamp = date("Y-m-d H:i:s", strtotime($att[3]));

            // Prevent duplicates
            $check = $conn->prepare("SELECT id FROM attendance WHERE user_id = ? AND log_time = ?");
            $check->bind_param("ss", $user_id, $timestamp);
            $check->execute();
            $check_result = $check->get_result();

            if ($check_result->num_rows == 0) {
                $insert = $conn->prepare("
                    INSERT INTO attendance (user_id, log_time, status, device_id, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, NOW(), NOW())
                ");
                $insert->bind_param("ssss", $user_id, $timestamp, $status, $serial);
                $insert->execute();
                $count++;
            }
        }
        echo "<p>✅ Synced $count new records.</p>";
    } else {
        echo "<p>No logs found on device (or zklib not fully implemented).</p>";
    }

    $zk->disconnect();
} else {
    echo "<h3>❌ Could not connect to device at $ip</h3>";
}

$conn->close();
?>
