<?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 Livewire\WithFileUploads;

class DossierWizard extends Component
{
    use WithFileUploads;

    public $selectedBrand, $models;
    public $selectedBrandop, $modelsop;
    public $dossiers, $dossiers1, $selectedDossier, $numero_attestationop, $selectedDossier1, $pv, $declaration, $constat;
    public $insurances, $tel, $telop;
    public $count = 0;
    public $hidden = true;
    public $type_vehicule_id, $civility, $city_id, $points, $carburant, $puissance_fiscale, $mode_id, $kilometrage, $civilityop, $matriculeop, $garage_id, $type_expertise_id, $nameop, $telephoneop, $intermidiaire_id, $companyop_id, $vehicule_modelop_id, $new_matricule, $chassis_number, $matricule, $name, $telephone, $company_id, $vehicule_model_id, $guarantee_id, $type_dossier_id, $date_sinistre, $date_reception, $circulation_date, $numero_police, $numero_sinistre, $numero_attestation;

    public function vehiculeStep()
    {

        $this->validatedData = $this->validate([
            'telephone' => 'nullable|min:10|max:10',
            'new_matricule' => 'required_without:matricule|size:8|nullable', //|regex:/^[W,w]{2}[-][0-9]{4,6}/
            'matricule' => 'required_without:new_matricule|nullable', //|regex:/^[0-9]{4,5}[-][A-Z]{1}[-][0-9]{1,2}/
            'date_sinistre' => 'required|date',
            'name' => 'required',
            'company_id' => 'required',
            'numero_sinistre' => 'required|unique:dossiers,numero_sinistre',
            'date_reception' => 'required'
       ]);

        $this->count++;
    }

    // public function insuredStep()
    // {
    //     $this->validatedData = $this->validate([


    //     ]);

    //     $this->count++;
    // }

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

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

    //     $this->count++;
    // }


    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++;

        if ($this->telephone != "") {
            $tel = $this->telephone;
        } else {
            $tel = $this->telephone;
        }
        $insured = Insured::create([
            'civility' => $this->civility,
            'name' => $this->name,
            'telephone' => $tel,
        ]);


        // $ref = IdGenerator::generate(['table' => 'dossiers', 'length' => 6, 'field' => 'ref', 'prefix' => '']).date('m') . date('Y');
        if ($this->garage_id  == "") {
            $this->garage_id = null;
        }
        if ($this->company_id  == "") {
            $this->company_id = null;
        }
        if ($this->companyop_id  == "") {
            $this->companyop_id = null;
        }
        if ($this->carburant  == "") {
            $this->carburant = null;
        }
        if ($this->vehicule_model_id  == "") {
            $this->vehicule_model_id = null;
        }
        if ($this->intermidiaire_id  == "") {
            $this->intermidiaire_id = null;
        }
        if ($this->guarantee_id  == "") {
            $this->guarantee_id = null;
        }
        if ($this->type_expertise_id  == "") {
            $this->type_expertise_id = null;
        }
        if ($this->mode_id  == "") {
            $this->mode_id = null;
        }
        if ($this->city_id  == "") {
            $this->city_id = null;
        }
        if ($this->type_vehicule_id  == "") {
            $this->type_vehicule_id = 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([
            // 'ref' => $ref,
            '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
        ]);
        $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]);

        if (!empty($this->declaration)) {
            foreach ($this->declaration as $declar) {
                $filename =  uniqid() . '.' . File::extension($declar->getClientOriginalName());;
                $path3 = $declar->storeAs('documents/' . $dossier->ref . '/Declaration', $filename, 's3');
                Document::create([
                    'path' => $path3,
                    'type_document_id' => 3,
                    'dossier_id' => $dossier->id,
                ]);
            }
        }
        if (!empty($this->pv)) {
            foreach ($this->pv as $pv) {
                $filename =  uniqid() . '.' . File::extension($pv->getClientOriginalName());;
                $path = $pv->storeAs('documents/' . $dossier->ref . '/PV', $filename, 's3');
                Document::create([
                    'path' => $path,
                    'type_document_id' => 1,
                    'dossier_id' => $dossier->id,

                ]);
            }
        }

        if (!empty($this->constat)) {
            foreach ($this->constat as $consta) {
                $filename =  uniqid() . '.' . File::extension($consta->getClientOriginalName());;
                $path2 = $consta->storeAs('documents/' . $dossier->ref . '/Constat', $filename, 's3');
                Document::create([
                    'path' => $path2,
                    'type_document_id' => 2,
                    'dossier_id' => $dossier->id,

                ]);
            }
        }



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

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

    public function previousStep()
    {
        $this->count--;
    }

    public function render()
    {
        return view('livewire.dossier-wizard', [
            'brands' => Brand::get()->sortBy(function ($brand) {
            return strtolower($brand->brand);
        })
        ->values(),
            'warranties' => Guarantee::get()->sortBy(function ($warrantie) {
            return strtolower($warrantie->guarantee);
        })
        ->values(),
            'dossierTypes' => Mode::get()->sortBy(function ($mode) {
            return strtolower($mode->mode);
        })
        ->values(),

            'companies' => Company::get()->sortBy(function ($company) {
            return strtolower($company->company);
        })
        ->values(),
            'intermidiaires' => Intermidiaire::get()->sortBy(function ($intermidiaire) {
            return strtolower($intermidiaire->company);
        })
        ->values(),
            'typeexpertises' => TypeExpertise::get()->sortBy(function ($type) {
            return strtolower($type->type);
        })
        ->values(),
            'garages' => Garage::get()->sortBy(function ($garage) {
            return strtolower($garage->libelle);
        })
        ->values(),
            'typevehicules' => TypeVehicule::get()->sortBy(function ($type) {
            return strtolower($type->type);
        })
        ->values(),
            'carburants' => Carburant::get()->sortBy(function ($carburant) {
            return strtolower($carburant->name);
        })
        ->values(),
            'cities' => City::get()->sortBy(function ($city) {
            return strtolower($city->city);
        })
        ->values()
        ]);
    }

    public function updatedSelectedBrandop($brand)
    {
        $this->modelsop = VehiculeModel::where('brand_id', $brand)->get()->sortBy(function ($vehicule) {
            return strtolower($vehicule->name);
        })
        ->values();
    }

    public function updatedSelectedBrand($brand)
    {
        $this->models = VehiculeModel::where('brand_id', $brand)->get()->sortBy(function ($vehicule) {
            return strtolower($vehicule->name);
        })
        ->values();
    }

    // public function updatedSelectedEmetteur($emetteur)
    // {
    //     if ($emetteur  'Assurance') {
    //         $this->insurances = Company::where('type', 'assurance')->get();
    //         $this->intermidiants = null;
    //     } elseif ($emetteur == 'Intermédiaire') {
    //         $this->intermidiants = Company::where('type', 'intermidiare')->get();
    //         $this->insurances = null;
    //     }
    // }

    public function updatedMatricule()
    {
        $this->dossiers = Dossier::where('matricule', $this->matricule)->with('insured')->get();
    }

    public function updatedNewMatricule()
    {
        $this->dossiers1 = Dossier::where('new_matricule', $this->new_matricule)->with('insured')->get();
    }

    // public function changeTab($tab)
    // {
    //     if ($tab == 'vehiculeTab') return $this->count = 0;
    //     if ($tab == 'insuredTab') return $this->count = 1;
    //     if ($tab == 'insuranceTab') return $this->count = 2;
    //     if ($tab == 'opponentTab') return $this->count = 3;
    //     if ($tab == 'documentTab') return $this->count = 4;
    // }

    public function toggleTable()
    {
        $this->hidden = !$this->hidden;
    }

    public function importDossier($dossier)
    {
        $this->selectedDossier = $dossier;
    }
    public function importDossier1($dossier1)
    {
        $this->selectedDossier1 = $dossier1;
    }
}
