<?php
require_once __DIR__ . '/../../connect.php';

/**
 * تطبيع رقم الهاتف ليتوافق مع التخزين في قاعدة البيانات
 */
function normalizePhone($phone) {
    $clean = preg_replace('/\D+/', '', $phone);
    // Syria: 099XXXXXXX or 9639XXXXXXX
    if (strlen($clean) === 10 && strpos($clean, '09') === 0) return '963' . substr($clean, 1);
    if (strlen($clean) === 12 && strpos($clean, '963') === 0) return $clean;
    if (strlen($clean) === 9 && strpos($clean, '9') === 0) return '963' . $clean;
    // Jordan: 079XXXXXXX or 9627XXXXXXX
    if (strlen($clean) === 10 && strpos($clean, '07') === 0) return '962' . substr($clean, 1);
    if (strlen($clean) === 12 && strpos($clean, '962') === 0) return $clean;
    if (strlen($clean) === 9 && strpos($clean, '7') === 0) return '962' . $clean;
    // Egypt: 010XXXXXXXX or 2010XXXXXXXX
    if (strlen($clean) === 11 && strpos($clean, '01') === 0) return '20' . substr($clean, 1);
    if (strlen($clean) === 13 && strpos($clean, '20') === 0) return $clean;
    return $clean;
}

// 1. تسجيل بداية الطلب
$phone = filterRequest("phone");
error_log("[MONITOR_RIDE] ---------------- START REQUEST ----------------");
error_log("[MONITOR_RIDE] 1. Received Phone: " . $phone);

// تطبيع الرقم
$phone = normalizePhone($phone);
error_log("[MONITOR_RIDE] 1.5 Normalized Phone: " . $phone);

//------------------------------------------------------------------------
// 1) البحث عن الهاتف أولاً في جدول السائق ثم جدول الراكب
//------------------------------------------------------------------------

$encPhone = $encryptionHelper->encryptData($phone);
error_log("[MONITOR_RIDE] 2. Encrypted Phone: " . $encPhone);

// Check Driver Table
$driverQuery = $con->prepare("SELECT id AS driverID FROM driver WHERE phone = :phone LIMIT 1");
$driverQuery->execute([':phone' => $encPhone]);
$driver = $driverQuery->fetch(PDO::FETCH_ASSOC);

// Check Passenger Table
$customerQuery = $con->prepare("SELECT id AS customerID FROM passengers WHERE phone = :phone LIMIT 1");
$customerQuery->execute([':phone' => $encPhone]);
$customer = $customerQuery->fetch(PDO::FETCH_ASSOC);

// حدد نوع المستخدم
$userType = '';
$driverID = null;
$customerID = null;

if ($driver) {
    $userType = 'driver';
    $driverID = $driver['driverID'];
    error_log("[MONITOR_RIDE] 3. User Found: Type = DRIVER, ID = " . $driverID);
} elseif ($customer) {
    $userType = 'customer';
    $customerID = $customer['customerID'];
    error_log("[MONITOR_RIDE] 3. User Found: Type = CUSTOMER, ID = " . $customerID);
} else {
    error_log("[MONITOR_RIDE] 3. FAILURE: Phone number not found in Driver or Passenger tables.");
    jsonError("رقم الهاتف غير موجود في النظام.");
    exit;
}

//------------------------------------------------------------------------
// 2) جلب آخر رحلة حالتها نشطة (Apply, Applied, Arrived, Begin)
//------------------------------------------------------------------------

$activeStatuses = "'Apply','Applied','Arrived','arrived','Begin'";

if ($userType == 'driver') {
    error_log("[MONITOR_RIDE] 4. Searching for active ride for Driver ID: " . $driverID);
    $rideQuery = $con->prepare("
        SELECT * FROM ride
        WHERE driver_id = :driverID AND status IN ($activeStatuses)
        ORDER BY id DESC LIMIT 1
    ");
    $rideQuery->execute([':driverID' => $driverID]);
} else {
    error_log("[MONITOR_RIDE] 4. Searching for active ride for Customer ID: " . $customerID);
    $rideQuery = $con->prepare("
        SELECT * FROM ride
        WHERE passenger_id = :customerID AND status IN ($activeStatuses)
        ORDER BY id DESC LIMIT 1
    ");
    $rideQuery->execute([':customerID' => $customerID]);
}

$ride = $rideQuery->fetch(PDO::FETCH_ASSOC);

if (!$ride) {
    error_log("[MONITOR_RIDE] 4. FAILURE: No active ride found.");
    jsonError("لا توجد رحلة نشطة لهذا المستخدم.");
    exit;
} else {
    error_log("[MONITOR_RIDE] 4. SUCCESS: Active Ride Found. Ride ID: " . $ride['id'] . " Status: " . $ride['status']);
}

//------------------------------------------------------------------------
// 3) جلب معلومات السائق من الرحلة
//------------------------------------------------------------------------

$rideDriverID = $ride['driverID'] ?? $ride['driver_id'];
error_log("[MONITOR_RIDE] 5. Fetching info for Driver ID from Ride: " . $rideDriverID);

$driverInfoQuery = $con->prepare("
    SELECT id, first_name, last_name, phone
    FROM driver 
    WHERE id = :driverID
    LIMIT 1
");

$driverInfoQuery->execute([':driverID' => $rideDriverID]);
$driverInfo = $driverInfoQuery->fetch(PDO::FETCH_ASSOC);

if ($driverInfo) {
    $driverInfo['phone'] = $encryptionHelper->decryptData($driverInfo['phone']);
    $driverInfo['first_name'] = $encryptionHelper->decryptData($driverInfo['first_name']);
    $driverInfo['last_name']  = $encryptionHelper->decryptData($driverInfo['last_name']);
    $fullName = $driverInfo['first_name'] . " " . $driverInfo['last_name'];
    $driverInfo['fullname'] = $fullName;
    error_log("[MONITOR_RIDE] 5. Driver Info Found: " . $fullName);
} else {
    error_log("[MONITOR_RIDE] 5. WARNING: Driver info not found for ID " . $rideDriverID);
}

//------------------------------------------------------------------------
// 4) جلب آخر موقع للسائق من جدول car_locations بشرط الحالة ON
//------------------------------------------------------------------------

error_log("[MONITOR_RIDE] 6. Querying Tracking DB for Driver ID: " . $rideDriverID);

$locationQuery = $con_tracking->prepare("
    SELECT latitude, longitude, speed, heading, updated_at 
    FROM car_locations
    WHERE driver_id = :driverID AND status = 'ON'
    ORDER BY updated_at DESC LIMIT 1
");
$locationQuery->execute([':driverID' => $rideDriverID]);
$location = $locationQuery->fetch(PDO::FETCH_ASSOC);

if ($location) {
    error_log("[MONITOR_RIDE] 6. Location Found: Lat=" . $location['latitude'] . " Lng=" . $location['longitude']);
} else {
    error_log("[MONITOR_RIDE] 6. WARNING: No live location found.");
}

//------------------------------------------------------------------------
// 5) تجهيز البيانات للرد
//------------------------------------------------------------------------

$response = [
    "ride_details"    => $ride,
    "driver_details" => $driverInfo,
    "driver_location" => $location ?: "No live location"
];

error_log("[MONITOR_RIDE] 7. Sending Success Response.");
jsonSuccess($response);