<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class Dossier extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'insured_id',
        'opponent_id',
        'company_id',
        'garage_id',
        'guarantee_id',
        'intermidiaire_id',
        'type_dossier_id',
        'type_expertise_id',
        'dossier_status_id',
        'vehicule_model_id',
        'numero_sinistre',
        'numero_police',
        'numero_attestation',
        'numero_chassis',
        'sinistre_douteux',
        'date_sinistre',
        'date_reception',
        'ref',
        'new_matricule',
        'matricule',
        'mode_id',
        'kilometrage',
        'puissance_fiscale',
        'date_circulation',
        'step_id',
        'date_fin',
        'carburant_id',
        'valeurneuf',
        'valeuradire',
        'horssinistre',
        'valeurepave',
        'valeurvenale',
        'valeurneuf_ttc',
        'valeuradire_ttc',
        'horssinistre_ttc',
        'valeurepave_ttc',
        'valeurvenale_ttc',
        'user_id',
        'type_vehicule_id',
        'from',
        'to',
        'city_id',
        'currency_id',
        'facture',
        'date_facturation',
        'montant_accord_adverse',
        'update'
    ];

    public function currency()
    {
        return $this->belongsTo(Currency::class);
    }

    public function insured()
    {
        return $this->belongsTo(Insured::class);
    }

    public function city()
    {
        return $this->belongsTo(City::class);
    }

    public function carburant()
    {
        return $this->belongsTo(Carburant::class);
    }

    public function typevehicule()
    {
        return $this->belongsTo(TypeVehicule::class, 'type_vehicule_id');
    }

    // adversaire victime
    public function opponent()
    {
        return $this->belongsTo(Opponent::class);
    }

    public function guarantee()
    {
        return $this->belongsTo(Guarantee::class);
    }

    public function document()
    {
        return $this->hasMany(Document::class);
    }

    public function piecetype()
    {
        return $this->belongsToMany(PieceType::class);
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function mode()
    {
        return $this->belongsTo(Mode::class);
    }

    public function typeexpertise()
    {
        return $this->belongsTo(TypeExpertise::class, 'type_expertise_id');
    }

    public function status()
    {
        return $this->belongsTo(DossierStatus::class, 'dossier_status_id');
    }
    public function dossierstatus()
    {
        return $this->belongsToMany(DossierStatus::class, 'dossier_status')->withTimestamps();
    }

    public function observation()
    {
        return $this->hasMany(Observation::class);
    }

    public function transaction()
    {
        return $this->hasMany(Transaction::class);
    }

    public function meeting()
    {
        return $this->hasMany(Meeting::class);
    }
    public function onemeeting()
    {
        return $this->hasOne(Meeting::class)->orderByDesc('created_at');
    }
    public function onedocument()
    {
        return $this->hasOne(Document::class)->where('type_document_id', 5);
    }
    public function contradictoire()
    {
        return $this->hasOne(Contradictoire::class);
    }

    public function step()
    {
        return $this->belongsToMany(Step::class, 'step_dossier')->withPivot('user_id')->withTimestamps();
    }

    public function shockpoint()
    {
        return $this->belongsToMany(ShockPoint::class, 'dossier_shockpoint');
    }

    public function devis()
    {
        return $this->hasMany(Devis::class);
    }
     
    public function onedevis()
    {
        return $this->hasOne(Devis::class)->orderByDesc('created_at');
    }

    public function notification()
    {
        return $this->hasMany(Notification::class);
    }

    public function vehiculemodel()
    {
        return $this->belongsTo(VehiculeModel::class, 'vehicule_model_id');
    }

    public function demande()
    {
        return $this->hasMany(Demande::class);
    }

    public function intermidiaire()
    {
        return $this->belongsTo(Intermidiaire::class);
    }

    public function garage()
    {
        return $this->belongsTo(Garage::class);
    }

    public function rapport()
    {
        return $this->hasMany(Rapport::class);
    }
    public function onerapport()
    {
        return $this->hasOne(Rapport::class)->orderByDesc('created_at');
    }

    public function facture()
    {
        return $this->hasMany(Facture::class);
    }

    public function onefacture()
    {
        return $this->hasOne(Facture::class)->orderByDesc('created_at');
    }

    public function lastmeet()
    {
        return $this->hasOne(Meeting::class)->orderByDesc('created_at');
    }

    public function montant()
    {
        return $this->hasOne(Montant::class);
    }

    // 
    public function payment()
    {
        return $this->hasOne(Payment::class);
    }

    public function paymentArbitrage()
    {
        return $this->hasMany(Payment::class);
    }

    public function signedurl()
    {
        return $this->hasMany(SignedUrl::class);
    }

    public function currentStep()
    {
        return $this->belongsTo(Step::class, 'step_id');
    }
    public function lastdevis()
    {
        return $this->hasOne(Devis::class)->orderByDesc('created_at')->where('devis_status_id',4);
    }
    
    public function scopeUser($query)
    {
        $user = auth()->user();

        // Get the userCompanyType relations associated with the user
        $userCompanyTypes = $user->userCompanyType;
        if (Auth::user()->role_id == 4 || Gate::allows('fullaccess', $this)) {
            return;
        } else if (Auth::user()->role_id == 1 ) {
            foreach ($userCompanyTypes as $userCompanyType) {

                $query->orWhere(function ($query) use ($userCompanyType) {
                    $query->where('company_id', $userCompanyType->pivot->company_id)
                        ->where('type_expertise_id', $userCompanyType->pivot->type_expertise_id);
                });
            }

            return $query;
        } else if( Auth::user()->role_id == 2){
            $chiff = User::whereId(Auth::user()->id)->with('seuil')->first();

            foreach ($userCompanyTypes as $userCompanyType) {

                $query->orWhere(function ($query) use ($userCompanyType) {
                    $query->where('company_id', $userCompanyType->pivot->company_id)
                        ->where('type_expertise_id', $userCompanyType->pivot->type_expertise_id);
                });
            }
            // $seuil = Seuil::where('user_id',Auth::user()->id)->where('company_id',$this->company_id)->first();

            // $query->whereHas('company.seuil',function($query){
            //     $query->where('user_id',Auth::user()->id);
            //  })
            //  ->where(function ($query)  {
            //     $query->whereHas('onedevis', function ($subquery) use ($query) {
            //         $subquery->where('montant_devis', '>=', $query->company->seuil->min)
            //             ->where('montant_devis', '<', $query->company->seuil->max);
            //     })->orWhereHas('onefacture', function ($subquery) use ($query) {
            //         $subquery->where('montant_facture', '>=', $query->company->seuil->min)
            //             ->where('montant_facture', '<', $query->company->seuil->max);
            //     });
            // });

            return $query;
        }
    }

    // public function scopeUser($query)
    // {
    //     if (Auth::user()->role_id == 4 || Gate::allows('fullaccess', $this)) {
    //         return;
    //     } else if (Auth::user()->role_id == 1) {
    //         return $query->wherehas('company.usertypes', function ($query) {
    //             $query->where('user_id', Auth::user()->id);
    //         })->wherehas('typeexpertise.usercompany', function ($query) {
    //             $query->where('user_id', Auth::user()->id);
    //         });
    //     } else if (Auth::user()->role_id == 2) {
    //         $user = User::whereId(Auth::user()->id)->with('seuil')->first();
    //         return $this->wherehas('company.usertypes', function ($query) {
    //             $query->where('user_id', Auth::user()->id);
    //         })->wherehas('typeexpertise.usercompany', function ($query) {
    //             $query->where('user_id', Auth::user()->id);
    //         })->where(function ($query) use ($user) {
    //             $query->whereHas('onedevis', function ($subquery) use ($user) {
    //                 $subquery->where('montant_devis', '>=', $user->seuil->min)
    //                     ->where('montant_devis', '<', $user->seuil->max);
    //             })->orWhereHas('onefacture', function ($subquery) use ($user) {
    //                 $subquery->where('montant_facture', '>=', $user->seuil->min)
    //                     ->where('montant_facture', '<', $user->seuil->max);
    //             });
    //         });
    //     }
    // }
    // protected static function boot()
    // {
    //     parent::boot();
    //     static::addGlobalScope(new DossierCloturerScope);
    // }

}
