<?php

namespace App\Http\Livewire;

use App\Models\Brand;
use App\Models\Carburant;
use App\Models\City;
use App\Models\Company;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Garage;
use App\Models\Guarantee;
use App\Models\Insured;
use App\Models\Intermidiaire;
use App\Models\Mode;
use App\Models\Opponent;
use App\Models\Step;
use App\Models\TypeDocument;
use App\Models\TypeExpertise;
use App\Models\TypeVehicule;
use App\Models\User;
use App\Models\VehiculeModel;
use Carbon\Carbon;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Livewire\WithFileUploads;

class DossierWizard extends Component
{
    use WithFileUploads;

    // Brand/Model selections
    public $selectedBrand, $models;
    public $selectedBrandop, $modelsop;
    
    // Brand autocomplete
    public $brandSearch = '';
    public $brandResults = [];
    public $showBrandDropdown = false;
    public $selectedBrandName = '';
    
    // City autocomplete
    public $citySearch = '';
    public $cityResults = [];
    public $showCityDropdown = false;
    public $selectedCityName = '';
    
    // Garage autocomplete
    public $garageSearch = '';
    public $garageResults = [];
    public $showGarageDropdown = false;
    public $selectedGarageName = '';
    
    // Intermediaire autocomplete
    public $intermediaireSearch = '';
    public $intermediaireResults = [];
    public $showIntermediaireDropdown = false;
    public $selectedIntermediaireName = '';
    
    // Opponent Brand autocomplete
    public $brandSearchOp = '';
    public $brandResultsOp = [];
    public $showBrandDropdownOp = false;
    public $selectedBrandNameOp = '';
    
    // Document upload management
    public $uploadedFiles = [];
    public $fileTypes = []; // Array to store type for each file
    
    // Dossier search results
    public $dossiers = [];
    public $dossiers1 = [];
    public $dossiersByChassis = [];
    public $dossiersByName = [];
    public $selectedDossier, $selectedDossier1;
    
    // Documents
    public $pv, $declaration, $constat;
    
    // Insurance
    public $insurances;
    
    // Counter and UI state
    public $count = 0;
    public $hidden = true;
    public $showChassisResults = false;
    public $showNameResults = false;
    public $searchingMatricule = false;
    public $searchingChassis = false;
    public $searchingName = false;
    
    // Form fields
    public $type_vehicule_id, $civility, $city_id, $points, $carburant, $puissance_fiscale;
    public $mode_id, $kilometrage, $civilityop, $matriculeop, $garage_id, $type_expertise_id;
    public $nameop, $telephoneop, $intermidiaire_id, $companyop_id, $vehicule_modelop_id;
    public $new_matricule, $chassis_number, $matricule, $name, $telephone, $tel, $telop;
    public $company_id, $vehicule_model_id, $guarantee_id, $type_dossier_id;
    public $date_sinistre, $date_reception, $circulation_date;
    public $numero_police, $numero_sinistre, $numero_attestation, $numero_attestationop;
    
    // API vehicle data
    public $api_brand_name, $api_model_name, $api_year;
    
    // Debounce timers (milliseconds)
    protected $debounceTime = 300;

    // Listeners for JavaScript events
    protected $listeners = [
        'searchMatricule' => 'searchMatricule',
        'searchNewMatricule' => 'searchNewMatricule',
        'searchChassis' => 'searchChassis',
        'searchByName' => 'searchByName',
        'setVehicleFromApi' => 'setVehicleFromApi',
        'formatMatricule' => 'formatMatricule',
        'formatNewMatricule' => 'formatNewMatricule',
    ];

    /**
     * Format old-style Moroccan matricule (XXXXX-X-XX)
     */
    public function formatMatricule($value)
    {
        $this->matricule = $this->formatOldMatricule($value);
    }

    /**
     * Format WW-style Moroccan matricule
     */
    public function formatNewMatricule($value)
    {
        $this->new_matricule = $this->formatWWMatricule($value);
    }

    /**
     * Helper: Format old matricule (XXXXX-X-XX)
     */
    private function formatOldMatricule($value)
    {
        // Remove all non-alphanumeric except dashes
        $clean = preg_replace('/[^A-Za-z0-9]/', '', strtoupper($value));
        
        // Format: XXXXX-X-XX (5 digits, 1 letter, 2 digits)
        $formatted = '';
        $len = strlen($clean);
        
        if ($len >= 1) {
            // First part: up to 5 digits
            $part1 = substr($clean, 0, min(5, $len));
            $formatted = $part1;
        }
        
        if ($len > 5) {
            // Second part: 1 letter
            $part2 = substr($clean, 5, 1);
            if (preg_match('/[A-Z]/', $part2)) {
                $formatted .= '-' . $part2;
            }
        }
        
        if ($len > 6) {
            // Third part: up to 2 digits
            $part3 = substr($clean, 6, min(2, $len - 6));
            if (preg_match('/^[0-9]+$/', $part3)) {
                $formatted .= '-' . $part3;
            }
        }
        
        return $formatted;
    }

    /**
     * Helper: Format WW matricule (WW-XXXXXX)
     */
    private function formatWWMatricule($value)
    {
        // Remove all non-alphanumeric except dashes
        $clean = preg_replace('/[^A-Za-z0-9]/', '', strtoupper($value));
        
        // If starts with WW, format as WW-XXXXXX
        if (substr($clean, 0, 2) === 'WW') {
            $numbers = substr($clean, 2, 6);
            if (strlen($numbers) > 0) {
                return 'WW-' . $numbers;
            }
            return 'WW-';
        }
        
        // If it's just numbers, assume they meant WW prefix
        if (preg_match('/^[0-9]+$/', $clean)) {
            return 'WW-' . substr($clean, 0, 6);
        }
        
        return strtoupper($value);
    }

    /**
     * Search dossiers by old matricule
     */
    public function searchMatricule($value = null)
    {
        $search = $value ?? $this->matricule;
        $this->searchingMatricule = true;
        
        if (empty($search) || strlen($search) < 3) {
            $this->dossiers = [];
            $this->searchingMatricule = false;
            return;
        }

        // Normalize search (remove dashes, dots, spaces)
        $normalized = preg_replace('/[^A-Za-z0-9]/', '', strtoupper($search));
        
        $this->dossiers = Dossier::where(function($query) use ($normalized, $search) {
            $query->whereRaw("REPLACE(REPLACE(REPLACE(IFNULL(matricule,''), '.', ''), ' ', ''), '-', '') LIKE ?", ['%' . $normalized . '%'])
                  ->orWhere('matricule', 'like', '%' . $search . '%');
        })
        ->with(['insured', 'vehiculemodel.brand', 'company'])
        ->latest()
        ->take(10)
        ->get();
        
        $this->searchingMatricule = false;
        // Don't auto-show - user must click "Afficher"
        // $this->hidden stays as is
    }

    /**
     * Search dossiers by new (WW) matricule
     */
    public function searchNewMatricule($value = null)
    {
        $search = $value ?? $this->new_matricule;
        $this->searchingMatricule = true;
        
        if (empty($search) || strlen($search) < 3) {
            $this->dossiers1 = [];
            $this->searchingMatricule = false;
            return;
        }

        // Normalize search
        $normalized = preg_replace('/[^A-Za-z0-9]/', '', strtoupper($search));
        
        $this->dossiers1 = Dossier::where(function($query) use ($normalized, $search) {
            $query->whereRaw("REPLACE(REPLACE(REPLACE(IFNULL(new_matricule,''), '.', ''), ' ', ''), '-', '') LIKE ?", ['%' . $normalized . '%'])
                  ->orWhere('new_matricule', 'like', '%' . $search . '%');
        })
        ->with(['insured', 'vehiculemodel.brand', 'company'])
        ->latest()
        ->take(10)
        ->get();
        
        $this->searchingMatricule = false;
        // Don't auto-show - user must click "Afficher"
        // $this->hidden stays as is
    }

    /**
     * Search dossiers by VIN/Chassis number
     */
    public function searchChassis($value = null)
    {
        $search = $value ?? $this->chassis_number;
        $this->searchingChassis = true;
        
        if (empty($search) || strlen($search) < 5) {
            $this->dossiersByChassis = [];
            $this->searchingChassis = false;
            $this->showChassisResults = false;
            return;
        }

        // Normalize search (remove spaces, dashes)
        $normalized = preg_replace('/[^A-Za-z0-9]/', '', strtoupper($search));
        
        $this->dossiersByChassis = Dossier::where(function($query) use ($normalized, $search) {
            $query->whereRaw("REPLACE(REPLACE(REPLACE(IFNULL(numero_chassis,''), '.', ''), ' ', ''), '-', '') LIKE ?", ['%' . $normalized . '%'])
                  ->orWhere('numero_chassis', 'like', '%' . $search . '%');
        })
        ->with(['insured', 'vehiculemodel.brand', 'company'])
        ->latest()
        ->take(10)
        ->get();
        
        $this->searchingChassis = false;
        // Don't auto-show - user must click "Afficher"
        // $this->showChassisResults stays false until user clicks
    }

    /**
     * Search dossiers by client/insured name
     */
    public function searchByName($value = null)
    {
        $search = $value ?? $this->name;
        $this->searchingName = true;
        
        if (empty($search) || strlen($search) < 2) {
            $this->dossiersByName = [];
            $this->searchingName = false;
            $this->showNameResults = false;
            return;
        }

        $this->dossiersByName = Dossier::whereHas('insured', function($query) use ($search) {
            $query->where('name', 'like', '%' . $search . '%');
        })
        ->with(['insured', 'vehiculemodel.brand', 'company'])
        ->latest()
        ->take(10)
        ->get();
        
        $this->searchingName = false;
        // Don't auto-show - user must click "Afficher"
        // $this->showNameResults stays false until user clicks
    }

    /**
     * Set vehicle details from API selection
     */
    public function setVehicleFromApi($brandName, $modelName, $year = null)
    {
        $this->api_brand_name = $brandName;
        $this->api_model_name = $modelName;
        $this->api_year = $year;
        
        // Try to find matching brand in local database
        if ($brandName) {
            $brand = Brand::where('brand', 'like', '%' . $brandName . '%')->first();
            if ($brand) {
                $this->selectedBrand = $brand->id;
                $this->updatedSelectedBrand($brand->id);
                
                // Try to find matching model
                if ($modelName) {
                    $model = VehiculeModel::where('brand_id', $brand->id)
                        ->where('name', 'like', '%' . $modelName . '%')
                        ->first();
                    if ($model) {
                        $this->vehicule_model_id = $model->id;
                    }
                }
            }
        }
    }

    /**
     * Updated hooks for real-time search (debounced from JS)
     */
    public function updatedMatricule($value)
    {
        // Auto-format
        $this->matricule = $this->formatOldMatricule($value);
    }

    public function updatedNewMatricule($value)
    {
        // Auto-format
        $this->new_matricule = $this->formatWWMatricule($value);
    }

    public function updatedChassisNumber($value)
    {
        // Normalize to uppercase
        $this->chassis_number = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $value));
    }

    /**
     * Validation step: Assuré & Véhicule
     */
    public function vehiculeStep()
    {
        $this->validatedData = $this->validate([
            'telephone' => 'nullable|min:10|max:10',
            'new_matricule' => 'required_without:matricule|size:9|nullable',
            'matricule' => 'required_without:new_matricule|nullable',
            'date_sinistre' => 'required|date',
            'name' => 'required',
            'company_id' => 'required',
            'numero_sinistre' => 'required|unique:dossiers,numero_sinistre',
            'date_reception' => 'required',
            'type_expertise_id' => 'required',
            'mode_id' => 'required',
            'chassis_number' => 'min:17|max:17|nullable',
            'puissance_fiscale' => 'nullable|numeric',
            'kilometrage' => 'nullable|numeric',
        ]);

        $this->count++;
    }

    /**
     * Validation step: Insurance (kept for compatibility)
     */
    public function insuranceStep()
    {
        $this->validatedData = $this->validate([
            'type_expertise_id' => 'required',
            'mode_id' => 'required',
            'chassis_number' => 'min:17|max:17|nullable',
            'puissance_fiscale' => 'nullable|numeric',
            'kilometrage' => 'nullable|numeric',
        ]);
        
        $this->count++;
    }

    /**
     * Validation step: Opponent
     */
    public function opponentStep()
    {
        $this->validatedData = $this->validate([
            'matriculeop' => 'nullable',
            'telephoneop' => 'nullable|min:10|max:10',
        ]);
        $this->count++;
    }

    /**
     * Create dossier
     */
    public function createStep()
    {
        $this->validatedData = $this->validate([
            'type_expertise_id' => 'required',
            'mode_id' => 'required',
            'chassis_number' => 'min:17|max:17|nullable',
            'puissance_fiscale' => 'nullable|numeric',
            'kilometrage' => 'nullable|numeric',
            'telephone' => 'nullable|min:10|max:10',
            'new_matricule' => 'required_without:matricule|nullable',
            'matricule' => 'required_without:new_matricule|nullable',
            'date_sinistre' => 'required|date',
            'name' => 'required',
            'company_id' => 'required',
            'numero_sinistre' => 'required|unique:dossiers,numero_sinistre',
            'date_reception' => 'required'
        ]);

        $currentMonthCount = Dossier::whereMonth('created_at', Carbon::now()->month)
            ->whereYear('created_at', Carbon::now()->year)
            ->withTrashed()
            ->count();
        $currentMonthCount++;

        $tel = $this->telephone ?: null;
        
        $insured = Insured::create([
            'civility' => $this->civility,
            'name' => $this->name,
            'telephone' => $tel,
        ]);

        // Null checks for optional fields
        $this->garage_id = $this->garage_id ?: null;
        $this->company_id = $this->company_id ?: null;
        $this->companyop_id = $this->companyop_id ?: null;
        $this->carburant = $this->carburant ?: null;
        $this->vehicule_model_id = $this->vehicule_model_id ?: null;
        $this->intermidiaire_id = $this->intermidiaire_id ?: null;
        $this->guarantee_id = $this->guarantee_id ?: null;
        $this->type_expertise_id = $this->type_expertise_id ?: null;
        $this->mode_id = $this->mode_id ?: null;
        $this->city_id = $this->city_id ?: null;
        $this->type_vehicule_id = $this->type_vehicule_id ?: null;

        $opponent = null;
        if ($this->nameop || $this->matriculeop || $this->telephoneop || $this->companyop_id || $this->vehicule_modelop_id || $this->numero_attestationop) {
            $opponent = Opponent::create([
                'civility' => $this->civilityop,
                'matricule' => $this->matriculeop,
                'name' => $this->nameop,
                'telephone' => $this->telephoneop,
                'company_id' => $this->companyop_id,
                'vehicule_model_id' => $this->vehicule_modelop_id ?? null,
                'numero_attestation' => $this->numero_attestationop
            ]);
        }

        $dossier = Dossier::create([
            'insured_id' => $insured->id,
            'opponent_id' => $opponent->id ?? null,
            'new_matricule' => $this->new_matricule,
            'matricule' => $this->matricule,
            'carburant_id' => $this->carburant,
            'date_circulation' => $this->circulation_date,
            'vehicule_model_id' => $this->vehicule_model_id ?? null,
            'intermidiaire_id' => $this->intermidiaire_id,
            'company_id' => $this->company_id,
            'guarantee_id' => $this->guarantee_id,
            'date_sinistre' => $this->date_sinistre,
            'date_reception' => $this->date_reception,
            'numero_sinistre' => $this->numero_sinistre,
            'numero_attestation' => $this->numero_attestation,
            'numero_chassis' => $this->chassis_number,
            'numero_police' => $this->numero_police,
            'type_expertise_id' => $this->type_expertise_id,
            'dossier_status_id' => 2,
            'mode_id' => $this->mode_id,
            'city_id' => $this->city_id,
            'garage_id' => $this->garage_id,
            'kilometrage' => $this->kilometrage,
            'puissance_fiscale' => $this->puissance_fiscale,
            'step_id' => 1,
            'user_id' => Auth::user()->id,
            'type_vehicule_id' => $this->type_vehicule_id,
            'currency_id' => 1,
            // Store API vehicle info if local not found
            'api_brand_name' => $this->api_brand_name,
            'api_model_name' => $this->api_model_name,
        ]);

        $dossier->ref = $currentMonthCount . date('m') . date('Y');
        $dossier->update();

        $user = User::whereId(Auth::user()->id)->first();
        $step = Step::whereId(1)->first();
        $dossier->step()->attach($step, ['user_id' => $user->id]);

        // Handle document uploads
        $this->handleDocumentUploads($dossier);

        if (!empty($this->constat)) {
            return redirect()->route('ShockPoint.create', $dossier->id);
        }

        return redirect()->route('Dossier.show', $dossier->id);
    }

    /**
     * Handle document uploads
     */
    private function handleDocumentUploads($dossier)
    {
        // Process unified file uploads with type assignments
        if (!empty($this->uploadedFiles)) {
            foreach ($this->uploadedFiles as $index => $file) {
                $typeId = $this->fileTypes[$index] ?? null;
                if (!$typeId) continue; // Skip files without type assignment
                
                // Determine folder based on type
                $folderMap = [
                    '1' => 'PV',
                    '2' => 'Constat', 
                    '3' => 'Declaration'
                ];
                $folder = $folderMap[$typeId] ?? 'Other';
                $type = TypeDocument::find($typeId);
                $typeName = $type ? $type->type : $folder;
                
                // Check if file is PDF
                $pdfMimes = ['application/pdf', 'application/x-pdf', 'application/acrobat', 'application/vnd.pdf', 'text/pdf', 'text/x-pdf'];
                $isPdf = in_array($file->getMimeType(), $pdfMimes) || strtolower($file->getClientOriginalExtension()) == 'pdf';
                
                if ($isPdf) {
                    // Convert PDF to images using Imagick
                    $this->convertPdfToImages($file, $dossier, $typeId, $typeName);
                } else {
                    // Process regular image with watermark
                    $this->processImageFile($file, $dossier, $typeId, $typeName);
                }
            }
        }

        // Legacy support for old separate uploads
        if (!empty($this->declaration)) {
            foreach ($this->declaration as $declar) {
                $this->processFileWithConversion($declar, $dossier, 3, 'Declaration');
            }
        }

        if (!empty($this->pv)) {
            foreach ($this->pv as $pv) {
                $this->processFileWithConversion($pv, $dossier, 1, 'PV');
            }
        }

        if (!empty($this->constat)) {
            foreach ($this->constat as $consta) {
                $this->processFileWithConversion($consta, $dossier, 2, 'Constat');
            }
        }
    }

    /**
     * Process file with PDF conversion if needed
     */
    private function processFileWithConversion($file, $dossier, $typeId, $typeName)
    {
        $pdfMimes = ['application/pdf', 'application/x-pdf', 'application/acrobat', 'application/vnd.pdf', 'text/pdf', 'text/x-pdf'];
        $isPdf = in_array($file->getMimeType(), $pdfMimes) || strtolower($file->getClientOriginalExtension()) == 'pdf';
        
        if ($isPdf) {
            $this->convertPdfToImages($file, $dossier, $typeId, $typeName);
        } else {
            $this->processImageFile($file, $dossier, $typeId, $typeName);
        }
    }

    /**
     * Convert PDF to images and save each page
     */
    private function convertPdfToImages($file, $dossier, $typeId, $typeName)
    {
        // Create temp directory
        $tempDir = storage_path('app/temp/pdf_' . uniqid());
        if (!file_exists($tempDir)) {
            mkdir($tempDir, 0755, true);
        }
        
        $tempPdfPath = $tempDir . '/' . uniqid() . '.pdf';
        copy($file->getRealPath(), $tempPdfPath);
        
        if (extension_loaded('imagick')) {
            try {
                $imagick = new \Imagick();
                $imagick->setResolution(150, 150);
                $imagick->readImage($tempPdfPath);
                $pageCount = $imagick->getNumberImages();
                
                for ($i = 0; $i < $pageCount; $i++) {
                    $imagick->setIteratorIndex($i);
                    $imagick->setImageFormat('png');
                    $imagick->setImageCompressionQuality(90);
                    $imagick->setImageBackgroundColor('white');
                    $imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
                    
                    $tempImagePath = $tempDir . '/' . uniqid() . '.png';
                    $imagick->writeImage($tempImagePath);
                    
                    // Apply watermark using Intervention Image
                    $img = \Image::make($tempImagePath);
                    $watermark = \Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
                    $img->insert($watermark, 'top-left', 10, 10);
                    
                    $text = $dossier->ref . " : " . $typeName . " par " . Auth::user()->name . " " . now();
                    $img->text($text, 80, 30, function ($font) {
                        $font->file(public_path('fonts/gnuolane.ttf'));
                        $font->size(21);
                        $font->color('#FF0000');
                        $font->align('top');
                        $font->valign('right');
                        $font->angle(0);
                    });
                    
                    $filename = uniqid() . '.png';
                    $path = 'documents/' . $dossier->ref . '/' . $typeName . '/' . $filename;
                    Storage::disk('s3')->put($path, $img->stream());
                    
                    Document::create([
                        'path' => $path,
                        'type_document_id' => (int) $typeId,
                        'dossier_id' => $dossier->id,
                    ]);
                    
                    unlink($tempImagePath);
                }
                
                $imagick->clear();
                $imagick->destroy();
            } catch (\Exception $e) {
                // Fallback: save PDF as-is if Imagick fails
                $filename = uniqid() . '.pdf';
                $path = 'documents/' . $dossier->ref . '/' . $typeName . '/' . $filename;
                Storage::disk('s3')->put($path, file_get_contents($tempPdfPath));
                
                Document::create([
                    'path' => $path,
                    'type_document_id' => (int) $typeId,
                    'dossier_id' => $dossier->id,
                ]);
            }
        } else {
            // No Imagick: save PDF as-is
            $filename = uniqid() . '.pdf';
            $path = 'documents/' . $dossier->ref . '/' . $typeName . '/' . $filename;
            Storage::disk('s3')->put($path, file_get_contents($tempPdfPath));
            
            Document::create([
                'path' => $path,
                'type_document_id' => (int) $typeId,
                'dossier_id' => $dossier->id,
            ]);
        }
        
        // Cleanup
        unlink($tempPdfPath);
        @rmdir($tempDir);
    }

    /**
     * Process image file with watermark
     */
    private function processImageFile($file, $dossier, $typeId, $typeName)
    {
        $img = \Image::make($file);
        $watermark = \Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
        $img->insert($watermark, 'top-left', 10, 10);
        
        $text = $dossier->ref . " : " . $typeName . " par " . Auth::user()->name . " " . now();
        $img->text($text, 80, 30, function ($font) {
            $font->file(public_path('fonts/gnuolane.ttf'));
            $font->size(21);
            $font->color('#FF0000');
            $font->align('top');
            $font->valign('right');
            $font->angle(0);
        });
        
        $filename = uniqid() . '.png'; // Always save as PNG for consistency
        $path = 'documents/' . $dossier->ref . '/' . $typeName . '/' . $filename;
        Storage::disk('s3')->put($path, $img->stream('png'));
        
        Document::create([
            'path' => $path,
            'type_document_id' => (int) $typeId,
            'dossier_id' => $dossier->id,
        ]);
    }

    /**
     * Previous step
     */
    public function previousStep()
    {
        $this->count--;
    }

    /**
     * Render
     */
    public function render()
    {
        return view('livewire.dossier-wizard', [
            'brands' => Brand::get()->sortBy(fn($brand) => strtolower($brand->brand))->values(),
            'warranties' => Guarantee::get()->sortBy(fn($w) => strtolower($w->guarantee))->values(),
            'dossierTypes' => Mode::get()->sortBy(fn($m) => strtolower($m->mode))->values(),
            'companies' => Company::get()->sortBy(fn($c) => strtolower($c->company))->values(),
            'intermidiaires' => Intermidiaire::get()->sortBy(fn($i) => strtolower($i->company))->values(),
            'typeexpertises' => TypeExpertise::get()->sortBy(fn($t) => strtolower($t->type))->values(),
            'garages' => Garage::get()->sortBy(fn($g) => strtolower($g->libelle))->values(),
            'typevehicules' => TypeVehicule::get()->sortBy(fn($t) => strtolower($t->type))->values(),
            'carburants' => Carburant::get()->sortBy(fn($c) => strtolower($c->name))->values(),
            'cities' => City::get()->sortBy(fn($c) => strtolower($c->city))->values()
        ]);
    }

    /**
     * Update opponent models when brand changes
     */
    public function updatedSelectedBrandop($brand)
    {
        $this->modelsop = VehiculeModel::where('brand_id', $brand)
            ->get()
            ->sortBy(fn($v) => strtolower($v->name))
            ->values();
    }

    /**
     * Update models when brand changes
     */
    public function updatedSelectedBrand($brand)
    {
        $this->models = VehiculeModel::where('brand_id', $brand)
            ->get()
            ->sortBy(fn($v) => strtolower($v->name))
            ->values();
    }

    /**
     * Search brands for autocomplete
     */
    public function updatedBrandSearch($value)
    {
        if (strlen($value) < 1) {
            $this->brandResults = [];
            $this->showBrandDropdown = false;
            return;
        }

        $this->brandResults = Brand::where('brand', 'like', '%' . $value . '%')
            ->orderByRaw("CASE WHEN brand LIKE ? THEN 0 ELSE 1 END", [$value . '%'])
            ->orderBy('brand')
            ->limit(15)
            ->get();
        
        $this->showBrandDropdown = true;
    }

    /**
     * Select a brand from autocomplete
     */
    public function selectBrand($brandId, $brandName)
    {
        $this->selectedBrand = $brandId;
        $this->selectedBrandName = $brandName;
        $this->brandSearch = $brandName;
        $this->showBrandDropdown = false;
        $this->brandResults = [];
        
        // Load models for this brand
        $this->updatedSelectedBrand($brandId);
    }

    /**
     * Clear brand selection
     */
    public function clearBrand()
    {
        $this->selectedBrand = null;
        $this->selectedBrandName = '';
        $this->brandSearch = '';
        $this->models = [];
        $this->vehicule_model_id = null;
        $this->showBrandDropdown = false;
    }

    /**
     * Hide brand dropdown
     */
    public function hideBrandDropdown()
    {
        $this->showBrandDropdown = false;
    }

    /**
     * Search cities for autocomplete (Moroccan cities)
     */
    public function updatedCitySearch($value)
    {
        if (strlen($value) < 1) {
            $this->cityResults = [];
            $this->showCityDropdown = false;
            return;
        }

        $this->cityResults = City::where('city', 'like', '%' . $value . '%')
            ->orderByRaw("CASE WHEN city LIKE ? THEN 0 ELSE 1 END", [$value . '%'])
            ->orderBy('city')
            ->limit(15)
            ->get();
        
        $this->showCityDropdown = true;
    }

    /**
     * Select a city from autocomplete
     */
    public function selectCity($cityId, $cityName)
    {
        $this->city_id = $cityId;
        $this->selectedCityName = $cityName;
        $this->citySearch = $cityName;
        $this->showCityDropdown = false;
        $this->cityResults = [];
    }

    /**
     * Clear city selection
     */
    public function clearCity()
    {
        $this->city_id = null;
        $this->selectedCityName = '';
        $this->citySearch = '';
        $this->showCityDropdown = false;
    }

    /**
     * Search garages for autocomplete
     */
    public function updatedGarageSearch($value)
    {
        if (strlen($value) < 1) {
            $this->garageResults = [];
            $this->showGarageDropdown = false;
            return;
        }

        $this->garageResults = Garage::where('libelle', 'like', '%' . $value . '%')
            ->orderByRaw("CASE WHEN libelle LIKE ? THEN 0 ELSE 1 END", [$value . '%'])
            ->orderBy('libelle')
            ->limit(15)
            ->get();
        
        $this->showGarageDropdown = true;
    }

    /**
     * Select a garage from autocomplete
     */
    public function selectGarage($garageId, $garageName)
    {
        $this->garage_id = $garageId;
        $this->selectedGarageName = $garageName;
        $this->garageSearch = $garageName;
        $this->showGarageDropdown = false;
        $this->garageResults = [];
    }

    /**
     * Clear garage selection
     */
    public function clearGarage()
    {
        $this->garage_id = null;
        $this->selectedGarageName = '';
        $this->garageSearch = '';
        $this->showGarageDropdown = false;
    }

    /**
     * Search intermediaires for autocomplete
     */
    public function updatedIntermediaireSearch($value)
    {
        if (strlen($value) < 1) {
            $this->intermediaireResults = [];
            $this->showIntermediaireDropdown = false;
            return;
        }

        $this->intermediaireResults = Intermidiaire::where('company', 'like', '%' . $value . '%')
            ->orderByRaw("CASE WHEN company LIKE ? THEN 0 ELSE 1 END", [$value . '%'])
            ->orderBy('company')
            ->limit(15)
            ->get();
        
        $this->showIntermediaireDropdown = true;
    }

    /**
     * Select an intermediaire from autocomplete
     */
    public function selectIntermediaire($intermediaireId, $intermediaireName)
    {
        $this->intermidiaire_id = $intermediaireId;
        $this->selectedIntermediaireName = $intermediaireName;
        $this->intermediaireSearch = $intermediaireName;
        $this->showIntermediaireDropdown = false;
        $this->intermediaireResults = [];
    }

    /**
     * Clear intermediaire selection
     */
    public function clearIntermediaire()
    {
        $this->intermidiaire_id = null;
        $this->selectedIntermediaireName = '';
        $this->intermediaireSearch = '';
        $this->showIntermediaireDropdown = false;
    }

    /**
     * Search opponent brands for autocomplete
     */
    public function updatedBrandSearchOp($value)
    {
        if (strlen($value) < 1) {
            $this->brandResultsOp = [];
            $this->showBrandDropdownOp = false;
            return;
        }

        $this->brandResultsOp = Brand::where('brand', 'like', '%' . $value . '%')
            ->orderByRaw("CASE WHEN brand LIKE ? THEN 0 ELSE 1 END", [$value . '%'])
            ->orderBy('brand')
            ->limit(15)
            ->get();
        
        $this->showBrandDropdownOp = true;
    }

    /**
     * Select opponent brand from autocomplete
     */
    public function selectBrandOp($brandId, $brandName)
    {
        $this->selectedBrandop = $brandId;
        $this->selectedBrandNameOp = $brandName;
        $this->brandSearchOp = $brandName;
        $this->showBrandDropdownOp = false;
        $this->brandResultsOp = [];
        
        // Load models for selected brand
        $this->modelsop = VehiculeModel::where('brand_id', $brandId)->orderBy('name')->get();
        $this->vehicule_modelop_id = null;
    }

    /**
     * Clear opponent brand selection
     */
    public function clearBrandOp()
    {
        $this->selectedBrandop = null;
        $this->selectedBrandNameOp = '';
        $this->brandSearchOp = '';
        $this->showBrandDropdownOp = false;
        $this->modelsop = [];
        $this->vehicule_modelop_id = null;
    }

    /**
     * Handle multiple file uploads
     */
    public function updatedUploadedFiles()
    {
        // Initialize file types array for new files
        foreach ($this->uploadedFiles as $index => $file) {
            if (!isset($this->fileTypes[$index])) {
                $this->fileTypes[$index] = ''; // No type assigned yet
            }
        }
    }

    /**
     * Set file type for uploaded file
     */
    public function setFileType($index, $type)
    {
        $this->fileTypes[$index] = $type;
    }

    /**
     * Remove uploaded file
     */
    public function removeUploadedFile($index)
    {
        if (isset($this->uploadedFiles[$index])) {
            unset($this->uploadedFiles[$index]);
            unset($this->fileTypes[$index]);
            // Re-index arrays
            $this->uploadedFiles = array_values($this->uploadedFiles);
            $this->fileTypes = array_values($this->fileTypes);
        }
    }

    /**
     * Toggle dossier results table
     */
    public function toggleTable()
    {
        $this->hidden = !$this->hidden;
    }

    /**
     * Toggle chassis results
     */
    public function toggleChassisResults()
    {
        $this->showChassisResults = !$this->showChassisResults;
    }

    /**
     * Toggle name results
     */
    public function toggleNameResults()
    {
        $this->showNameResults = !$this->showNameResults;
    }

    /**
     * Import from dossier (old matricule)
     */
    public function importDossier($dossierId)
    {
        $dossier = Dossier::with(['insured', 'vehiculemodel.brand'])->find($dossierId);
        if ($dossier) {
            $this->selectedDossier = $dossier->toArray();
            $this->populateFormFromDossier($dossier);
        }
    }

    /**
     * Import from dossier (new matricule)
     */
    public function importDossier1($dossierId)
    {
        $dossier = Dossier::with(['insured', 'vehiculemodel.brand'])->find($dossierId);
        if ($dossier) {
            $this->selectedDossier1 = $dossier->toArray();
            $this->populateFormFromDossier($dossier);
        }
    }

    /**
     * Import from dossier (chassis)
     */
    public function importDossierByChassis($dossierId)
    {
        $dossier = Dossier::with(['insured', 'vehiculemodel.brand'])->find($dossierId);
        if ($dossier) {
            $this->populateFormFromDossier($dossier);
            $this->showChassisResults = false;
        }
    }

    /**
     * Import from dossier (name)
     */
    public function importDossierByName($dossierId)
    {
        $dossier = Dossier::with(['insured', 'vehiculemodel.brand'])->find($dossierId);
        if ($dossier) {
            $this->populateFormFromDossier($dossier);
            $this->showNameResults = false;
        }
    }

    /**
     * Populate form fields from existing dossier
     */
    private function populateFormFromDossier($dossier)
    {
        // Populate vehicle fields
        $this->matricule = $dossier->matricule;
        $this->new_matricule = $dossier->new_matricule;
        $this->type_vehicule_id = $dossier->type_vehicule_id;
        $this->vehicule_model_id = $dossier->vehicule_model_id;
        $this->chassis_number = $dossier->numero_chassis;
        $this->kilometrage = $dossier->kilometrage;
        $this->puissance_fiscale = $dossier->puissance_fiscale;
        $this->carburant = $dossier->carburant_id;
        $this->circulation_date = $dossier->date_circulation;

        // Populate insured fields
        if ($dossier->insured) {
            $this->civility = $dossier->insured->civility;
            $this->name = $dossier->insured->name;
            $this->telephone = $dossier->insured->telephone;
        }

        // Populate brand and load models (including autocomplete fields)
        if ($dossier->vehiculemodel && $dossier->vehiculemodel->brand) {
            $this->selectedBrand = $dossier->vehiculemodel->brand_id;
            $this->selectedBrandName = $dossier->vehiculemodel->brand->brand;
            $this->brandSearch = $dossier->vehiculemodel->brand->brand;
            $this->updatedSelectedBrand($this->selectedBrand);
        }

        // Populate city (with autocomplete)
        if ($dossier->city_id) {
            $this->city_id = $dossier->city_id;
            $city = City::find($dossier->city_id);
            if ($city) {
                $this->selectedCityName = $city->city;
                $this->citySearch = $city->city;
            }
        }

        // Populate garage (with autocomplete)
        if ($dossier->garage_id) {
            $this->garage_id = $dossier->garage_id;
            $garage = Garage::find($dossier->garage_id);
            if ($garage) {
                $this->selectedGarageName = $garage->libelle;
                $this->garageSearch = $garage->libelle;
            }
        }

        // Populate intermediaire (with autocomplete)
        if ($dossier->intermidiaire_id) {
            $this->intermidiaire_id = $dossier->intermidiaire_id;
            $intermediaire = Intermidiaire::find($dossier->intermidiaire_id);
            if ($intermediaire) {
                $this->selectedIntermediaireName = $intermediaire->company;
                $this->intermediaireSearch = $intermediaire->company;
            }
        }

        // Populate insurance fields
        $this->guarantee_id = $dossier->guarantee_id;
        $this->company_id = $dossier->company_id;
        $this->numero_police = $dossier->numero_police;
        $this->numero_attestation = $dossier->numero_attestation;
        $this->mode_id = $dossier->mode_id;
        $this->type_expertise_id = $dossier->type_expertise_id;

        // Hide all results/dropdowns but keep fields editable
        $this->hidden = true;
        $this->showChassisResults = false;
        $this->showNameResults = false;
        $this->showBrandDropdown = false;
        $this->showCityDropdown = false;
        $this->showGarageDropdown = false;
        $this->showIntermediaireDropdown = false;
        
        // Emit event to update JS components
        $this->emit('dossierImported');
    }
}