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

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

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

try {
    $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['action'])) {
        echo json_encode(['success' => false, 'error' => 'Missing data']);
        exit;
    }

    $studentId = $data['student_id'];
    $action = $data['action']; // 'pickup' or 'drop'
    $busId = $driver['bus_id'];

    // 1. Log the attendance
    $stmt = $pdo->prepare("INSERT INTO attendance_logs (student_id, bus_id, action) VALUES (?, ?, ?)");
    $stmt->execute([$studentId, $busId, $action]);

    // 2. --- Push Notification to Parent ---
    try {
        require_once '../includes/notifications.php';
        
        // Get student name and parent FCM token (only VALID tokens)
        $studentStmt = $pdo->prepare("
            SELECT s.name, t.token 
            FROM students s 
            LEFT JOIN fcm_tokens t ON s.parent_phone = t.phone 
                AND (t.is_valid = 1 OR t.is_valid IS NULL)
            WHERE s.id = ?");
        $studentStmt->execute([$studentId]);
        $student = $studentStmt->fetch();

        if ($student && $student['token']) {
            $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($student['token'], $title, $body, ['student_id' => $studentId, 'action' => $action]);
        } else {
            error_log("No valid FCM token found for student ID: " . $studentId);
        }
    } catch (Exception $e) {
        // Silently log or ignore notification errors to prevent primary action failure
    }

    echo json_encode(['success' => true, 'action' => $action, 'notify' => (bool)($student['token'] ?? false)]);

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