<?php
// =================================================================
// ملف: getUpdatedLocationForAdmin.php
// =================================================================

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

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

// تفعيل إظهار الأخطاء لمعرفة مشكلة الكتابة
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // البدء بالاتصال بقواعد البيانات المطلوبة
    $con_tracking = Database::get('tracking');
    $con_ride     = Database::get('ride');
    // $con (main) تم تعريفه بالفعل في connect.php
    $mode = isset($_GET['mode']) && $_GET['mode'] == 'day' ? 'day' : 'live';

    if ($mode == 'day') {
        $fileName = 'locations_day.json';
        $timeCondition = "DATE(created_at) = CURDATE()"; 
    } else {
        $fileName = 'locations_live.json';
        $freshSeconds = 1200; 
        $timeCondition = "created_at >= NOW() - INTERVAL $freshSeconds SECOND";
    }

    // تحديد المسار الكامل بدقة
    $savePath = __DIR__ . '/' . $fileName;

    // === فحص صلاحيات الكتابة ===
    if (!is_writable(__DIR__)) {
        // إذا لم تكن هناك صلاحية، سنطبع الخطأ ونوقف التنفيذ
        echo json_encode([
            "status" => "error", 
            "message" => "Permission Denied: Cannot write to directory. Please chmod 777 this folder.",
            "path" => __DIR__
        ]);
        exit;
    }

    // 1. جلب المواقع
    $sql_locations = "
    SELECT t.driver_id,
           t.latitude AS lat,
           t.longitude AS lon,
           t.heading,
           t.speed,
           t.created_at
    FROM car_tracks t
    INNER JOIN (
        SELECT driver_id, MAX(id) AS max_id
        FROM car_tracks
        WHERE $timeCondition
        GROUP BY driver_id
    ) latest
      ON t.id = latest.max_id
    ORDER BY t.created_at DESC
";
  	$stmt = $con_tracking->prepare($sql_locations);
    $stmt->execute();
    $locations = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. جلب بيانات السائقين
    $driver_ids = array_unique(array_column($locations, 'driver_id'));
    $drivers_info = [];

    if (!empty($driver_ids)) {
        $placeholders = implode(',', array_fill(0, count($driver_ids), '?'));
        $sql_drivers = "SELECT id, first_name, last_name, phone FROM driver WHERE id IN ($placeholders)";
        $stmt_drivers = $con->prepare($sql_drivers);
        $stmt_drivers->execute(array_values($driver_ids));
        foreach ($stmt_drivers->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $drivers_info[$row['id']] = $row;
        }
    }

    // 3. الدمج
    $final_drivers = [];
    foreach ($locations as $loc) {
        $d_id = $loc['driver_id'];
        $merged = [
            'id' => $d_id,
            'lat' => $loc['lat'],
            'lon' => $loc['lon'],
            'heading' => $loc['heading'],
            'speed' => $loc['speed'],
            'name' => 'Unknown',
            'phone' => '',
            'completed' => 0,
            'cancelled' => 0
        ];

        if (isset($drivers_info[$d_id])) {
            $info = $drivers_info[$d_id];
            // فك التشفير البسيط (تأكد من عمل encryptionHelper)
            if (isset($encryptionHelper)) {
                try { $info['first_name'] = $encryptionHelper->decryptData($info['first_name']); } catch(Exception $e){}
                try { $info['last_name'] = $encryptionHelper->decryptData($info['last_name']); } catch(Exception $e){}
                try { $info['phone'] = $encryptionHelper->decryptData($info['phone']); } catch(Exception $e){}
            }
            
            $merged['name'] = trim(($info['first_name']??'') . ' ' . ($info['last_name']??''));
            $merged['phone'] = $info['phone'] ?? '';
            $merged['completed'] = $info['completed'] ?? 0;
            $merged['cancelled'] = $info['cancelled'] ?? 0;
        }
        $final_drivers[] = $merged;
    }

    // 4. الحفظ
    $jsonContent = json_encode(['drivers' => $final_drivers, 'last_updated' => date('Y-m-d H:i:s')], JSON_UNESCAPED_UNICODE);
    
    // محاولة الحفظ
    if (file_put_contents($savePath, $jsonContent) !== false) {
        echo json_encode(["status" => "success", "message" => "File written successfully to $savePath"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to write file. Check permissions."]);
    }

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>