<?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'];
    $activeRouteId = $driver['active_route_id'];

    // 2. Check if driver has selected a route
    if (!$activeRouteId) {
        echo json_encode(['success' => false, 'error' => 'Please select a route first']);
        exit;
    }

    // 3. Find Student by NFC ID and verify route assignment
    $studentStmt = $pdo->prepare("
        SELECT * FROM students 
        WHERE nfc_id = ? AND route_id = ?
    ");
    $studentStmt->execute([$nfcId, $activeRouteId]);
    $student = $studentStmt->fetch();

    if (!$student) {
        // Check if student exists but on different route
        $checkStmt = $pdo->prepare("SELECT s.*, r.route_name FROM students s 
                                     LEFT JOIN routes r ON s.route_id = r.id 
                                     WHERE s.nfc_id = ?");
        $checkStmt->execute([$nfcId]);
        $otherStudent = $checkStmt->fetch();
        
        if ($otherStudent) {
            $routeName = $otherStudent['route_name'] ?? 'Unknown Route';
            echo json_encode([
                'success' => false, 
                'error' => 'Student not on this route',
                'student_name' => $otherStudent['name'],
                'student_route' => $routeName
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Unknown student tag']);
        }
        exit;
    }

    // 4. 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']);
}
?>
