<?php
// Mock session and environment
require_once 'includes/db.php';
require_once 'includes/functions.php';

echo "Running Kiosk Attendance Test...\n";

$company_id = 1;
$code = 'EMP-0001';

// 1. Find employee
$emp = fetch("SELECT id, name, employee_code FROM employees WHERE employee_code = ? AND company_id = ?", [$code, $company_id]);
if (!$emp) {
    echo "FAIL: Employee $code not found!\n";
    exit(1);
}
echo "Found employee: {$emp['name']} (ID: {$emp['id']})\n";

// 2. Base64 mock image
$mockBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=";

// 3. Process base64
$photoPath = null;
if (preg_match('/^data:image\/(\w+);base64,/', $mockBase64, $type)) {
    $photoData = substr($mockBase64, strpos($mockBase64, ',') + 1);
    $photoData = base64_decode($photoData);
    if ($photoData) {
        $dir = 'uploads/attendance_photos';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $filename = 'test_checkin_' . $emp['id'] . '_' . time() . '.jpg';
        $filepath = $dir . '/' . $filename;
        file_put_contents($filepath, $photoData);
        $photoPath = 'uploads/attendance_photos/' . $filename;
        echo "Saved photo to: $photoPath\n";
    }
}

if (!$photoPath || !file_exists($photoPath)) {
    echo "FAIL: Photo was not created or saved!\n";
    exit(1);
}

// 4. Clean existing logs for today for Kamal3 to ensure we test Clock In
$date = date('Y-m-d');
query("DELETE FROM attendance WHERE employee_id = ? AND date = ?", [$emp['id'], $date]);

// 5. Test Clock In
$now = date('Y-m-d H:i:s');
$status = 'present';
query(
    "INSERT INTO attendance (employee_id, company_id, date, clock_in, status, source, clock_in_photo) VALUES (?, ?, ?, ?, ?, 'kiosk', ?)",
    [$emp['id'], $company_id, $date, $now, $status, $photoPath]
);
echo "Clocked in successfully!\n";

// Verify insert
$log = fetch("SELECT * FROM attendance WHERE employee_id = ? AND date = ? ORDER BY id DESC LIMIT 1", [$emp['id'], $date]);
if ($log && $log['clock_in_photo'] === $photoPath) {
    echo "SUCCESS: Clock-in log verified in DB!\n";
} else {
    echo "FAIL: Clock-in log verification failed!\n";
    exit(1);
}

// 6. Test Clock Out
$outPhotoPath = 'uploads/attendance_photos/test_checkout_' . $emp['id'] . '_' . time() . '.jpg';
copy($photoPath, $outPhotoPath);

$nowOut = date('Y-m-d H:i:s', strtotime('+8 hours'));
query(
    "UPDATE attendance SET clock_out = ?, clock_out_photo = ? WHERE id = ?",
    [$nowOut, $outPhotoPath, $log['id']]
);
echo "Clocked out successfully!\n";

// Verify update
$logOut = fetch("SELECT * FROM attendance WHERE id = ?", [$log['id']]);
if ($logOut && $logOut['clock_out_photo'] === $outPhotoPath && $logOut['clock_out'] === $nowOut) {
    echo "SUCCESS: Clock-out log verified in DB!\n";
} else {
    echo "FAIL: Clock-out log verification failed!\n";
    exit(1);
}

echo "All Kiosk Attendance Tests Passed successfully!\n";
