<?php namespace App\Http\Controllers\Compta_old;

use Auth\AuthController;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\Journal_compta_old;
use App\Models\Parametre;
use App\Models\Imputation;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use View;
use DB;
use App\Http\Requests\JournalOLDRequest;
use Illuminate\Http\Request;
use Validator;


class JournauxController extends Controller {
    private $menu='old_compta';
    private $submenu='compta_old_journaux';
    private $menu_home='comptabilite';


    public function index($exercice="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $exercice_encours=Parametre::where('ref','=','CPT_EXERCICE')->first()->value;
        if($exercice=="") $exercice=$exercice_encours;
        $exercices=$this->getListeExercices();
        $journaux=Journal_compta_old::where('date','like',$exercice."%")->get();
        Session::put('journal_exercice',$exercice);

        return View::make('compta_old.journal.index', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'journaux' => $journaux, 
            'exercices' => $exercices,
            'exercice' => $exercice,
            'exercice_encours' => $exercice_encours,
        ]);

    }

    public function index_ltd($exercice,$numcpt)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $exercice_encours=Parametre::where('ref','=','CPT_EXERCICE')->first()->value;
        if($exercice=="") $exercice=$exercice_encours;
        $journaux=Journal_compta_old::where('date','like',$exercice."%")->where('numcpt','=',$numcpt)->get();

        return View::make('compta_old.journal.index_ltd', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'journaux' => $journaux, 
            'exercice' => $exercice,
            'numcpt' => $numcpt,
            ]);

    }

    public function show($journal_id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $journal=Journal_compta_old::find($journal_id);

        return View::make('compta_old.journal.visu', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'journal' => $journal
        ]);

    }

    public function create()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $comptes=$this->getListeComptes();
        return View::make('compta_old.journal.create', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'comptes' => $comptes
        ]);
    }
 
     public function create_compense($lst_ecritures)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $comptes=$this->getListeComptes();

        $t_ecritures=explode("~",$lst_ecritures);
        foreach($t_ecritures as $ecriture) 
            if($ecriture!="") $t_journaux[]=$ecriture;

        $journaux=Journal_compta_old::wherein('id',$t_journaux)->get();
        $debit=0;$credit=0;
        $ref="";$libelle="";
        foreach($journaux as $journal) {
            $debit+=$journal->credit;
            $credit+=$journal->debit;
            $ref=$journal->ref;
            $imputation=imputation::find($journal->imputation_mdt_id);
            if($imputation) $libelle=$imputation->designation;
        } 

        return View::make('compta_old.journal.create_compense', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'comptes' => $comptes,
            'debit' =>$debit, 
            'credit' =>$credit, 
            'ref' =>$ref, 
            'libelle' =>$libelle, 
            ]);
    }

    public function store(JournalOLDRequest $request)
    {
        dd($request);
        $t_error=[];
        $budget=0;$budget2=0;
        $plan=array();$plan2=array();

        //$comptes=$this->getListeComptes();
        //$compte=$request->numcpt; //Changement 2024
        $compte=$request->nomcpt;
        $compte2=$request->numcpt2;
        $budget=$request->budget;


        $debit=(isset($request->debit)&&($request->debit<>""))?$request->debit:0;
        $credit=(isset($request->credit)&&($request->credit<>""))?$request->credit:0;       

        $date=$request->date;
        $exercice=date('Y', strtotime(str_replace('/', '-', $date)));
        $exercice_encours=Parametre::where('ref','=','CPT_EXERCICE')->first()->value;

        if($compte) {
            $plan=Plan::where("numcpt","=",$compte)->first(); 
        }
        if($compte2) {
            $plan2=Plan::where("numcpt","=",$compte2)->first(); 
            $budget2=$request->budget2;
        }

        //Si crédit et débit de remplis et pas de compensation
        if(($credit!=0)&&($debit!=0)) {
            $t_error['credit_debit']='Il ne peut pas avoir un crédit et un débit sur le même compte (en remplir un seul dans tous les cas)';
        }
        //Si crédit et débit de remplis et pas de compensation
        if(($credit==0)&&($debit==0)) {
            $t_error['credit_debit_saisie']="La saisie d'un montant de débit ou un montant de crédit est obligatoire";
        }

        $cat_compte=substr($compte,0,1);
        //Controle Budget si exercice en cours
        if(($debit>0)&&($exercice==$exercice_encours) && ($cat_compte!='4') && ($cat_compte!='5') )  {
            $solde_cpt=$plan->getSoldeCalc($exercice);
            $reste=$budget-$solde_cpt-$debit;
            if($reste < 0 ) {
                $t_error['budget_dep']="Le budget sur le compte ".$compte." est dépassé de ".$reste." CFP";
            }
        }

        $liste_cotisations=$request->liste_cotisations;
        if (count($t_error)>0) {

            //Session::flash('nom_compte2', $plan2->nomcpt);
            return redirect()->back()
                ->withInput()
                ->withErrors($t_error);
        }

        $journal = new Journal;
        $date=$request->date;
        $journal->date = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):"" ;
        $journal->numcpt=$request->numcpt;
        $journal->ref=$request->ref;
        $journal->libelle=$request->libelle;
        $journal->debit=$debit;
        $journal->credit=$credit;
        $journal->enc=(isset($request->enc)?$request->enc:0);
        $journal->budget=$request->budget;
        //$journal->amortissement=$request->amortissement;
        $journal->save();

        //Compensation
        if( isset($request->numcpt2) && ($request->numcpt2>0) ) {
            $journal = new Journal;
            $date=$request->date;
            $journal->date = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):"" ;
            $journal->numcpt=$request->numcpt2;
            $journal->ref=$request->ref;
            $journal->libelle=$request->libelle;
            $journal->debit=($debit==0)?$credit:0;
            $journal->credit=($credit==0)?$debit:0;
            $journal->enc=(isset($request->enc)?$request->enc:0);
            $journal->budget=$request->budget2;
            $journal->save();
        }
        $exercice=Session::get('journal_exercice');
        if(isset($exercice)) return Redirect::to('/compta_old/journal_exercice/'.$exercice);
        return Redirect::to('/compta_old/journal');
    }
 
    public function edit($id)
    {
        //30/03/21 Modification interdite
        return "";
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $comptes=$this->getListeComptes();
        $journal = Journal_compta_old::find($id);
        return View::make('compta_old.journal.edit', ['comptes' => $comptes,
            'journal' => $journal, 'user'=>$user]); 
    }

    public function update($id,JournalOLDRequest $request)
    {
        //30/03/21 Modification interdite
        return "";
        $journal = Journal_compta_old::find($id);
        $date=$request->date;
        $journal->date = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):"" ;    
        $journal->numcpt=$request->numcpt;
        $journal->ref=$request->ref;
        $journal->libelle=$request->libelle;
        $journal->debit=$request->debit;
        $journal->credit=$request->credit;
        $journal->enc=$request->enc;
        $journal->budget=$request->budget;
        $journal->save();

        $exercice=Session::get('journal_exercice');
        if(isset($exercice)) return Redirect::to('/compta_old/journal_exercice/'.$exercice);
        return Redirect::to('/compta_old/journal');
    }
 
    public function destroy($id)
    {
        //30/03/21 Modification interdite
        return "";
        Journal_compta_old::destroy($id);
 
        return Redirect::to('/compta_old/journal');
    }
 
    /**
     * Listes des exercices
     */
    public function getListeExercices()
    {
        $t_exercices=array();
        $exercices = DB::table('journal')
            ->select(db::raw("distinct(LEFT(date,4)) as exercice"))
            ->orderby('exercice','DESC')->get(); 

        foreach($exercices as $exercice) $t_exercices[$exercice->exercice]=$exercice->exercice;
        if(!isset($t_exercices[date('Y')])) $t_exercices[date('Y')]=date('Y');
        arsort($t_exercices);
        return $t_exercices;
    }

    /**
     * Listes des Comptes
     */
    public function getListeComptes()
    {
        $comptes = DB::table('plans')
            ->select('numcpt',db::raw("CONCAT(numcpt,' ',nomcpt) as nomcpt"))
            ->distinct('exercice')
            ->pluck('nomcpt','numcpt')->toArray();

        return $comptes;
    }


    public function auto_compte_compta(Request $request)
    {        
        $param = $request->term;
        $associate = array();
        $search    = DB::select(
            "select numcpt as id ,CONCAT(numcpt,' ',TRIM(nomcpt)) as value,budget
            from plans
            where numcpt like ('{$param}%')
            or nomcpt like ('{$param}%')
            order by numcpt
            "
        );
        foreach ($search as $result) {
            $associate[] = $result;
        }
        return json_encode($associate);
    }


}