<?php

namespace App\Livewire;

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

class SaisieJournalOdAchatVente extends Component
{   
    use WithFileUploads;
    public $inputs ,$listComptaDevise , $CurrentDate ;
    private $regEx = "([0-9])";
    //protected $listeners = ['refreshSaisieJournaux' => '$refresh'];

    public $idFournisseur_achat, $NumFacture_achat,$compte_achat  , $date_achat , $libelle_achat ,$reference_achat, $debit_achat ,$compte_tiers_achat,$value_tiers = '',
    $credit_achat , $devise_achat , $total_ht_achat, $taxe_achat , $total_achat, $total_debit = 0, $total_credit =0, $isEgal_achat = false , $file_piece_justif, $piece_justif ;
    public $readonly_debit_achat = false , $readonly_credit_achat = false , $focus_debit_achat = false , 
            $focus_credit_achat = false  ;
    public $MyArray_achat = [] , $ListCompte_achat , $isImmo = false ;


    public function mount(){
        //$this->tab = request()->tab ? request()->tab : $this->tabname ;
       // $this->tab = $this->tabname ;
        $this->devise_achat = get_main_devise();
        //$this->devise_vente = get_main_devise();
        //$this->devise_od = get_main_devise();

        
        // $this->total_ttc_achat = "Wep5556666666666666";
    }

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


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


    public function addItem_achat(){

       $validator = $this->validate([
            'compte_achat' => ['required', new CompteExist ], 
            'debit_achat'  => ['nullable','numeric','min:0','max:9999999999999.99'],
            'credit_achat' => ['nullable','numeric','min:0','max:9999999999999.99'],
        ],[ 
            'compte_achat.required' => "Compte obligatoire",
            /*'debit_achat.required' => "obligatoire",*/
            'debit_achat.numeric'  => "montant invalide",
            'debit_achat.min'      => "montant invalide",
            'debit_achat.max'      => "montant trop grand",
           /* 'credit_achat.required' => "obligatoire",*/
            'credit_achat.numeric'  => "montant invalide",
            'credit_achat.min'      => "montant invalide",
            'credit_achat.max'      => "montant trop grand",
        ]);
      
          $key = array_search($validator['compte_achat'], array_column($this->MyArray_achat, 'compte')) ;

              if(is_int($key) && $key >= 0){

                  $this->showToastr('failed|ce compte existe déjà');

              }else{
                  
                  if(empty(trim($validator['debit_achat'])) && empty(trim($validator['credit_achat'])) ){
                  
                        $this->showToastr('failed|crédit et débit ne peuvent être vide');
                      
                  }elseif($validator['debit_achat'] > 0 && $validator['credit_achat'] > 0){

                        $this->showToastr('failed|crédit et débit ne peuvent avoir des valeurs');

                  }else{
                      $array = array(
                          'compte' => $validator['compte_achat'],
                          'intitule' => get_intitule_compte($validator['compte_achat']),
                          'debit'     => (empty(trim($validator['debit_achat'])))? 0 : $validator['debit_achat']  ,
                          'credit'    => (empty(trim($validator['credit_achat'])))? 0 : $validator['credit_achat']
                      );
          
                      array_push($this->MyArray_achat , $array);
                      $this->check_if_credit_debit_are_egal_achat();
                      $this->resetItem_achat() ;
                      $montant = ($array['debit'] > $array['credit'])? $array['debit'] : $array['credit'] ;
                      $this->checkIsImmo($array['compte'],$this->libelle_achat,
                                         $montant,$this->devise_achat,$this->date_achat);
                  }
              }
    }

    private function check_if_credit_debit_are_egal_achat(){

        $credit = 0;
        $debit  = 0 ;
        
            foreach($this->MyArray_achat as $array):
                $credit += $array['credit'];
                $debit  += $array['debit'] ;
            endforeach ;
     
       // $this->total_achat = ($credit == $debit) ? $credit : null ;
        $this->isEgal_achat = ($credit == $debit && $debit <> 0) ? true : false ;
        $this->total_debit  = $debit ;
        $this->total_credit = $credit ;
        $this->total_achat =  ($credit == $debit && $debit <> 0) ? $debit : null  ;
        
    }

    public function annulerItem_achat(){
        $this->resetItem_achat();
    }

    public function checkIsImmo($compte,$libelle,$montant,$devise,$date)
    {
        $this->isImmo = (mb_substr($compte, 0, 1) == 2)? true : false ; 

        if($this->isImmo){
            $this->dispatch('sh_ModalConfirmImmo',$compte,$libelle,$montant,$devise,$date);
        }
    }

    public function resetItem_achat(){
        $this->compte_achat =
        $this->debit_achat  =
        $this->credit_achat =  null;
        $this->reset_readOnly_achat() ;
        //$this->isUpdateItem = false ;
        $this->resetValidation() ;
        $this->dispatch('resetSelect_Compte_achat', data : "");
    }

    public function reset_readOnly_achat()
    {   
        $this->debit_achat  =
        $this->credit_achat =  null;
        $this->readonly_credit_achat =
        $this->readonly_debit_achat =
        $this->focus_credit_achat =
        $this->focus_debit_achat = false ;
    }

    public function removeItem_achat($compte){

        $key = array_search($compte, array_column($this->MyArray_achat, 'compte')) ;
        unset($this->MyArray_achat[$key]); 
        $ar = array();

        foreach($this->MyArray_achat as $data):
            array_push($ar,$data);
        endforeach ;
        
        $this->MyArray_achat = $ar ;
        $this->check_if_credit_debit_are_egal_achat();
    }

    public function updatingCompteAchat($value)
    {   
        $this->reset_readOnly_achat() ;
    }

    public function updatedCompteAchat($value)
    {   
        $this->readOnly_achat($value) ;
    }

    public function readOnly_achat($string)
    {
       
        if(mb_substr($string,0,2) == 40 || mb_substr($string,0,2) == 48){
            $this->debit_achat = 0 ;
            $this->readonly_debit_achat = $this->focus_credit_achat = true ;
        }
        if(mb_substr($string,0,1) == 6 ){
            $this->credit_achat = 0 ;
            $this->readonly_credit_achat = $this->focus_debit_achat = true ;
        }
    }

 

    public function OpenModalApercuJournal()
    {   
        $this->dispatch('showModalApercuJournal');
    }

    
    public function resetForm_achat(){
        $this->idFournisseur_achat =
        $this->NumFacture_achat  =
        $this->reference_achat =
        $this->date_achat =
        $this->libelle_achat =  
        $this->compte_achat = 
        $this->total_achat = null;
        $this->MyArray_achat = [] ;
        $this->compte_tiers_achat = '' ;
        $this->value_tiers = 
        $this->debit_achat  = 
        $this->piece_justif =
        $this->file_piece_justif =
        $this->credit_achat = null;
        $this->devise_achat = get_main_devise();
        $this->resetValidation() ;

        $this->isEgal_achat = false;
        $this->total_debit =
        $this->total_credit =
        $this->total_achat = 0 ;
        //$this->dispatch('resetSelect_Tiers_achat', data : "");
    }

    public function updatedIdFournisseurAchat($value)
    {   
        $this->compte_tiers_achat = '' ;
        $this->value_tiers = '';
        $this->ListCompte_achat = get_compte_tiers($value) ;
       //dd($this->ListCompte_achat[0]->num_compte);
        $this->value_tiers = (count($this->ListCompte_achat) > 0)? $this->ListCompte_achat[0]->num_compte : '' ;
        $this->compte_tiers_achat = $this->value_tiers ;
        // get_compte_sj_achat
        // dd($this->ListCompte_achat);
        // dd($this->ListCompte_achat);
        //$this->dispatch('loadSelectCompteAchat');
    }

    public function updatedCompteTiersAchat($value)
    {
        $this->value_tiers = $value;
    }

    public function addItemby()
    {
        $this->addItem_achat() ;
    }

  

    public function equilibrerJAchat()
    {   

        if(empty(trim($this->compte_tiers_achat)) || is_null($this->compte_tiers_achat)){

            $this->showToastr('failed|Sélectionnez un compte tiers');
        }else{

            $key = array_search($this->compte_tiers_achat, array_column($this->MyArray_achat, 'compte')) ;
           
            if(is_int($key) && $key >= 0){
                $this->removeItem_achat($this->compte_tiers_achat);
            }

            if($this->total_debit <  $this->total_credit)
            {
                $array = array(
                    'compte' => $this->compte_tiers_achat,
                    'intitule' => get_intitule_compte($this->compte_tiers_achat),
                    'debit'  => $this->total_credit - $this->total_debit ,
                    'credit' => 0
                );

                array_push($this->MyArray_achat , $array);
                $this->check_if_credit_debit_are_egal_achat();

            }elseif($this->total_debit >  $this->total_credit){

                $array = array(
                    'compte' => $this->compte_tiers_achat,
                    'intitule' => get_intitule_compte($this->compte_tiers_achat),
                    'debit'  =>  0  ,
                    'credit' => $this->total_debit - $this->total_credit
                );

                array_push($this->MyArray_achat , $array);
                $this->check_if_credit_debit_are_egal_achat();

            }else{
               
                $this->MyArray_achat = [] ;
            }
        }
    }
 

    public function saveAchat()
    {
        $this->validate([
            'idFournisseur_achat' => ['required',],
            'piece_justif' => ['nullable','string'],
            'file_piece_justif' => ['nullable','file','mimes:pdf','max:102400'],
            'date_achat' => ['required','date','date_format:Y-m-d','before:tomorrow','after:2000-12-31',new DateBetweenExercice,new CheckTauxChangeByDate,
                                new CheckCloturePeriode, new CheckClotureExercice],
            'libelle_achat' => ['required','string','min:3','max:150'],
             /*'total_ttc_achat' => ['required'],*/
            'devise_achat' => ['required'],
            'MyArray_achat' => ['required','array'],
        ],[
            'idFournisseur_achat.required' => "obligatoire" ,
            'reference_achat.required' => "obligatoire" ,
            'reference_achat.string' => "obligatoire" ,
            'reference_achat.max' => "max. 50 caractères" ,
            
            'NumFacture_achat.string' => "format texte" ,
            'NumFacture_achat.max' => "max. 50 caractères" ,
            'date_achat.required' => "obligatoire" ,
            'date_achat.date' => "format invalide",
            'date_achat.date_format' => "format invalide" ,
            'date_achat.before'    =>  "date erronée", 
            'date_achat.after'     => "date min. 01-01-2001", 
            'libelle_achat.required' => "libellé obligatoire",
            'libelle_achat.string' => "libellé erroné",
            'libelle_achat.min' => "libellé trop court",
            'libelle_achat.max' => "libellé max:150",
            /*'total_ttc_achat.required' => "obligatoire" ,*/
            'devise_achat.required' => "obligatoire" ,
            'MyArray_achat.required' => "les comptes mouvementés attendus" ,
            'MyArray_achat.array' => "les comptes mouvementés attendus" ,
        ]);
        
        try {
                $file = null ;
                if(!is_null($this->file_piece_justif))
                {
                    $file = $this->file_piece_justif->store('p_justif/'.get_id_app(),'public');
                }

                $resp = save_saisie_journaux('od_av',$this->idFournisseur_achat,null,null,$this->date_achat,
                            $this->libelle_achat,$this->total_achat,$this->devise_achat,$this->piece_justif,$file,$this->MyArray_achat);
            
                if($resp)
                {   
                    $this->resetForm_achat();
                    $this->showToastr('success|Enregistrement effectué avec succès');
                }else{
                    $this->showToastr('failed|une erreur est survenue'); 
                }     

            } catch (\Exception $e) {
            
                $this->showToastr('failed|erreur uploading fichier'); 
            }

    }

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