<?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') . "] MARK_ATTENDANCE: " . $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['nfc_id'])) {
        echo json_encode(['success' => false, 'error' => 'Missing NFC ID']);
        exit;
    }

    $nfcId = $data['nfc_id'];
    $busId = $driver['bus_id'];

    // 2. Find Student by NFC ID
    $studentStmt = $pdo->prepare("SELECT * FROM students WHERE nfc_id = ?");
    $studentStmt->execute([$nfcId]);
    $student = $studentStmt->fetch();

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

    // 3. Determine Action (Pickup/Drop)
    // Simple logic: Check the last action for this student today
    $logStmt = $pdo->prepare("SELECT action FROM attendance_logs WHERE student_id = ? AND DATE(log_time) = CURDATE() ORDER BY log_time DESC LIMIT 1");
    $logStmt->execute([$student['id']]);
    $lastAction = $logStmt->fetchColumn();

    $action = ($lastAction == 'pickup') ? 'drop' : 'pickup';

    // 4. Log the attendance
    $insertStmt = $pdo->prepare("INSERT INTO attendance_logs (student_id, bus_id, action) VALUES (?, ?, ?)");
    $insertStmt->execute([$student['id'], $busId, $action]);

    // 5. --- Push Notification to Parent ---
    try {
        require_once '../includes/notifications.php';
        
        // Only get VALID tokens (is_valid = 1)
        $tokenStmt = $pdo->prepare("SELECT token FROM fcm_tokens WHERE phone = ? AND (is_valid = 1 OR is_valid IS NULL)");
        $tokenStmt->execute([$student['parent_phone']]);
        $parentToken = $tokenStmt->fetchColumn();

        if ($parentToken) {
            $studentName = $student['name'];
            $title = ($action == 'pickup') ? "Student Picked Up! 🚌" : "Student Dropped! 👋";
            $body = ($action == 'pickup') 
                    ? "$studentName has boarded the school bus." 
                    : "$studentName has reached their destination safely.";
            
            sendPushNotification($parentToken, $title, $body, ['student_id' => $student['id'], 'action' => $action]);
        } else {
            error_log("No valid FCM token found for parent: " . $student['parent_phone']);
        }
    } catch (Exception $e) {
        // notification failures don't stop the primary logic
    }

    echo json_encode([
        'success' => true, 
        'action' => $action, 
        'student_name' => $student['name'],
        'student_id' => $student['id']
    ]);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
}
?>
