<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Immobilisation as Immo;
use App\Rules\CheckClotureExercice;
use App\Rules\CheckCloturePeriode;
use App\Rules\CheckTauxChangeByDate;
use App\Rules\CompteExist;
use App\Rules\DateBetweenExercice;
use Illuminate\Support\Facades\DB;
use Exception;
use Barryvdh\DomPDF\Facade\Pdf;


class ModalImmo extends Component
{   

    protected $listeners = ['editImmobilisation', 'NewImmo','newImmoWithParam'];
    public $Select_devise ;
    public  $isNewImmo = true;
    public $id, $compte , $intitule_compte , $date_acq , $libelle , $montant, $devise, $periode, $amortissement , $hiddenId;
    private $regEx = "([0-9])";


    public function mount()
    {
        //$this->Select_devise = get_select_devise();
        $this->devise = get_main_devise();
    }



    
    public function saveAndCloseModalImmo()
    {
        $this->saveImmo();
        $this->CloseModalImmo();
    }

    public function NewImmo()
    {   
        //$this->tab_t = "identification";
        //$this->type_t =  ($this->tab === 'tous')? '': $this->tab ;
        $this->OpenModalImmo();
    }

    public function newImmoWithParam($compte,$libelle,$montant,$devise,$date)
    {
        $this->compte = $compte ;
        $this->libelle = $libelle ;
        $this->montant = $montant ;
        $this->devise = $devise ;
        $this->date_acq = $date ;
        $this->dispatch('resetSelect_Compte', data : $compte);
        $this->OpenModalImmo();
    }


    public function CloseModalImmo()
    {    
        $this->resetForm();
        $this->dispatch('hideModalImmo');
    }

    public function OpenModalImmo()
    {   
        $this->dispatch('showModalImmo');
    }

    public function showToastr($message){
        return $this->dispatch('showToast',
           message : $message
        );
    }

    /*** MY RENDER  ***********/
    public function render()
    {
        return view('livewire.modal-immo');
    }


    public function saveImmo(){

     /*  $p = DB::table('immobilisation_test')
            ->select('compte', 'libelle','montant','dateacq','periode')
            ->get();

       
        foreach($p as $a):
            Immo::create([
                'fk_num_compte' => $a->compte,
                'intitule'      => $a->libelle,
                'dependant_de'  => null,
                'date_acquisition' => $a->dateacq,
                'montant'      => $a->montant,
                'devise'       => 'USD',
                'fk_idworkday' => get_current_idWorkDay(),
                'periode'   => $a->periode,
                'user_crea' => get_pseudo(),
                'id_app'    => get_id_app()
            ]);

        endforeach;

        dd("c bon");
       
        */
        $this->validate([
            'compte'   => ['required',new CompteExist],
            'date_acq' => ['required','date','date_format:Y-m-d','before:tomorrow','after:2000-12-31',new DateBetweenExercice, new CheckTauxChangeByDate,
                            new CheckCloturePeriode, new CheckClotureExercice],
            'libelle'  => ['required','string','min:3','max:100'],
            'montant'  => ['required','numeric','min:0','max:9999999999999.99'],
            'devise'   => ['required'],
            'periode'  => ['required','int','min:0','max:100'],
           
        ],
        [
            'compte.required' => "compte obligatoire",
            'date_acq.required' => "date acquisition obligatoire",
            'date_acq.date' => "date format invalide",
            'date_acq.before' => "date erronée",
            'date_acq.after' => "date min. 01-01-2001",
            'libelle.required' => "libellé obligatoire",
            'libelle.string' => "libellé erroné",
            'libelle.min' => "libellé trop court",
            'libelle.max' => "libellé max:100",
            'montant.required' => "montant obligatoire",
            'montant.numeric' => "montant invalide",
            'montant.min' => "montant invalide",
            'montant.max' => "montant trop grand",
           /* 'montant.decimal' => "montant invalide", */
            'devise.required' => "devise obligatoire",
            'periode.required' => "periode obligatoire",
            'periode.int' => "periode invalide",
            'periode.min' => "periode invalide",
            'periode.max' => "periode trop grande",
        ]);

        try{

            if($this->isNewImmo){

                Immo::create([
                    'fk_num_compte' => $this->compte,
                    'intitule'      => $this->libelle,
                    'dependant_de'  => null,
                    'date_acquisition' => $this->date_acq,
                    'montant'      => $this->montant,
                    'devise'       => $this->devise,
                    'fk_idworkday' => get_idWorkDay_by_Date($this->date_acq),
                    'periode'   => $this->periode,
                    'user_crea' => get_pseudo(),
                    'id_app'    => get_id_app()
                ]);
                
                $msg = "Création effectuée avec success";
            }else{

                $immo = Immo::findOrFail($this->id);
                $immo->fill([
                    'fk_num_compte' => $this->compte,
                    'intitule'      => $this->libelle,
                    'date_acquisition' => $this->date_acq,
                    'montant'      => $this->montant,
                    'devise'       => $this->devise,
                    'fk_idworkday' => get_idWorkDay_by_Date($this->date_acq),
                    'periode'   => $this->periode,
                    'user_crea' => get_pseudo(),
                ]);
                $immo->save();

                $msg = "Modification effectuée avec success";
            }

            
            $this->resetForm();  
            $this->dispatch('loadImmoTable') ;
            $this->showToastr('success|'.$msg);

        }catch(Exception $e)
        {
            $this->showToastr('failed|Une erreur est survenue');
        }

       // $this->dispatch('hideConfirmModalTauxChange');
       
    }

    public function editImmobilisation(Immo $immo)
    {       
            $this->resetForm();
            $this->fill([
                'compte'   => $immo->fk_num_compte ,
                'date_acq' => $immo->date_acquisition,
                'libelle'  => $immo->intitule ,
                'montant'  => $immo->montant ,
                'devise'   => $immo->devise ,
                'periode'  => $immo->periode,
                'amortissement' =>  amort_journalier($immo->montant,$immo->periode),
            ]);
        
        $this->isNewImmo = false ;
        $this->id = $immo->id;
        $this->dispatch('resetSelect_Compte', data : $immo->fk_num_compte);
        $this->OpenModalImmo();
            
    }


    public function updatedMontant($value)
    {
        if(!is_null($this->periode))
        {
           if(preg_match($this->regEx, $value) && preg_match($this->regEx, $this->periode))
           {
            $this->amortissement = amort_journalier($value,$this->periode) ;
           }else{
            $this->amortissement = "";
           }
            
        }
        
    }

    public function updatedPeriode($value)
    {
        if(!is_null($this->montant))
        {
           if(preg_match($this->regEx, $value) && preg_match($this->regEx, $this->montant))
           {
            $this->amortissement = amort_journalier($this->montant,$value) ;
           }else{
            $this->amortissement = "";
        }
            
        }
    }


    public function resetForm()
    {
        $this->compte = $this->intitule_compte = $this->date_acq = $this->montant =
        $this->libelle = $this->periode = $this->amortissement =  $this->id = null ;
        $this->devise = get_main_devise();
        $this->resetValidation();
        $this->isNewImmo = true ;
        $this->resetValidation() ;
        $this->dispatch('resetSelect_Compte', data : "");
    }
}
