<?php

namespace App\Livewire;

use App\Rules\CheckClotureExercice;
use App\Rules\CheckCloturePeriode;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Rules\CheckTauxChangeByDate;
use App\Rules\CompteExist;
use App\Rules\DateBetweenExercice;
use App\Rules\NumFactureExist;

class SaisieJournalCaisse extends Component
{   
    use WithFileUploads;
    public $tab = null;
    public $tabname = "facture" ;
    public $type_tiers , $ligne = 10 , $search ;
    protected $queryString = ['tab'] ;
    //protected $listeners = ['refreshTiers' => '$refresh'];
    public $MyArray_achat = [] , $ListCompte   ;
    protected $listeners = ['getRefFactureCaisse'];

     //**** Block sur Facture */
     public $Reference_facture , $CompteCaisse_facture , $libelle_facture, $file_piece_justif_facture,
            $montant_facture, $devise_facture, $date_facture, $justification_facture , $CompteTiers_facture;

     //**** Block sur Tiers */
     public  $idTiers,$value_tiers, $CompteCaisse_tiers , $libelle_tiers, $file_piece_justif_tiers,
            $montant_tiers, $devise_tiers, $date_tiers, $justification_tiers , $CompteTiers_tiers
            ;


     //**** Block Transactions Diverses  */
     public $CompteCaisse_td , $libelle_td, $montant_td, $devise_td, $date_td, $justification_td ,
             $CompteTiers_td, $file_piece_justif_td;
 
   
   

    // General Block *************************/
    public function selectTab($tab){
        $this->tab = $tab ;
        // $this->search = null;
        $this->resetValidation() ;
        //$this->resetPage();
        //$this->type_tiers = $tab ;
    }

    public function getRefFactureCaisse(string $ref)
    {
        $this->Reference_facture = $ref ;
    }


    public function mount(){
        $this->tab = request()->tab ? request()->tab : $this->tabname ;
        $this->type_tiers = $this->tab ;
        $this->devise_facture = get_main_devise();
        $this->devise_tiers = get_main_devise();
        $this->devise_td = get_main_devise();
    }


    public function goToJournalCompta()
    {
        session()->put('journal', 'caisse');
        to_route('journaux-comptable');
    }


    public function saveSurFacture()
    {
    
            $this->validate([
                'Reference_facture' => ['required', new NumFactureExist],
                'CompteCaisse_facture' => ['required',new CompteExist],
                'libelle_facture' => ['required','min:3','max:100'],
                'montant_facture'=> ['required','numeric','min:0','max:9999999999999.99'],
                'devise_facture' => ['required'],
                'date_facture' => ['required','date','date_format:Y-m-d','before:tomorrow','after:2000-12-31',new DateBetweenExercice,new CheckTauxChangeByDate,
                    new CheckCloturePeriode, new CheckClotureExercice],
                'justification_facture' => ['nullable','string'],
                'file_piece_justif_facture' => ['nullable','file','mimes:pdf','max:102400'],
            ], [
                'Reference_facture.required' => 'Obligatoire',
                'CompteCaisse_facture.required' => 'Obligatoire',
                'libelle_facture.required' => 'libellé obligatoire',
                'libelle_facture.string' => "libellé erroné",
                'libelle_facture.min' => "libellé trop court",
                'libelle_facture.max' => "libellé max:100",
                'montant_facture.required' => "montant obligatoire",
                'montant_facture.numeric' => "montant invalide",
                'montant_facture.min' => "montant invalide",
                'montant_facture.max' => "montant trop grand",
                'devise_facture.required' => 'devise  obligatoire',
                'date_facture.required' => "date obligatoire",
                'date_facture.date' => "date format invalide",
                'date_facture.before' => "date erronée",
                'date_facture.after' => "date min. 01-01-2001",

            ]) ;


            try {
                    $file = null ;
                   /* if(!is_null($this->file_piece_justif_facture))
                    {
                        $file = $this->file_piece_justif_facture->store('p_justif/'.get_id_app(),'public');
                    }*/

                    $resp =  save_Treso('TresoFacture',null,null,$this->CompteCaisse_facture,$this->Reference_facture,
                            $this->date_facture, $this->libelle_facture, $this->montant_facture,
                            $this->devise_facture,$this->justification_facture,$file);


                    if($resp === 1)
                    {   
                        $this->resetForm_Facture();
                        $this->showToastr('success|Enregistrement effectué avec succès');
                    }else{
                        $this->showToastr('failed|'.$resp); 
                    }
            } catch (\Exception $e) {
                    $this->showToastr('failed|erreur uploading fichier'); 
            }

    }

    public function resetForm_Facture(){
       // $this->idTiers =
       // $this->idFacture =
      //  $this->CompteTiers  =
        $this->CompteCaisse_facture =
        $this->libelle_facture =  
        $this->montant_facture = 
        $this->justification_facture =
        $this->file_piece_justif_facture =
        $this->date_facture = null ;
        $this->resetValidation();
        $this->devise_facture = get_main_devise();
    }

    /**
     * ! Traitement sur Tiers 
     */

    public function enCaissement()
    {
       $this->saveSurTiers(true);
    }

    public function DeCaissement()
    {
        $this->saveSurTiers();
    }

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


    public function saveSurTiers($isEncaissement = false)
    {
        $this->validate([
            'idTiers' => ['required'],
            'CompteTiers_tiers' => ['required'],
            'CompteCaisse_tiers' => ['required',new CompteExist],
            'libelle_tiers' => ['required','min:3','max:100'],
            'montant_tiers'=> ['required','numeric','min:0','max:9999999999999.99'],
            'devise_tiers' => ['required'],
            'date_tiers' => ['required','date','date_format:Y-m-d','before:tomorrow','after:2000-12-31',new DateBetweenExercice,new CheckTauxChangeByDate,
                            new CheckCloturePeriode, new CheckClotureExercice],
            'justification_tiers' => ['nullable','string'],
            'file_piece_justif_tiers' => ['nullable','file','mimes:pdf','max:102400'],
        ], [
            'idTiers.required' => ['Tiers obligatoire'],
            'CompteTiers_tiers.required' => 'Obligatoire',
            'CompteCaisse_tiers.required' => 'Obligatoire',
            'libelle_tiers.required' => 'libellé obligatoire',
            'libelle_tiers.string' => "libellé erroné",
            'libelle_tiers.min' => "libellé trop court",
            'libelle_tiers.max' => "libellé max:100",
            'montant_tiers.required' => "montant obligatoire",
            'montant_tiers.numeric' => "montant invalide",
            'montant_tiers.min' => "montant invalide",
            'montant_tiers.max' => "montant trop grand",
            'devise_tiers.required' => 'devise  obligatoire',
            'date_tiers.required' => "date obligatoire",
            'date_tiers.date' => "date format invalide",
            'date_tiers.before' => "date erronée",
            'date_tiers.after' => "date min. 01-01-2001",

        ]) ;


        try {
                $file = null ;
                if(!is_null($this->file_piece_justif_tiers))
                {
                    $file = $this->file_piece_justif_tiers->store('p_justif/'.get_id_app(),'public');
                }

                $resp =  save_Treso('TresoFacture',$this->idTiers,$this->CompteTiers_tiers,
                        $this->CompteCaisse_tiers,null, $this->date_tiers, $this->libelle_tiers,
                        $this->montant_tiers, $this->devise_tiers,$this->justification_tiers,
                        $file,$isEncaissement);

                if($resp == 1)
                {   
                    $this->resetForm_Tiers();
                    $this->showToastr('success|Enregistrement effectué avec succès');
                }else{
                    $this->showToastr('failed|'.$resp); 
                }
        } catch (\Exception $e) {
                $this->showToastr('failed|erreur uploading fichier'); 
        }

    }

    public function resetForm_Tiers(){
         $this->idTiers =
         $this->CompteTiers_tiers  =
         $this->CompteCaisse_tiers =
         $this->libelle_tiers =  
         $this->montant_tiers = 
         $this->justification_tiers =
         $this->file_piece_justif_tiers =
         $this->date_tiers = null;
         $this->resetValidation();
         $this->devise_tiers = get_main_devise();
     }

    public function updatedIdTiers($value)
    {   
         $this->CompteTiers_tiers = '' ;
         $this->value_tiers = '';
         $this->ListCompte = get_compte_tiers($value) ;
         $this->value_tiers = (count($this->ListCompte) > 0)? $this->ListCompte[0]->num_compte : '' ;
         $this->CompteTiers_tiers = $this->value_tiers ;
    }
    
    /**
     * ! Traitement Transaction diverse
     */
    
     public function enCaissement_()
     {
        $this->saveSurTD(true);
     }
 
     public function DeCaissement_()
     {
         $this->saveSurTD();
     }
 
 
     public function saveSurTD($isEncaissement = false)
     {
         $this->validate([
            
             'CompteTiers_td'  => ['required'],
             'CompteCaisse_td' => ['required',new CompteExist],
             'libelle_td'      => ['required','min:3','max:100'],
             'montant_td'      => ['required','numeric','min:0','max:9999999999999.99'],
             'devise_td'       => ['required'],
             'date_td'         => ['required','date','date_format:Y-m-d','before:tomorrow','after:2000-12-31',new DateBetweenExercice,new CheckTauxChangeByDate,
                                    new CheckCloturePeriode, new CheckClotureExercice],
             'justification_td' => ['nullable','string'],
             'file_piece_justif_td' => ['nullable','file','mimes:pdf','max:102400'],
         ], [
            
             'CompteTiers_td.required' => 'Obligatoire',
             'CompteCaisse_td.required' => 'Obligatoire',
             'libelle_td.required' => 'libellé obligatoire',
             'libelle_td.string' => "libellé erroné",
             'libelle_td.min' => "libellé trop court",
             'libelle_td.max' => "libellé max:100",
             'montant_td.required' => "montant obligatoire",
             'montant_td.numeric' => "montant invalide",
             'montant_td.min' => "montant invalide",
             'montant_td.max' => "montant trop grand",
             'devise_td.required' => 'devise  obligatoire',
             'date_td.required' => "date obligatoire",
             'date_td.date' => "date format invalide",
             'date_td.before' => "date erronée",
             'date_td.after' => "date min. 01-01-2001",
 
         ]) ;
 
 
        try {
                $file = null ;
                if(!is_null($this->file_piece_justif_td))
                {
                    $file = $this->file_piece_justif_td->store('p_justif/'.get_id_app(),'public');
                }
 
                $resp =  save_Treso('TresoTD',null,$this->CompteTiers_td,
                        $this->CompteCaisse_td,null, $this->date_td, $this->libelle_td,
                        $this->montant_td, $this->devise_td,$this->justification_td,
                        $file,$isEncaissement);
 
                if($resp === 1)
                {   
                     $this->resetForm_TD();
                     $this->showToastr('success|Enregistrement effectué avec succès');
                }else{
                     $this->showToastr('failed|'.$resp); 
                }
        } catch (\Exception $e) {
                 $this->showToastr('failed|erreur uploading fichier'); 
        }
 
     }
 
     public function resetForm_TD()
     {
          $this->CompteTiers_td  =
          $this->CompteCaisse_td =
          $this->libelle_td =  
          $this->montant_td = 
          $this->justification_td =
          $this->file_piece_justif_td =
          $this->date_td = null;
          $this->resetValidation();
          $this->devise_td = get_main_devise();
    }


    public function render()
    {
        return view('livewire.saisie-journal-caisse');
    }
}
