<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Driver;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

class DriversController extends Controller
{
public function getDeliveryOrders(Request $request)
{
    $user = Auth::user(); // Get the authenticated user's details

    // Validate the request parameter
    $request->validate([
        'type' => 'required|in:delivery',
    ]);

    $type = $request->input('type'); // 'delivery'

    // Fetch delivery orders with matching user_id from the orders table
    $orders = DB::table('orders')
        ->select(
            'orders.id', 'orders.order_id', 'orders.user_id', 'orders.vendor_id', 'orders.vendor_address',
            'orders.vendor_latitude', 'orders.vendor_longitude', 'orders.user_latitude', 'orders.user_longitude',
            'orders.status', 'orders.created_at as order_date', 'orders.user_total_cost', 'orders.payment_mode',
            'users.name as customer_name', 'users.phone_number as customer_contact_number',
            'orders.customer_address as customer_address'
        )
        ->join('users', 'users.user_id', '=', 'orders.user_id') // Join orders with users table
        ->where('orders.delivery_agent_id', $user->user_id)
        ->whereIn('orders.status', ['At Vendor', 'Ready for Delivery', 'Delivery In Progress', 'Delivered', 'Completed'])
        ->get();

    // Prepare the response format
    $response = [
        'pending' => [],
        'delivered' => [],
    ];

    foreach ($orders as $order) {
        $orderDetails = [
            'order_id' => $order->order_id,
            'address' => $order->customer_address,
            'lat' => $order->user_latitude,
            'lng' => $order->user_longitude,
            'status'=> $order->status,
            'customer_name' => $order->customer_name,
            'customer_contact_number' => $order->customer_contact_number,
            'order_date' => $order->order_date,
        ];

        // Include `cash_collected` only if payment_mode is 'cash'
        if ($order->payment_mode === 'cash') {
            $orderDetails['cash_collected'] = $order->user_total_cost;
        }

        // Categorize orders based on their status
        if (in_array($order->status, ['At Vendor', 'Ready for Delivery', 'Delivery In Progress'])) {
            $response['pending'][] = $orderDetails;
        } elseif (in_array($order->status, ['Delivered', 'Completed'])) {
            $response['delivered'][] = $orderDetails;
        }
    }

    // Return the response with empty categories if no orders are found
    return response()->json($response);
}
public function getDeliveryOrder(Request $request)
{
    $user = Auth::user(); // Get the authenticated user's details

    // Validate the request parameter
    $request->validate([
        'type' => 'required|in:delivery',
    ]);

    $type = $request->input('type'); // 'delivery'

    // Fetch delivery orders with matching user_id from the orders table
    $orders = DB::table('orders')
        ->select(
            'orders.id', 'orders.order_id', 'orders.user_id', 'orders.vendor_id', 'orders.vendor_address',
            'orders.vendor_latitude', 'orders.vendor_longitude', 'orders.user_latitude', 'orders.user_longitude',
            'orders.status', 'orders.created_at as order_date', 'orders.user_total_cost', 'orders.payment_mode',
            'users.name as customer_name', 'users.phone_number as customer_contact_number',
            'orders.customer_address as customer_address'
        )
        ->join('users', 'users.user_id', '=', 'orders.user_id') // Join orders with users table
        ->where('orders.delivery_agent_id', $user->user_id)
        ->whereIn('orders.status', [
            'At Vendor', 'Ready for Delivery', 'Delivery In Progress', 'Delivered', 'Completed'
        ])
        ->get();

    // Prepare the response format
    $response = [
        'pending' => [],
        
    ];

    foreach ($orders as $order) {
        $orderDetails = [
            'order_id' => $order->order_id,
            'pickup' => [
                'lat' => $order->vendor_latitude, // Vendor latitude (pickup)
                'lng' => $order->vendor_longitude, // Vendor longitude (pickup)
                'to_lat' => $order->user_latitude, // User latitude (destination)
                'to_lng' => $order->user_longitude, // User longitude (destination)
                'from' => 'vendor', // Indicates it's from vendor
                'name' => $order->customer_name, // Customer name
                'contact_number' => $order->customer_contact_number, // Customer contact number
                'address' => $order->customer_address, // Customer address
                'ht_reach' => '', // Assuming this remains empty
            ],
            'delivery' => [
                'lat' => $order->user_latitude, // User latitude (destination)
                'lng' => $order->user_longitude, // User longitude (destination)
                'to' => 'customer', // Indicates it's for delivery to customer
                'name' => $order->customer_name, // Customer name
                'contact_number' => $order->customer_contact_number, // Customer contact number
                'address' => $order->customer_address, // Customer address
                'ht_reach' => '', // Assuming this remains empty
            ],
            'order_date' => $order->order_date, // Order date
        ];

        // Include `cash_collected` only if payment_mode is 'cash'
        if ($order->payment_mode === 'cash') {
            $orderDetails['cash_collected'] = $order->user_total_cost;
        }

        // Categorize orders based on their status
        if (in_array($order->status, ['At Vendor', 'Ready for Delivery', 'Delivery In Progress'])) {
            $response['pending'][] = $orderDetails;
        } 
    }

    // Ensure keys are always present, even if no data
    $response['pending'] = $response['pending'] ?? [];

    

    return response()->json($response);
}

public function getPickupOrders(Request $request)
{
    try {
        // Get the authenticated user
        $user = Auth::user();

        // Validate request parameters
        $validatedData = $request->validate([
            'type' => 'required|in:pickup',
        ]);

        $type = $validatedData['type']; // 'pickup'

        // Fetch pickup orders for the authenticated user
        $orders = DB::table('orders')
            ->select(
                'orders.id', 'orders.order_id', 'orders.user_id', 'orders.vendor_id', 'orders.vendor_address',
                'orders.vendor_latitude', 'orders.vendor_longitude', 'orders.user_latitude', 'orders.user_longitude',
                'orders.status', 'orders.created_at as order_date', 'orders.user_total_cost', 'orders.payment_mode',
                'users.name as customer_name', 'users.phone_number as customer_contact_number',
                'orders.customer_address as customer_address'
            )
            ->join('users', 'users.user_id', '=', 'orders.user_id') // Join orders with users table
            ->where('orders.pickup_agent_id', $user->user_id)
            ->whereIn('orders.status', [
                'Pending', 'Accepted', 'Pickup In Progress', 'Picked Up',
                'At Vendor', 'Ready for Delivery', 'Delivery In Progress',
                'Delivered', 'Completed', 'Cancelled'
            ])
            ->get();

        // Prepare response data
        $response = [
            'pickup_pending' => [],
            'pickedup' => [],
        ];

        foreach ($orders as $order) {
            $orderDetails = [
                'order_id' => $order->order_id,
                'address' => $order->vendor_address,
                'lat' => $order->vendor_latitude,
                'lng' => $order->vendor_longitude,
                'status'=> $order->status,
                'customer_name' => $order->customer_name,
                'customer_contact_number' => $order->customer_contact_number,
                'order_date' => $order->order_date,
            ];

            // Categorize orders based on their status
            if (in_array($order->status, ['Accepted', 'Pickup In Progress'])) {
                $response['pickup_pending'][] = $orderDetails;
            } elseif (in_array($order->status, ['Picked Up', 'At Vendor', 'Ready for Delivery', 'Delivery In Progress'])) {
                $response['pickedup'][] = $orderDetails;
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Pickup orders retrieved successfully',
            'data' => $response
        ], 200);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation error',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'An error occurred while fetching pickup orders',
            'error' => $e->getMessage()
        ], 500);
    }
}



public function getPickupOrder(Request $request)
{
    $user = Auth::user(); // Get the authenticated user's details

    // Validate the request parameter
    $request->validate([
        'type' => 'required|in:pickup',
    ]);

    $type = $request->input('type'); // 'pickup'

    // Fetch all orders with the given pickup agent ID
    $orders = DB::table('orders')
        ->select(
            'orders.id', 'orders.order_id', 'orders.user_id', 'orders.vendor_id', 'orders.vendor_address',
            'orders.vendor_latitude', 'orders.vendor_longitude', 'orders.user_latitude', 'orders.user_longitude',
            'orders.status', 'orders.created_at as order_date', 'orders.user_total_cost', 'orders.payment_mode',
            'customer.name as customer_name', 'customer.phone_number as customer_contact_number',
            'orders.customer_address as customer_address', 
            'vendor.name as vendor_name', 'vendor.phone_number as vendor_contact_number'
        )
        ->join('users as customer', 'customer.user_id', '=', 'orders.user_id') // Join orders with users table for customer
        ->join('users as vendor', 'vendor.user_id', '=', 'orders.vendor_id') // Join orders with users table for vendor
        ->where('orders.pickup_agent_id', $user->user_id)
        ->whereIn('orders.status', [
            'Pending', 'Accepted', 'Pickup In Progress', 'Picked Up',
            'At Vendor', 'Ready for Delivery', 'Delivery In Progress',
            'Delivered', 'Completed', 'Cancelled'
        ])
        ->get();

    // Prepare the response format
    $response = [
        'pickup_pending' => [],
        'pickedup' => [],
    ];

    foreach ($orders as $order) {
        $orderDetails = [
            'order_id' => $order->order_id,
            'pickup' => [
                'lat' => $order->user_latitude,
                'lng' => $order->user_longitude,
                'to_lat' => $order->vendor_latitude,
                'to_lng' => $order->vendor_longitude,
                'from' => 'customer',
                'name' => $order->customer_name,
                'contact_number' => $order->customer_contact_number,
                'address' => $order->customer_address,
                'ht_reach' => '', // Assuming it's an empty field for now
            ],
            'delivery' => [
                'lat' => $order->vendor_latitude,
                'lng' => $order->vendor_longitude,
                'to' => 'vendor',
                'name' => $order->vendor_name,
                'contact_number' => $order->vendor_contact_number,
                'address' => $order->vendor_address,
                'ht_reach' => '', // Assuming it's an empty field for now
            ]
        ];

        // Categorize orders based on their status
        if (in_array($order->status, ['Accepted', 'Pickup In Progress'])) {
            // Orders in these statuses fall under `pickup_pending`
            $response['pickup_pending'][] = $orderDetails;
        } elseif (in_array($order->status, ['Picked Up', 'At Vendor', 'Ready for Delivery', 'Delivery In Progress'])) {
            // Orders in these statuses fall under `pickedup`
            $response['pickedup'][] = $orderDetails;
        }
    }

    // Ensure keys are always present, even if no data
    $response['pickup_pending'] = $response['pickup_pending'] ?? [];

    $response['pickedup'] = $response['pickedup'] ?? [];

    return response()->json($response);
}












   public function updateOnlineStatus(Request $request)
{
    // Get authenticated user
    $user = Auth::user();

    // Validate the request input for 'status'
    $status = $request->input('status');
    if (!in_array($status, ['online', 'offline'])) {
        return response()->json(['message' => 'Invalid status. Use "online" or "offline".'], 400);
    }

    // Determine the online status value based on input
    $onlineStatus = ($status === 'online') ? 1 : 0;

    // Update the online status based on the user's role
    if ($user->role === 'driver') {
        // Update online_status for drivers table
        DB::update('UPDATE drivers SET online_status = ? WHERE user_id = ?', [$onlineStatus, $user->user_id]);
    } elseif ($user->role === 'vendor') {
        // Update online_status for vendors table
        DB::update('UPDATE vendors SET online_status = ? WHERE user_id = ?', [$onlineStatus, $user->user_id]);
    } else {
        return response()->json(['message' => 'Invalid role or not authorized'], 403);
    }

    return response()->json(['message' => 'Online status updated successfully', 'status' => $status], 200);
}
    /**
     * Store a newly created driver in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
public function store(Request $request)
{
    // Retrieve the authenticated user
    $user = auth()->user();
    if (!$user) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    // Custom validation with detailed error handling
    $validator = Validator::make($request->all(), [
        'driving_license_number' => 'nullable|string|max:255',
        'driving_license_expiry' => 'nullable|date',
        'pan_card_number' => 'nullable|string|max:255',
        'aadhar_card_number' => 'nullable|string|max:255',
        'bike_brand' => 'nullable|string|max:255',
        'bike_model' => 'nullable|string|max:255',
        'bike_year' => 'nullable|integer|digits:4',
        'bike_registration_plate' => 'nullable|string|max:255',
        'vehicle_number' => 'nullable|string|max:255',
        'chassis_number' => 'nullable|string|max:255',
        'insurance_number' => 'nullable|string|max:255',
        'insurance_expiry' => 'nullable|date',
        'vehicle_inspection_date' => 'nullable|date',
        'inspection_expiry_date' => 'nullable|date',
        // File validations
        'profile_photo' => 'nullable|image|max:2048',
        'driving_license_front' => 'required|image|max:2048',
        'driving_license_back' => 'nullable|image|max:2048',
        'pan_card_photo' => 'nullable|image|max:2048',
        'aadhar_card_front' => 'nullable|image|max:2048',
        'aadhar_card_back' => 'nullable|image|max:2048',
        'vehicle_picture_front' => 'nullable|image|max:2048',
        'vehicle_picture_back' => 'nullable|image|max:2048',
        'vehicle_picture_left' => 'nullable|image|max:2048',
        'vehicle_picture_right' => 'nullable|image|max:2048',
        'vehicle_document_1' => 'nullable|file|max:2048',
        'vehicle_document_2' => 'nullable|file|max:2048',
        'vehicle_document_3' => 'nullable|file|max:2048',
        'vehicle_document_4' => 'nullable|file|max:2048',
         'location' => 'nullable|string',
        'longitude' => 'nullable|string|between:-180,180',
        'latitude' => 'nullable|string|between:-90,90',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'success' => false,
            'message' => 'Validation errors',
            'errors' => $validator->errors(),
        ], 422);
    }

    // Check if a driver record already exists for this user
    $driver = Driver::where('user_id', $user->user_id)->first();

    // Handle file uploads and delete old files if needed
    $filePaths = $this->handleFileUploads($request, [
        'driving_license_front', 'driving_license_back', 'pan_card_photo', 'profile_photo',
        'aadhar_card_front', 'aadhar_card_back', 'vehicle_picture_front',
        'vehicle_picture_back', 'vehicle_picture_left', 'vehicle_picture_right',
        'vehicle_document_1', 'vehicle_document_2', 'vehicle_document_3', 'vehicle_document_4'
    ]);

    if ($driver) {
        // Delete old files if they exist before updating paths
        $this->deleteExistingFiles($driver);

        // Update the existing driver record with new data
        $driver->update(array_merge($validator->validated(), $filePaths));
    } else {
        // Create a new driver record
        $driverData = array_merge($validator->validated(), $filePaths, [
            'user_id' => $user->user_id, // Set user_id from the authenticated user
        ]);
        $driver = Driver::create($driverData);
    }

    return response()->json([
        'success' => true,
        'data' => $driver,
        'message' => 'Driver record saved successfully!',
    ], 200);
}
public function storeDrivingLicense(Request $request)
{
     $user = auth()->user();
    if (!$user) {
        return response()->json(['error' => 'Unauthdfgorized'], 401);
    }

    \Log::info('Authenticated User:', ['user' => $user]);

    $validator = Validator::make($request->all(), [
        'driving_license_number' => 'required|string|max:255|unique:drivers,driving_license_number',
        'driving_license_expiry' => 'required|date',
        'driving_license_front' => 'required|image|max:2048',
        'driving_license_back' => 'required|image|max:2048',
        
    ]);

    if ($validator->fails()) {
        return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
    }

    $filePaths = $this->handleFileUploads($request, ['driving_license_front', 'driving_license_back']);

    try {
        DB::table('drivers')->updateOrInsert(
            ['user_id' => $user->user_id],  // Ensure correct user ID reference
            array_merge($validator->validated(), $filePaths)
        );

        return response()->json(['success' => true, 'message' => 'Driving License details saved!'], 200);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'error' => 'Database error', 'message' => $e->getMessage()], 500);
    }
}


    // Step 2: Store Aadhar Card Details
    public function storeAadharDetails(Request $request)
    {
        $user = auth()->user();
        if (!$user) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $validator = Validator::make($request->all(), [
            'aadhar_card_number' => 'required|string|max:255|unique:drivers',
            'aadhar_card_front' => 'required|image|max:2048',
            'aadhar_card_back' => 'required|image|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $filePaths = $this->handleFileUploads($request, ['aadhar_card_front', 'aadhar_card_back']);

        DB::table('drivers')->updateOrInsert(
            ['user_id' => $user->user_id],
            array_merge($validator->validated(), $filePaths)
        );

        return response()->json(['success' => true, 'message' => 'Aadhar details saved!'], 200);
    }

    // Step 3: Store PAN Card Details
    public function storePanCardDetails(Request $request)
    {
        $user = auth()->user();
        if (!$user) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $validator = Validator::make($request->all(), [
            'pan_card_number' => 'required|string|max:255|unique:drivers',
            'pan_card_photo' => 'required|image|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $filePaths = $this->handleFileUploads($request, ['pan_card_photo']);

        DB::table('drivers')->updateOrInsert(
            ['user_id' => $user->user_id],
            array_merge($validator->validated(), $filePaths)
        );

        return response()->json(['success' => true, 'message' => 'PAN details saved!'], 200);
    }

public function storeVehicleImages(Request $request)
{
    $user = auth()->user();
    if (!$user) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    // Validation Rules
    $validator = Validator::make($request->all(), [
        'vehicle_picture_front' => 'required|image|max:2048',
        'vehicle_picture_back' => 'required|image|max:2048',
        'vehicle_picture_left' => 'nullable|image|max:2048',
        'vehicle_picture_right' => 'nullable|image|max:2048',
        'vehicle_document_1' => 'required|image|max:2048',
        'vehicle_document_2' => 'required|image|max:2048',
        'vehicle_document_3' => 'nullable|image|max:2048',
        'vehicle_document_4' => 'nullable|image|max:2048',
    ]);

    if ($validator->fails()) {
        return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
    }

    // Handle File Uploads
    $filePaths = [];
    foreach ($validator->validated() as $key => $file) {
        if ($request->hasFile($key)) {
            $filePaths[$key] = $request->file($key)->store('vehicle_images', 'public');
        }
    }
    

    // Save to Database
    DB::table('drivers')->updateOrInsert(
        ['user_id' => $user->user_id],
        array_merge($filePaths, ['updated_at' => now()])
    );

    return response()->json(['success' => true, 'message' => 'Vehicle images saved successfully!'], 200);
}


    // Step 4: Store Vehicle Details
   public function storeVehicleDetails(Request $request)
{
    $user = auth()->user();
    if (!$user) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    // Validation Rules
    $validator = Validator::make($request->all(), [
        'bike_brand' => 'required|string|max:255',
        'bike_model' => 'required|string|max:255',
        'bike_year' => 'required|integer|digits:4',
        'bike_registration_plate' => 'nullable|string|max:255',
        'vehicle_number' => 'nullable|string|max:255',
        'chassis_number' => 'nullable|string|max:255',
        'insurance_number' => 'nullable|string|max:255',
        'insurance_expiry' => 'nullable|date',
        'vehicle_inspection_date' => 'nullable|date',
        'inspection_expiry_date' => 'nullable|date',
    ]);

    if ($validator->fails()) {
        return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
    }

    // Extracting validated data
    $data = $validator->validated();

    // Checking for uniqueness but allowing the same user to update their own details
    $uniqueFields = ['bike_registration_plate', 'vehicle_number', 'chassis_number'];
    foreach ($uniqueFields as $field) {
        if (!empty($data[$field])) {
            $existingRecord = DB::table('drivers')
                ->where($field, $data[$field])
                ->where('user_id', '!=', $user->user_id) // Ensure it's not the same user
                ->exists();

            if ($existingRecord) {
                return response()->json([
                    'success' => false,
                    'error' => ucfirst(str_replace('_', ' ', $field)) . ' is already registered by another user.'
                ], 422);
            }
        }
    }

    // Insert or update for the authenticated user
    DB::table('drivers')->updateOrInsert(
        ['user_id' => $user->user_id],  // Ensures only updating the same user
        $data
    );

    return response()->json(['success' => true, 'message' => 'Vehicle details saved successfully!'], 200);
}


    // Handle file uploads
    private function handleFileUploads(Request $request, array $fields)
    {
        $filePaths = [];

        foreach ($fields as $field) {
            if ($request->hasFile($field)) {
                $filePaths[$field] = $request->file($field)->store('drivers', 'public');
            }
        }

        return $filePaths;
    }

/**
 * Delete existing files associated with the driver record.
 */
private function deleteExistingFiles($driver)
{
    $fileFields = [
        'driving_license_front', 'driving_license_back', 'pan_card_photo', 
        'aadhar_card_front', 'aadhar_card_back', 'vehicle_picture_front','profile_photo',
        'vehicle_picture_back', 'vehicle_picture_left', 'vehicle_picture_right',
        'vehicle_document_1', 'vehicle_document_2', 'vehicle_document_3', 'vehicle_document_4'
    ];

    foreach ($fileFields as $field) {
        if ($driver->$field) {
            $filePath = $driver->$field; // The path stored in DB (e.g., drivers/filename.jpg)
            if (Storage::disk('public')->exists($filePath)) {
                Storage::disk('public')->delete($filePath);
            }
        }
    }
}



    /**
     * Handle file uploads.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $fields
     * @return array
     */
//     private function handleFileUploads(Request $request, array $fields)
// {
//     $filePaths = [];
//     $baseFolder = 'drivers/'; // Base folder for driver files

//     foreach ($fields as $field) {
//         if ($request->hasFile($field)) {
//             // Store the file in the drivers folder and get the relative path
//             $filePaths[$field] = $request->file($field)->store($baseFolder, 'public');
//         }
//     }

//     return $filePaths;
// }

    /**
     * Show the specified driver details.
     *
     * @param  \App\Models\Driver  $driver
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Driver $driver)
    {
        return response()->json([
            'success' => true,
            'data' => $driver,
        ], 200);
    }

    /**
     * Update the specified driver in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Driver  $driver
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Driver $driver)
    {
        // Custom validation
        $validator = Validator::make($request->all(), [
            // Add appropriate validation rules similar to the store method
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation errors',
                'errors' => $validator->errors(),
            ], 422);
        }

        // Handle file uploads for updating files
        $filePaths = $this->handleFileUploads($request, [
            'driving_license_front', 'driving_license_back', 'pan_card_photo', 
            'aadhar_card_front', 'aadhar_card_back', 'vehicle_picture_front',
            'vehicle_picture_back', 'vehicle_picture_left', 'vehicle_picture_right',
            'vehicle_document_1', 'vehicle_document_2', 'vehicle_document_3', 'vehicle_document_4'
        ]);

        // Update driver details
        try {
            $driver->update(array_merge($validator->validated(), $filePaths));
            return response()->json([
                'success' => true,
                'message' => 'Driver updated successfully!',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating driver',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Remove the specified driver from storage.
     *
     * @param  \App\Models\Driver  $driver
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Driver $driver)
    {
        try {
            // Delete associated files if needed
            $this->deleteDriverFiles($driver);
            
            $driver->delete();
            return response()->json([
                'success' => true,
                'message' => 'Driver deleted successfully!',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting driver',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Delete the files associated with a driver.
     *
     * @param  \App\Models\Driver  $driver
     * @return void
     */
    private function deleteDriverFiles(Driver $driver)
    {
        $fileFields = [
            'driving_license_front', 'driving_license_back', 'pan_card_photo',
            'aadhar_card_front', 'aadhar_card_back', 'vehicle_picture_front',
            'vehicle_picture_back', 'vehicle_picture_left', 'vehicle_picture_right',
            'vehicle_document_1', 'vehicle_document_2', 'vehicle_document_3', 'vehicle_document_4'
        ];

        foreach ($fileFields as $field) {
            if ($driver->$field && Storage::disk('public')->exists($driver->$field)) {
                Storage::disk('public')->delete($driver->$field);
            }
        }
    }
}
