<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Driver;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class DriverController extends Controller
{
  public function store(Request $request)
{
    // Detailed validation with file handling
    $validator = Validator::make($request->all(), [
        'driving_license_number' => 'required|string|max:255',
        'driving_license_expiry' => 'required|date',
        'pan_card_number' => 'required|string|max:255',
        'aadhar_card_number' => 'required|string|max:255',
        'bike_brand' => 'required|string|max:255',
        'bike_model' => 'required|string|max:255',
        'bike_year' => 'required|integer|digits:4',
        'bike_registration_plate' => 'required|string|max:255',
        'vehicle_number' => 'required|string|max:255',
        'chassis_number' => 'required|string|max:255',
        'insurance_number' => 'required|string|max:255',
        'insurance_expiry' => 'required|date',
        'vehicle_inspection_date' => 'required|date',
        'inspection_expiry_date' => 'required|date',
        'location' => 'required|string',
        'longitude' => 'required|numeric|between:-180,180',
        'latitude' => 'required|numeric|between:-90,90',
        // File validations
        'profile_photo' => 'nullable|image|max:2048',
        'driving_license_front' => 'nullable|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',
    ]);

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

    // Generate unique ID and create user in `users` table
    $role = 'driver';
    $uniqueUserId = $this->generateUniqueId($role);

    // Insert the user data into `users` table using raw query
    $userData = [
        'name' => $request->name,
        'phone_number' => $request->phone_number,
        'email' => $request->email,
        'user_id' => $uniqueUserId,
        'role' => 'driver',
        'wallet' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ];

    DB::table('users')->insert($userData);

    // Handle file uploads
    $filePaths = $this->handleFileUploads($request, [
        'profile_photo', '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'
    ]);

    // Merge the validated data with file paths and user_id
    $driverData = array_merge($validator->validated(), $filePaths, ['user_id' => $uniqueUserId]);

    // Insert the driver data into `drivers` table using raw query
    DB::table('drivers')->insert($driverData);

    return response()->json([
        'success' => true,
        'data' => $driverData,
        'message' => 'Driver added successfully!',
    ], 201);
}

private function generateUniqueId($role)
{
    $prefix = match($role) {
        'vendor' => 'CleaneoVendor',
        'driver' => 'CleaneoAgent',
        'admin' => 'CleaneoAdmin',
        default => 'Cleaneo',
    };

    // Fetch the latest user ID for this role
    $latestUser = DB::table('users')
                    ->where('role', $role)
                    ->orderBy('id', 'desc')
                    ->first();

    $lastId = $latestUser ? (int)substr($latestUser->user_id, strlen($prefix)) : 0;
    $newId = str_pad($lastId + 1, $role === 'vendor' ? 6 : 5, '0', STR_PAD_LEFT);

    return $prefix . $newId;
}


    public function update(Request $request, Driver $driver)
    {
        // Validation with detailed error handling
        $validator = Validator::make($request->all(), [
            'driving_license_number' => 'nullable|string|max:255',
            // Additional fields and validation rules
        ]);

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

        // Handle file uploads for updating
        $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 data
        $driver->update(array_merge($validator->validated(), $filePaths));

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

    public function destroy(Driver $driver)
    {
        $this->deleteDriverFiles($driver);
        $driver->delete();

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

    private function handleFileUploads(Request $request, array $fields)
    {
        $filePaths = [];
        $baseFolder = 'drivers/';

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

        return $filePaths;
    }
     public function index()
    {
        $drivers = Driver::all();
        return view('components.delivery_add', compact('drivers'));
    }

    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);
            }
        }
    }
}
