<?php
// ابدأ التخزين المؤقت فوراً
ob_start();

require_once __DIR__ . '/../../get_connect.php';

// تنظيف *جميع* مستويات التخزين المؤقت (Loop)
// هذا يضمن التخلص من أي مسافات أو أخطاء ظهرت من ملفات الـ include
while (ob_get_level()) {
    ob_end_clean();
}

// ابدأ مخزناً جديداً ونظيفاً لهذا الملف فقط
ob_start();

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Content-Type: application/json; charset=UTF-8");

function sendError($message, $code = 400, $extra = []) {
    // تنظيف ما قبل الخطأ
    ob_clean();
    http_response_code($code);
    echo json_encode(array_merge(["status" => "failure", "message" => $message], $extra));
    exit;
}

try {
    $rideID = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
    $token = filter_input(INPUT_GET, 'token', FILTER_SANITIZE_SPECIAL_CHARS);

    if (!$rideID || !$token) {
        sendError("Missing parameters");
    }

    $stmtRide = $con_ride->prepare("SELECT driver_id, status FROM ride WHERE id = ? LIMIT 1");
    $stmtRide->execute([$rideID]);
    $rideData = $stmtRide->fetch(PDO::FETCH_ASSOC);

    if (!$rideData) sendError("Ride not found");

    $driverID = $rideData['driver_id'];
    $status   = $rideData['status'];
    $secretSalt = "Intaleq_Secure_Track_2025"; 
    $generatedToken = md5(trim(strval($rideID)) . trim(strval($driverID)) . $secretSalt);

    if ($token !== $generatedToken) sendError("Invalid Token");

    $allowedStatuses = ['Applied', 'Arrived', 'Begin', 'inProgress']; 
    if (!in_array($status, $allowedStatuses)) {
        sendError("Ride not active", 200, ["current_status" => $status]);
    }

    $stmtLoc = $con_tracking->prepare("SELECT latitude, longitude, heading, speed, updated_at FROM car_locations WHERE driver_id = ? ORDER BY updated_at DESC LIMIT 1");
    $stmtLoc->execute([$driverID]);
    $locData = $stmtLoc->fetch(PDO::FETCH_ASSOC);

    if (!$locData) sendError("Waiting for driver signal...", 200);

    $stmtDriver = $con->prepare("SELECT d.first_name, c.model, c.color, c.car_plate FROM driver d LEFT JOIN CarRegistration c ON d.id = c.driverID WHERE d.id = ? LIMIT 1");
    $stmtDriver->execute([$driverID]);
    $driverInfo = $stmtDriver->fetch(PDO::FETCH_ASSOC);

    $driverName = "Captain";
    $carModel   = "Car";
    $carColor   = "";
    $plate      = "";

    if ($driverInfo) {
        if (!empty($driverInfo['first_name'])) $driverName = $encryptionHelper->decryptData($driverInfo['first_name']);
        if (!empty($driverInfo['model'])) $carModel = $driverInfo['model'];
        if (!empty($driverInfo['color'])) $carColor = $driverInfo['color'];
        if (!empty($driverInfo['car_plate'])) $plate = $encryptionHelper->decryptData($driverInfo['car_plate']);
    }

    $response = [
        "status" => "success",
        "data"   => [
            "lat"         => $locData['latitude'],
            "lng"         => $locData['longitude'],
            "heading"     => $locData['heading'],
            "speed"       => $locData['speed'],
            "last_update" => $locData['updated_at'],
            "driver_name" => $driverName,
            "car_model"   => $carModel,
            "car_color"   => $carColor,
            "plate"       => $plate,
            "ride_status" => $status 
        ]
    ];

    // التنظيف النهائي قبل الطباعة
    ob_clean();
    echo json_encode($response);

} catch (Exception $e) {
    error_log("Tracking API Error: " . $e->getMessage());
    sendError("Server Error");
}