<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';
    $scan_type = isset($_POST['scan_type']) ? trim($_POST['scan_type']) : '';

    if (empty($user_id) || $scan_type !== 'attendance') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid or missing data.']);
        exit;
    }

    // Check if user exists
    $stmt = $conn->prepare("SELECT fullname, participant_type FROM users WHERE id = ?");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => '❌ User not found.']);
        exit;
    }

    $fullname = $user['fullname'];
    $participant_type = $user['participant_type'];

    // Optional: Check recent scan within last 60 seconds
    $recentStmt = $conn->prepare("SELECT checkin_time FROM attendance WHERE user_id = ? ORDER BY checkin_time DESC LIMIT 1");
    $recentStmt->bind_param("s", $user_id);
    $recentStmt->execute();
    $recentResult = $recentStmt->get_result();

    if ($recent = $recentResult->fetch_assoc()) {
        $lastCheckin = strtotime($recent['checkin_time']);
        if ($lastCheckin > (time() - 60)) {
            echo json_encode(['status' => 'error', 'message' => '⚠️ Already checked in recently.']);
            exit;
        }
    }

    // Insert attendance
    $insertStmt = $conn->prepare("INSERT INTO attendance (user_id, participant_type, fullname) VALUES (?, ?, ?)");
    $insertStmt->bind_param("sss", $user_id, $participant_type, $fullname);
    if ($insertStmt->execute()) {
        echo json_encode([
            'status' => 'success',
            'message' => "✅ Attendance marked for $fullname",
            'fullname' => $fullname,
            'participant_type' => $participant_type
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => '❌ Failed to mark attendance.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
