<?php
include 'includes/db.php';

$uid = $_POST['uid'] ?? '';

if (!$uid) {
    echo json_encode(['success' => false, 'message' => 'No UID received']);
    exit;
}

$member = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM members WHERE nfc_uid = '$uid'"));

if (!$member) {
    echo json_encode(['success' => false, 'message' => 'Card not linked']);
    exit;
}

$member_number = $member['member_number'];

// Check if user is currently logged in
$current = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM current_logins WHERE member_number = $member_number"));

if ($current) {
    // Logout
    mysqli_query($conn, "DELETE FROM current_logins WHERE member_number = $member_number");
    mysqli_query($conn, "INSERT INTO attendance (member_number, scan_time, action) VALUES ($member_number, NOW(), 'logout')");
    $action = 'logout';
    $message = 'Logged out successfully';
} else {
    // Login
    mysqli_query($conn, "INSERT INTO current_logins (member_number, scan_time) VALUES ($member_number, NOW())");
    mysqli_query($conn, "INSERT INTO attendance (member_number, scan_time, action) VALUES ($member_number, NOW(), 'login')");
    $action = 'login';
    $message = 'Logged in successfully';
}

echo json_encode([
    'success' => true,
    'action' => $action,
    'name' => $member['first_name'] . ' ' . $member['surname'],
    'status' => $member['payment_status'],
    'expiry' => $member['expiry_date'] ? date('d/m/Y', strtotime($member['expiry_date'])) : 'N/A',
    'phone' => $member['phone'],
    'photo' => $member['photo'] ?? 'default.png',
    'message' => $message
]);
?>
