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

// Authenticate via API Key
$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.*, b.bus_number FROM drivers d JOIN buses b ON d.bus_id = b.id 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['latitude']) && isset($data['longitude'])) {
        $busLat = (float)$data['latitude'];
        $busLon = (float)$data['longitude'];
        $busId = $driver['bus_id'];

        $logStmt = $pdo->prepare("INSERT INTO gps_logs (bus_id, latitude, longitude, battery_level) VALUES (?, ?, ?, ?)");
        $logStmt->execute([
            $busId,
            $busLat,
            $busLon,
            $data['battery_level'] ?? null
        ]);

        // --- Proximity Alerts ---
        require_once '../includes/notifications.php';
        
        // Find students within 500m who haven't been notified in last 30 mins
        $stmt = $pdo->prepare("
            SELECT s.id, s.name, s.parent_phone, s.latitude, s.longitude, t.token 
            FROM students s
            LEFT JOIN fcm_tokens t ON s.parent_phone = t.phone
            WHERE s.bus_id = ? 
              AND s.latitude IS NOT NULL 
              AND (s.last_notified_at IS NULL OR s.last_notified_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE))
        ");
        $stmt->execute([$busId]);
        $students = $stmt->fetchAll();

        $notificationsSent = 0;
        foreach ($students as $student) {
            if (!$student['token']) continue;

            // Simple Haversine
            $earth_radius = 6371;
            $dLat = deg2rad($student['latitude'] - $busLat);
            $dLon = deg2rad($student['longitude'] - $busLon);
            $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($busLat)) * cos(deg2rad($student['latitude'])) * sin($dLon/2) * sin($dLon/2);
            $c = 2 * atan2(sqrt($a), sqrt(1-$a));
            $dist = $earth_radius * $c;

            if ($dist < 0.5) { // 500 meters
                $title = "Bus Arriving Soon!";
                $body = "The bus for " . $student['name'] . " is approximately 500m away.";
                sendPushNotification($student['token'], $title, $body, ['student_id' => $student['id']]);
                
                // Update last_notified_at
                $upd = $pdo->prepare("UPDATE students SET last_notified_at = NOW() WHERE id = ?");
                $upd->execute([$student['id']]);
                $notificationsSent++;
            }
        }

        echo json_encode([
            'success' => true,
            'message' => 'Location updated',
            'alerts_sent' => $notificationsSent,
            'server_time' => date('Y-m-d H:i:s'),
            'tracking_status' => 'active'
        ]);
    } else {
        echo json_encode(['success' => true, 'message' => 'Heartbeat received']);
    }

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