<?php
header('Content-Type: application/json');
require_once '../includes/db.php';

// Debug Logging
$logFile = 'debug_nfc.log';
$rawInput = file_get_contents('php://input');
$headers = getallheaders();
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] REQUEST: " . $rawInput . " | HEADERS: " . json_encode($headers) . "\n", FILE_APPEND);


$headers = getallheaders();
$apiKey = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$apiKey) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    // 1. Verify Driver
    $stmt = $pdo->prepare("SELECT d.* FROM drivers d WHERE d.api_key = ? AND d.status = 'active'");
    $stmt->execute([$apiKey]);
    $driver = $stmt->fetch();

    if (!$driver) {
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }

    $data = json_decode(file_get_contents('php://input'), true);
    if (!isset($data['student_id']) || !isset($data['nfc_id'])) {
        echo json_encode(['success' => false, 'error' => 'Missing student ID or NFC ID']);
        exit;
    }

    $studentId = $data['student_id'];
    $nfcId = $data['nfc_id'];

    // 2. Update Student Tag
    $updateStmt = $pdo->prepare("UPDATE students SET nfc_id = ? WHERE id = ?");
    $updateStmt->execute([$nfcId, $studentId]);

    echo json_encode([
        'success' => true,
        'message' => 'Tag registered successfully'
    ]);

} catch (PDOException $e) {
    if ($e->getCode() == 23000) {
        echo json_encode(['success' => false, 'error' => 'This tag is already assigned to another student']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database error']);
    }
}
?>
