<?php

namespace App\Livewire;

use App\Exports\CompteComptableExport;
use App\Exports\CompteExportFromView;
use App\Imports\CompteComptableImport;
use App\Imports\CompteDivisionnaireImport;
use App\Imports\ComptePrincipalImport;
use App\Imports\SousCompteImport;
use Livewire\WithPagination;
use App\Models\CompteComptable;
use App\Models\Devise;
use App\Rules\MaxCompte;
use App\Rules\MinCompte;
use Illuminate\Support\Carbon;
use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Livewire\WithFileUploads;
use Exception;

class CompteDevise extends Component
{   

    use WithFileUploads;
    use WithPagination;

    public $tab = null;
    public $tabname = "compte" ;
    protected $queryString = ['tab'] ;
    public  $user_id, $id_compte, $num_compte, $nom_compte, $type_compte, $fk_cg_code, $is_active, $title_modal, $ligne , $search = "";
    public  $liste_devise, $isNew , $file  ;

    // *************** /
    public $Is_main_devise ;
    public $Is_devise_used = [];
    
    public function selectTab($tab){
        $this->tab = $tab ;
    }


    public function mount(){
        $this->tab = request()->tab ? request()->tab : $this->tabname ;
        $this->ligne = 10 ;
        $idCurrent_ParentDevise = get_Current_idParent_Devise();
        $this->type_compte = "hybrid";
        $this->setIsNew(true) ;
        $this->liste_devise =   DB::select('SELECT 
                                        sys.devise, 
                                        sys.intitule ,
                                        sys.is_active ,
                                        sys.is_devise_local             
                                    FROM `sys_tbl_devise` sys ORDER BY sys.intitule'  
                                );

        $dev = Devise::select('devise')
                        ->where(['is_main' => 1, 'fk_id_parent' => $idCurrent_ParentDevise])
                        ->first();

       $this->Is_main_devise = ($dev)? $dev->devise : null ;

        $this->Is_devise_used = Devise::where(['fk_id_parent' => $idCurrent_ParentDevise])
                                         ->pluck('devise');          
    }

   /* public function loadListofCompteCompta()
    {
          
        $this->liste_compte = DB::table('cpt_tbl_compte_comptable')
            ->where(['id_app' => get_id_app() ])
            ->get();
    } */

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatedLigne()
    {
        $this->resetPage();
    }

    public function updateDevise(){
      
      

        $exec = create_Devise(collect($this->Is_devise_used)->toArray(),$this->Is_main_devise);
        if($exec)
        {
            $this->showToastr('success|Création success');
        }else{
            $this->showToastr('failed|Echec de création');
        }
        
    }

    public function handlerImport(){

        $this->validate([
            'file' => ['required', 'mimes:xlsx'],
        ], 
        [
            'file.required' => "fichier obligatoire",
            'file.mimes'    => "format attendu .xlsx",
        ]);

       
            Excel::import(new CompteComptableImport, $this->file);
           // Excel::import(new ComptePrincipalImport, $this->file);
          // Excel::import(new CompteDivisionnaireImport, $this->file);
          //Excel::import(new SousCompteImport, $this->file);
            $this->showToastr('success|Importation reussie ');
            $this->dispatch('hideImportModal');

    }

    public function ExportCompteCompta(){

        $file = 'exportListeCompte_'. Carbon::now()->format('d_m_Y_Hi');
        return Excel::download(new CompteComptableExport,$file.'.xlsx');
      //  return Excel::download(new CompteExportFromView,$file.'.pdf',\Maatwebsite\Excel\Excel::DOMPDF);

        
    }

    public function updateCompteCompta(){

        $this->validate([
            'num_compte'  => ['required','numeric',new MaxCompte],
            'type_compte' => ['required'],
            'nom_compte'  => ['required','string','min:3','max:100'],
        ],
        [
            'num_compte.required'  => "obligatoire",
            'num_compte.numeric'  => "invalide",
            'type_compte.required' => "obligatoire",
            'nom_compte.required'  => "obligatoire",
            'nom_compte.min'  => "invalide",
            'nom_compte.max'  => "max. 100 caractères",
        ]);

        $data = array(
            'num_compte'  => $this->num_compte,
            'type_compte' => $this->type_compte,
            'nom_compte'  => $this->nom_compte,
            'id_app'      => get_id_app(),
            'user'        => get_pseudo()
        );


        try{

            if($this->isNew){

                    $response = DB::select('call CPT_SAVE_COMPTE_COMPTABLE(:num_compte,:nom_compte,:type_compte,:id_app,:user)'
                        , $data);

                        if(isset($response[0]->Message)){
                                if($response[0]->Message == 1){
                                    $this->showToastr('success|Création effectuée avec success');
                                    $this->resetFormCompte();
                                }else{
                                    $this->showToastr('failed|'.$response[0]->Message);
                                }
                        }else{
                            $this->showToastr('failed|Echec de création');
                        }   

            }else{

                $compte = CompteComptable::findOrFail($this->id_compte);

                $compte->fill([
                    'nom_compte' => $this->nom_compte ,
                    'type_compte' => $this->type_compte,
                ]);
                $compte->save();
                $this->showToastr('success|Modification effectuée avec success');
                $this->CloseModalNewCompte();
            }

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


    public function editCompteCompta(CompteComptable $Compte)
    {
       // $Compte = CompteComptable::find($id);
        $this->num_compte = $Compte->num_compte;
        $this->nom_compte = $Compte->nom_compte ;
        $this->type_compte = $Compte->type_compte ;
        $this->id_compte = $Compte->id ;
        $this->setIsNew(false) ;
        $this->OpenModalNewCompte();

    }

    public function OpenModalNewCompte()
    {   
       
        $this->dispatch('showModal');
    }

    private function setIsNew($bool){
        $this->isNew = $bool ;
        $this->title_modal = ($bool) ? "Nouveau Compte comptable" : "Update Compte comptable";
    }

    public function OpenModalImport()
    {
        $this->dispatch('showImportModal');
    }

    

    public function CloseModalNewCompte()
    {
        $this->resetFormCompte();
        $this->dispatch('hideModal');
        $this->setIsNew(true) ;
    }

    public function CloseImportModal()
    {
        $this->file = null ;
        $this->resetValidation();
        $this->dispatch('hideImportModal');
    }

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

    public function resetFormCompte()
    {
        $this->num_compte = $this->nom_compte = $this->id_compte = null;
        $this->resetValidation();
        $this->type_compte = "hybrid";
    }

    public function render()
    {
        return view('livewire.compte-devise', [
            'liste_compte' => CompteComptable::where(['id_app' => get_id_app()])
                        ->search($this->search)
                        ->orderBy('num_compte', 'ASC')
                        ->paginate($this->ligne) ,
        ]);
    }
}
