<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\DriverController;
use App\Http\Controllers\Api\RestaurantController;
use App\Http\Controllers\Api\GasController;
use App\Http\Controllers\Api\GasOfficeController;
use App\Http\Controllers\Api\GasOfficeAuthController;
use App\Http\Controllers\Api\GasOfficeOrderController;
use App\Http\Controllers\Api\GasOfficeCylinderController;
use App\Http\Controllers\Api\GasOrderController;
use App\Http\Controllers\Api\AppSettingController;
use App\Http\Controllers\Api\PaymentController;
use App\Http\Controllers\Api\RestaurantAuthController;
use App\Http\Controllers\Api\MenuItemController;
use App\Http\Controllers\Api\OrderController;
use App\Http\Controllers\Api\TripRequestController;
use App\Http\Controllers\Api\TaxiRequestController;
use App\Http\Controllers\Api\RestaurantWalletController;
use App\Http\Controllers\Api\GasOfficeWalletController;
use App\Http\Controllers\Api\PromotionalWheelController;
use App\Http\Controllers\Api\PassengerExtraServiceController;
use App\Http\Controllers\Api\PassengerExtraServiceMediaController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/


// Routes للمطاعم (غير محمية)
Route::prefix('restaurant')->group(function () {
    Route::post('/login', [RestaurantAuthController::class, 'login']);
    
    // Orders routes for restaurants
    Route::get('/orders', [App\Http\Controllers\Api\RestaurantOrderController::class, 'index']);
    Route::get('/orders/incoming', [App\Http\Controllers\Api\RestaurantOrderController::class, 'getIncomingOrders']);
    Route::get('/orders/completed', [App\Http\Controllers\Api\RestaurantOrderController::class, 'getCompletedOrders']);
    Route::get('/orders/{id}', [App\Http\Controllers\Api\RestaurantOrderController::class, 'show']);
    Route::post('/orders/{id}/accept', [App\Http\Controllers\Api\RestaurantOrderController::class, 'acceptOrder']);
    Route::post('/orders/{id}/reject', [App\Http\Controllers\Api\RestaurantOrderController::class, 'rejectOrder']);
    Route::put('/orders/{id}/status', [App\Http\Controllers\Api\RestaurantOrderController::class, 'updateOrderStatus']);
});

// Test route بدون middleware
Route::get('/restaurant/orders/test', [App\Http\Controllers\Api\TestOrderController::class, 'test']);

// ====== PUBLIC RESTAURANT ROUTES (غير محمية) ======

// مسارات المطاعم العامة - لا تحتاج authentication
Route::get('/restaurants', [RestaurantController::class, 'getRestaurants']);
Route::get('/restaurants/available-governorates', [RestaurantController::class, 'getAvailableGovernorates']);
Route::get('/restaurants/available-cities', [RestaurantController::class, 'getAvailableCities']);
Route::get('/restaurants/{id}/menu', [RestaurantController::class, 'getMenu']);
Route::get('/restaurants/{id}', [RestaurantController::class, 'getRestaurantDetails']);

// مسارات الأطعمة والقوائم - عامة
Route::get('/menu-items/{id}', [RestaurantController::class, 'getMenuItemDetails']);
Route::get('/menu-items/popular', function (Request $request) {
    try {
        $controller = new \App\Http\Controllers\Api\RestaurantController();
        return $controller->getPopularFoodsByGovernorate($request);
    } catch (\Exception $e) {
        \Log::error('خطأ في جلب الأطعمة الشائعة: ' . $e->getMessage());
        
        return response()->json([
            'success' => false,
            'message' => 'حدث خطأ أثناء جلب الأطعمة الشائعة'
        ], 500);
    }
});

// مسارات أنواع المطابخ والمحافظات - عامة
Route::get('/cuisine-types', [RestaurantController::class, 'getCuisineTypes']);
Route::get('/governorates', [RestaurantController::class, 'getGovernorates']);

// Test routes
Route::get('/test', function () {
    return response()->json(['message' => 'API is working!']);
});

Route::get('/test-restaurants', function () {
    $restaurants = \App\Models\Restaurant::where('is_active', true)->get();
    return response()->json([
        'success' => true,
        'data' => $restaurants
    ]);
});

// Test taxi routes (غير محمية للاختبار)
Route::post('/test-taxi-request', [TaxiRequestController::class, 'createTestRequest']);
Route::get('/test-taxi-request/{id}', [TaxiRequestController::class, 'getRequestDetails']);

// Test driver update route (غير محمي للاختبار)
Route::put('/test-driver-update', function(Request $request) {
    try {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'name_ar' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:20',
            'vehicle_type' => 'sometimes|string|max:100',
            'vehicle_color' => 'sometimes|string|max:100',
            'license_plate' => 'sometimes|string|max:20',
            'latitude' => 'sometimes|numeric',
            'longitude' => 'sometimes|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في التحقق من البيانات',
                'errors' => $validator->errors()
            ], 422);
        }

        // محاكاة تحديث بيانات السائق
        $driverData = $request->only([
            'name', 'name_ar', 'phone', 'vehicle_type', 
            'vehicle_color', 'license_plate', 'latitude', 'longitude'
        ]);
        
        // إزالة القيم الفارغة
        $driverData = array_filter($driverData, function($value) {
            return $value !== null && $value !== '';
        });

        return response()->json([
            'success' => true,
            'message' => 'تم تحديث بيانات السائق بنجاح',
            'data' => $driverData
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'خطأ في تحديث البيانات: ' . $e->getMessage()
        ], 500);
    }
});

// ====== PUBLIC AUTH ROUTES ======

// Public routes - يجب أن تكون public لتسجيل الدخول والتسجيل
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/register-phone', [AuthController::class, 'registerWithPhone']);
// تسجيل الدخول بـ OTP (واتساب عبر BulkSMS Iraq): حد 5 رسائل/يوم، 5 دقائق بين الطلبات
Route::post('/auth/check-phone', [AuthController::class, 'checkPhone']);
Route::post('/auth/send-otp', [AuthController::class, 'sendOtp']);
Route::post('/auth/verify-otp', [AuthController::class, 'verifyOtp']);

// مسارات تسجيل الدخول لمكاتب الغاز
Route::post('/gas-office/login', [GasOfficeAuthController::class, 'login']);
Route::post('/gas-office/register', [GasOfficeAuthController::class, 'register']);

// خدمات إضافية للراكب (قائمة وتفاصيل — عامة)
Route::get('/extra-services', [PassengerExtraServiceController::class, 'index']);
Route::get('/extra-services/{id}', [PassengerExtraServiceController::class, 'show']);
Route::get('/passenger-extra-service-media', PassengerExtraServiceMediaController::class);

// App settings routes (public)
Route::get('/settings', [AppSettingController::class, 'index']);
Route::post('/settings/calculate-subscription', [AppSettingController::class, 'calculateSubscription']);

// Location routes (public)
Route::get('/governorates', [App\Http\Controllers\Api\LocationController::class, 'getGovernorates']);
Route::get('/cities', [App\Http\Controllers\Api\LocationController::class, 'getAllCities']);
Route::get('/cities/governorate/{governorateId}', [App\Http\Controllers\Api\LocationController::class, 'getCitiesByGovernorate']);
Route::get('/location/coordinates', [App\Http\Controllers\Api\LocationController::class, 'getLocationByCoordinates']);
Route::get('/user/location/{userId}', [App\Http\Controllers\Api\LocationController::class, 'getUserLocation']);

// Routes للعروض والإعلانات (عامة - لا تحتاج مصادقة)
Route::get('/offers-ads/slider', [App\Http\Controllers\Api\OffersAndAdsController::class, 'getSliderItems']);
Route::get('/offers-ads/banner', [App\Http\Controllers\Api\OffersAndAdsController::class, 'getBannerItems']);

// ====== PROTECTED ROUTES (محمية) ======

Route::middleware('auth:sanctum')->group(function () {
    // Auth routes
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/user', [AuthController::class, 'user']);
    Route::put('/user', [AuthController::class, 'updateUser']);
    Route::get('/user/profile', [AuthController::class, 'user']);
    
    // Profile routes
    Route::post('/profile/upload-image', [AuthController::class, 'uploadProfileImage']);
    Route::post('/auth/password', [AuthController::class, 'changePassword']);

    // ====== PROTECTED RESTAURANT ROUTES (محمية) ======
    
    // مسارات طلبات الراكب (طعام + تتبع) — OrderController
    Route::post('/orders', [OrderController::class, 'store']);
    Route::get('/orders', [OrderController::class, 'myOrders']);
    Route::get('/orders/track', [OrderController::class, 'myOrders']);
    Route::get('/orders/{foodOrder}', [OrderController::class, 'show']);
    Route::post('/orders/{foodOrder}/cancel', [OrderController::class, 'cancel']);
    Route::post('/orders/{foodOrder}/rate', [OrderController::class, 'rate']);

    Route::post('/wheel/spin', [PromotionalWheelController::class, 'spin']);

    Route::post('/extra-service-requests', [PassengerExtraServiceController::class, 'storeRequest']);
    Route::get('/my-extra-service-requests', [PassengerExtraServiceController::class, 'myRequests']);

    // Driver routes
    Route::prefix('driver')->middleware('driver')->group(function () {
        Route::get('/dashboard', [DriverController::class, 'dashboard']);
        Route::post('/location', [DriverController::class, 'updateLocation']);
        
        // مسارات مناطق العمل
        Route::get('/work-areas', [DriverController::class, 'getAvailableWorkAreas']);
        Route::get('/selected-work-areas', [DriverController::class, 'getSelectedWorkAreas']);
        Route::post('/work-areas', [DriverController::class, 'selectWorkAreas']);
        Route::delete('/work-areas/{workArea}', [DriverController::class, 'removeWorkArea']);
        Route::get('/custom-areas', [DriverController::class, 'getCustomAreas']);
        Route::post('/custom-areas', [DriverController::class, 'saveCustomArea']);
        Route::delete('/custom-areas/{areaId}', [DriverController::class, 'deleteCustomArea']);
        
        // مسارات الطلبات الواردة
        Route::get('/incoming-requests', [TripRequestController::class, 'getIncomingRequests']);
        Route::post('/accept-request', [TripRequestController::class, 'acceptRequest']);
        Route::post('/reject-request', [TripRequestController::class, 'rejectRequest']);
        Route::post('/complete-trip', [TripRequestController::class, 'completeRequest']);
        
        // مسارات الرحلات
        Route::get('/trips', [App\Http\Controllers\Api\TripController::class, 'getDriverTrips']);
        Route::get('/trips/stats', [App\Http\Controllers\Api\TripController::class, 'getDriverStats']);
        Route::put('/trips/{trip}/status', [App\Http\Controllers\Api\TripController::class, 'updateTripStatus']);

        // محفظة السائق
        Route::get('/wallet', [App\Http\Controllers\Api\DriverWalletController::class, 'index']);
        Route::post('/wallet/topup-request', [App\Http\Controllers\Api\DriverWalletController::class, 'createTopupRequest']);
        Route::get('/wallet/topup-requests', [App\Http\Controllers\Api\DriverWalletController::class, 'topupRequests']);
        Route::get('/wallet/transactions', [App\Http\Controllers\Api\DriverWalletController::class, 'transactions']);
        Route::post('/wallet/topup-aman-card', [App\Http\Controllers\Api\DriverWalletController::class, 'topUpWithAmanCard']);

        // معلومات السيارة
        Route::get('/vehicle', [App\Http\Controllers\Api\DriverVehicleController::class, 'show']);
        Route::put('/vehicle', [App\Http\Controllers\Api\DriverVehicleController::class, 'update']);

        // محفظة الكاش باك
        Route::get('/cashback', [App\Http\Controllers\Api\DriverCashbackController::class, 'index']);
        Route::post('/cashback/transfer', [App\Http\Controllers\Api\DriverCashbackController::class, 'transferToWallet']);
        Route::get('/cashback/referral-code', [App\Http\Controllers\Api\DriverCashbackController::class, 'getReferralCode']);
    });

    // Routes للسائقين (للركاب لرؤية السائقين المتاحين)
    Route::prefix('users')->group(function () {
        Route::get('/drivers', [DriverController::class, 'getAllDrivers']);
        Route::get('/drivers/nearby', [DriverController::class, 'getNearbyDrivers']);
        Route::post('/drivers/{driverId}/request-taxi', [DriverController::class, 'requestTaxi']);
        Route::get('/my-trip-requests', [DriverController::class, 'getMyTripRequests']);
    });

    // Route لطلبات التاكسي (مباشر)
    Route::middleware('auth:sanctum')->get('/trip-requests', [DriverController::class, 'getMyTripRequests']);

    // ====== TAXI REQUEST ROUTES (مسارات طلبات التاكسي) ======
    
    // إنشاء طلب تاكسي جديد
    Route::post('/taxi-requests', [TaxiRequestController::class, 'createRequest']);
    
    // جلب تفاصيل طلب تاكسي
    Route::get('/taxi-requests/{id}', [TaxiRequestController::class, 'getRequestDetails']);
    
    // جلب طلبات الراكب
    Route::get('/taxi-requests', [TaxiRequestController::class, 'getPassengerRequests']);
    
    // إلغاء طلب تاكسي
    Route::post('/taxi-requests/{id}/cancel', [TaxiRequestController::class, 'cancelRequest']);
    
    // إكمال طلب تاكسي
    Route::post('/taxi-requests/{id}/complete', [TaxiRequestController::class, 'completeRequest']);
    
    // إرسال إشعارات للسائقين
    Route::post('/notifications/send-to-drivers', [App\Http\Controllers\Api\NotificationController::class, 'sendToDrivers']);
    Route::post('/notifications/send-to-passenger', [App\Http\Controllers\Api\NotificationController::class, 'sendToPassenger']);
    Route::post('/notifications/send-to-driver', [App\Http\Controllers\Api\NotificationController::class, 'sendToDriver']);
    Route::post('/notifications/update-fcm-token', [App\Http\Controllers\Api\NotificationController::class, 'updateFCMToken']);
    
    // إشعارات طلبات التاكسي
    Route::post('/notifications/new-taxi-request', [App\Http\Controllers\Api\NotificationController::class, 'notifyNewTaxiRequest']);
    Route::post('/notifications/request-accepted', [App\Http\Controllers\Api\NotificationController::class, 'notifyRequestAccepted']);
    Route::post('/notifications/driver-arrived', [App\Http\Controllers\Api\NotificationController::class, 'notifyDriverArrived']);

    // Routes للمطاعم (تم نقلها إلى public routes في الأعلى)

    // Routes للنقاط والدعوات
    Route::prefix('points')->group(function () {
        Route::get('/info', [App\Http\Controllers\Api\PointsController::class, 'getPointsInfo']);
        Route::post('/generate-referral', [App\Http\Controllers\Api\PointsController::class, 'generateReferralCode']);
        Route::post('/use-referral', [App\Http\Controllers\Api\PointsController::class, 'useReferralCode']);
        Route::get('/rewards', [App\Http\Controllers\Api\PointsController::class, 'getRewards']);
        Route::post('/redeem', [App\Http\Controllers\Api\PointsController::class, 'redeemReward']);
        Route::get('/redemptions', [App\Http\Controllers\Api\PointsController::class, 'getRedemptions']);
    });

    // Routes للمحفظة
    Route::prefix('wallet')->group(function () {
        Route::get('/balance', [App\Http\Controllers\Api\WalletController::class, 'balance']);
        Route::get('/transactions', [App\Http\Controllers\Api\WalletController::class, 'transactions']);
        Route::post('/withdrawal', [App\Http\Controllers\Api\WalletController::class, 'requestWithdrawal']);
        Route::get('/withdrawal-requests', [App\Http\Controllers\Api\WalletController::class, 'withdrawalRequests']);
    });

    // Routes للعروض والإعلانات (محمية)
    Route::prefix('offers-ads')->group(function () {
        Route::get('/offers', [App\Http\Controllers\Api\OffersAndAdsController::class, 'getOffers']);
        Route::get('/ads', [App\Http\Controllers\Api\OffersAndAdsController::class, 'getAds']);
        Route::post('/click/{type}/{id}', [App\Http\Controllers\Api\OffersAndAdsController::class, 'recordClick']);
    });

    // سجل الهدايا (30 يوم متتالية = عجلة الحظ)
    Route::prefix('gift-calendar')->group(function () {
        Route::get('/', [App\Http\Controllers\Api\GiftCalendarController::class, 'getCalendar']);
        Route::post('/spin', [App\Http\Controllers\Api\GiftCalendarController::class, 'spin']);
    });

    // Routes للتسلية والمكافآت
    Route::prefix('entertainment')->group(function () {
        Route::get('/wheel-info', [App\Http\Controllers\Api\EntertainmentController::class, 'getWheelInfo']);
        Route::post('/spin-wheel', [App\Http\Controllers\Api\EntertainmentController::class, 'spinWheel']);
        Route::get('/mining-data', [App\Http\Controllers\Api\EntertainmentController::class, 'getMiningData']);
        Route::post('/update-mining', [App\Http\Controllers\Api\EntertainmentController::class, 'updateMiningData']);
        Route::get('/user-data', [App\Http\Controllers\Api\EntertainmentController::class, 'getUserData']);
        Route::post('/update-user', [App\Http\Controllers\Api\EntertainmentController::class, 'updateUserData']);
        Route::post('/buy-gems', [App\Http\Controllers\Api\EntertainmentController::class, 'buyGemPackage']);
        Route::get('/mining-history', [App\Http\Controllers\Api\EntertainmentController::class, 'getMiningHistory']);
        Route::get('/wheel-history', [App\Http\Controllers\Api\EntertainmentController::class, 'getWheelHistory']);
    });

    // Gas cylinders routes
    Route::prefix('gas')->group(function () {
        Route::get('/', [GasController::class, 'index']);
        Route::get('/{gasCylinder}', [GasController::class, 'show']);
        Route::post('/order', [GasController::class, 'order']);
        Route::get('/orders/my', [GasController::class, 'myOrders']);
        Route::get('/orders/{gasOrder}', [GasController::class, 'showOrder']);
        Route::post('/orders/{gasOrder}/cancel', [GasController::class, 'cancelOrder']);
        Route::post('/orders/{gasOrder}/rate', [GasController::class, 'rateOrder']);
    });

    // Payment routes
    Route::prefix('payments')->group(function () {
        Route::post('/', [PaymentController::class, 'store']);
        Route::get('/', [PaymentController::class, 'myPayments']);
        Route::get('/{payment}', [PaymentController::class, 'show']);
    });

    // Agent routes
    Route::get('/agents/governorates', [App\Http\Controllers\Api\AgentController::class, 'getGovernorates']);
    Route::get('/agents/by-governorate', [App\Http\Controllers\Api\AgentController::class, 'getAgentsByGovernorate']);
    Route::get('/agents/{id}', [App\Http\Controllers\Api\AgentController::class, 'getAgentDetails']);
    Route::post('/agents/transactions', [App\Http\Controllers\Api\AgentController::class, 'createTransaction']);
    Route::get('/agents/transactions/my', [App\Http\Controllers\Api\AgentController::class, 'getMyTransactions']);
    Route::post('/agents/reviews', [App\Http\Controllers\Api\AgentController::class, 'addReview']);
    
    // Chat routes
    Route::get('/chats', [App\Http\Controllers\Api\ChatController::class, 'getChats']);
    Route::post('/chats/send', [App\Http\Controllers\Api\ChatController::class, 'sendMessage']);
    Route::post('/chats/upload-image', [App\Http\Controllers\Api\ChatController::class, 'uploadImage']);
    Route::post('/chats/mark-read', [App\Http\Controllers\Api\ChatController::class, 'markAsRead']);
    Route::get('/chats/list', [App\Http\Controllers\Api\ChatController::class, 'getChatList']);
});

// ====== RESTAURANT MANAGEMENT ROUTES (محمية للمطاعم) ======

Route::prefix('restaurant')->middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [RestaurantAuthController::class, 'logout']);
    Route::get('/profile', [RestaurantController::class, 'getProfile']);
    Route::put('/profile', [RestaurantController::class, 'updateProfile']);
    Route::post('/logo', [RestaurantController::class, 'uploadLogo']);
    Route::post('/cover', [RestaurantController::class, 'uploadCover']);
    Route::get('/stats', [RestaurantController::class, 'getStats']);
    Route::put('/working-hours', [RestaurantController::class, 'updateWorkingHours']);
    
    // Menu Items routes
    Route::get('/menu', [MenuItemController::class, 'index']);
    Route::post('/menu', [MenuItemController::class, 'store']);
    Route::get('/menu/categories', [MenuItemController::class, 'getCategories']);
    Route::get('/menu/{id}', [MenuItemController::class, 'show']);
    Route::put('/menu/{id}', [MenuItemController::class, 'update']);
    Route::delete('/menu/{id}', [MenuItemController::class, 'destroy']);
    Route::post('/menu/{id}/image', [MenuItemController::class, 'uploadImage']);
    
    // Test route
    Route::get('/orders/test', [App\Http\Controllers\Api\TestOrderController::class, 'test']);
    
    // Orders routes
    Route::get('/orders', [App\Http\Controllers\Api\RestaurantOrderController::class, 'index']);
    Route::get('/orders/incoming', [App\Http\Controllers\Api\RestaurantOrderController::class, 'getIncomingOrders']);
    Route::get('/orders/completed', [App\Http\Controllers\Api\RestaurantOrderController::class, 'getCompletedOrders']);
    Route::get('/orders/{id}', [App\Http\Controllers\Api\RestaurantOrderController::class, 'show']);
    Route::post('/orders/{id}/accept', [App\Http\Controllers\Api\RestaurantOrderController::class, 'acceptOrder']);
    Route::post('/orders/{id}/reject', [App\Http\Controllers\Api\RestaurantOrderController::class, 'rejectOrder']);
    Route::put('/orders/{id}/status', [App\Http\Controllers\Api\RestaurantOrderController::class, 'updateOrderStatus']);

    // محفظة المطعم (طلب شحن → تأكيد الإدارة → إضافة الرصيد)
    Route::get('/wallet', [RestaurantWalletController::class, 'index']);
    Route::post('/wallet/topup-request', [RestaurantWalletController::class, 'createTopupRequest']);
    Route::get('/wallet/topup-requests', [RestaurantWalletController::class, 'topupRequests']);
    Route::get('/wallet/transactions', [RestaurantWalletController::class, 'transactions']);
});

// ====== GAS OFFICE MANAGEMENT ROUTES (محمية لمكاتب الغاز) ======

Route::prefix('gas-office')->middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [GasOfficeAuthController::class, 'logout']);
    Route::get('/profile', [GasOfficeAuthController::class, 'profile']);
    Route::put('/profile', [GasOfficeAuthController::class, 'updateProfile']);
    Route::post('/change-password', [GasOfficeAuthController::class, 'changePassword']);
    
    // مسارات إدارة المكتب
    Route::get('/stats', [GasOfficeController::class, 'getStats']);
    Route::put('/status', [GasOfficeController::class, 'updateStatus']);
    Route::put('/working-hours', [GasOfficeController::class, 'updateWorkingHours']);
    Route::put('/delivery-settings', [GasOfficeController::class, 'updateDeliveryFee']);
    Route::put('/service-areas', [GasOfficeController::class, 'updateServiceAreas']);
    
    // مسارات إدارة القناني
    Route::get('/cylinders', [GasOfficeCylinderController::class, 'index']);
    Route::post('/cylinders', [GasOfficeCylinderController::class, 'store']);
    Route::get('/cylinders/{gasCylinder}', [GasOfficeCylinderController::class, 'show']);
    Route::put('/cylinders/{gasCylinder}', [GasOfficeCylinderController::class, 'update']);
    Route::delete('/cylinders/{gasCylinder}', [GasOfficeCylinderController::class, 'destroy']);
    Route::post('/cylinders/{gasCylinder}/stock', [GasOfficeCylinderController::class, 'updateStock']);
    Route::post('/cylinders/{gasCylinder}/image', [GasOfficeCylinderController::class, 'uploadImage']);
    Route::get('/cylinders/stats', [GasOfficeCylinderController::class, 'getStats']);
    
    // مسارات إدارة الطلبات
    Route::get('/orders', [GasOfficeOrderController::class, 'index']);
    Route::get('/orders/incoming', [GasOfficeOrderController::class, 'getIncomingOrders']);
    Route::get('/orders/completed', [GasOfficeOrderController::class, 'getCompletedOrders']);
    Route::get('/orders/{gasOrder}', [GasOfficeOrderController::class, 'show']);
    Route::post('/orders/{gasOrder}/accept', [GasOfficeOrderController::class, 'acceptOrder']);
    Route::post('/orders/{gasOrder}/reject', [GasOfficeOrderController::class, 'rejectOrder']);
    Route::put('/orders/{gasOrder}/status', [GasOfficeOrderController::class, 'updateOrderStatus']);
    Route::post('/orders/{gasOrder}/assign-driver', [GasOfficeOrderController::class, 'assignDriver']);
    Route::get('/orders/stats', [GasOfficeOrderController::class, 'getStats']);

    // محفظة مكتب الغاز (تعبئة زين كاش / ماستر كارد، استقطاع رسوم التطبيق)
    Route::get('/wallet', [GasOfficeWalletController::class, 'index']);
    Route::post('/wallet/topup', [GasOfficeWalletController::class, 'topUp']);
    Route::get('/wallet/transactions', [GasOfficeWalletController::class, 'transactions']);
});

// ====== PUBLIC MAP DATA ROUTES ======

// API routes for working areas and map data
Route::get('/working-area', function () {
    $workingArea = \App\Models\WorkingArea::getActiveArea();
    if ($workingArea) {
        return response()->json([
            'success' => true,
            'data' => [
                'city_name' => $workingArea->city_name,
                'city_name_ar' => $workingArea->city_name_ar,
                'center_lat' => (float) $workingArea->center_lat,
                'center_lng' => (float) $workingArea->center_lng,
                'zoom_level' => $workingArea->zoom_level,
                'boundaries' => $workingArea->boundaries,
                'description' => $workingArea->description,
            ]
        ]);
    }
    
    return response()->json([
        'success' => false,
        'message' => 'لا توجد منطقة عمل محددة'
    ]);
});

Route::get('/service-points', function () {
    $servicePoints = \App\Models\ServicePoint::with('workingArea')->get();
    return response()->json([
        'success' => true,
        'data' => $servicePoints->map(function ($point) {
            return [
                'id' => $point->id,
                'name' => $point->name,
                'name_ar' => $point->name_ar,
                'type' => $point->type,
                'lat' => (float) $point->lat,
                'lng' => (float) $point->lng,
                'address' => $point->address,
                'service_radius' => $point->service_radius,
                'working_area' => $point->workingArea ? [
                    'city_name' => $point->workingArea->city_name,
                    'city_name_ar' => $point->workingArea->city_name_ar,
                ] : null,
            ];
        })
    ]);
});

// ====== PUBLIC GAS OFFICES ROUTES ======

// مسارات مكاتب الغاز العامة - لا تحتاج authentication
Route::get('/gas-offices', [GasOfficeController::class, 'index']);
Route::get('/gas-offices/{id}', [GasOfficeController::class, 'show']);
Route::get('/gas-offices/{id}/cylinders', [GasOfficeController::class, 'cylinders']);
Route::get('/gas-offices/search', [GasOfficeController::class, 'search']);
Route::get('/gas-offices/{id}/stats', [GasOfficeController::class, 'stats']);
Route::post('/gas-offices/create-test-data', [GasOfficeController::class, 'createTestData']);

// ====== GAS ORDERS ROUTES ======

// مسارات طلبات الغاز - تحتاج authentication
Route::middleware('auth:sanctum')->group(function () {
    // طلبات الغاز للمستخدمين
    Route::get('/users/{userId}/gas-orders', [GasOrderController::class, 'index']);
    Route::get('/gas-orders/{id}', [GasOrderController::class, 'show']);
    Route::post('/gas-orders', [GasOrderController::class, 'store']);
    Route::put('/gas-orders/{id}/status', [GasOrderController::class, 'updateStatus']);
    Route::put('/gas-orders/{id}/cancel', [GasOrderController::class, 'cancel']);
    Route::post('/gas-orders/{id}/rate', [GasOrderController::class, 'rate']);
    Route::get('/gas-orders/stats', [GasOrderController::class, 'stats']);
    
    // مسارات مكتب الغاز
    Route::get('/gas-office/orders', [GasOrderController::class, 'gasOfficeOrders']);
    Route::put('/gas-office/orders/{id}/status', [GasOrderController::class, 'updateStatus']);
});