<?php namespace App\Http\Controllers;

use Auth\AuthController;
use App\Models\User;
use App\Models\Role2;
use App\Models\Mandat;
use App\Models\Imputation;
use App\Models\Creancier;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use View;
use DB;

use App\Http\Requests\MandatRequest;
use Request;
use Response;
use App\Models\Parametre;
use App\Models\Journal;

class MandatsController extends Controller {
 
 
    /**
     * Liste
     */
    public function index($exercice="")
    {
        $user=User::where('id','=',Session::get('id'))->first();
        $exercice_encours=Parametre::where('ref','=','CPT_EXERCICE')->first()->value;
        if($exercice=="") $exercice=$exercice_encours; 
        $exercices=$this->getListeExercices();
        $list_exercice="";  
        $mandats=Mandat::where('exercice','=',$exercice)->orderby('id','DESC')->get();
        return View::make('mandatements.mandats.index', [ 
            'user'=>$user,
            'mandats' => $mandats,
            'exercice' => $exercice,
            'exercices' => $exercices,
        ]);
    }


    /**
     * Liste
     */
    public function index_generation($exercice="")
    {
        $user=User::where('id','=',Session::get('id'))->first();

        $list_exercice="";
       
        $mandats=Mandat::where('statut_transfert','=','ATR')->orderby('id','DESC')->get();
        return View::make('mandatements.mandats.index_generation', [ 
            'user'=>$user,
            'mandats' => $mandats,
        ]);
    }

    /* Validation demande de transfert */
    public function set_transfert($id,$exercice="")
    {
        $mandat=Mandat::find($id);
        $mandat->statut_transfert="ATR";
        $mandat->save();
        return $this->index($exercice);
    }
    /* Annulation demande de transfert */
    public function unset_transfert($id,$exercice="")
    {
        $mandat=Mandat::find($id);
        $mandat->statut_transfert="";
        $mandat->save();
        return $this->index($exercice);
    }

     public function create()
    {
        $user=User::where('id','=',Session::get('id'))->first();
        $exercices = $this->getListeExercices();
        return View::make('mandatements.mandats.create', 
            [
            'user'=>$user,
            'exercices' => $exercices,
            ]);
    }
 

    public function store(MandatRequest $request)
    {
        $mandat = new Mandat;
        $mandat->exercice = $request->exercice;
        $mandat->statut_mdt = $request->statut_mdt;
        $mandat->type = (!isset($request->type) || ($request->type==''))?"P":$request->type;

        $date = $request->date_sai;
        $mandat->date_sai = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $date = $request->date_valid;
        $mandat->date_valid = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $date = $request->date_valid_dir;
        $mandat->date_valid_dir = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;

        $mandat->observation_val = $request->observation_val;
        $mandat->observation = $request->observation;
        $mandat->observation_dir = $request->observation_dir;
        $mandat->save();
        return Redirect::to('mandatements/mandats/'.$mandat->id.'/edit');
     }
 

    public function edit($id)
    {
        $user=User::where('id','=',Session::get('id'))->first();
        $mandat=Mandat::find($id);
        if(!$mandat) return;
        $exercices = $this->getListeExercices();

        $imputations=Imputation::where('idmandat','=',$mandat->id)->get();
        $creanciers=Creancier::where('idmandat','=',$mandat->id)->get();
        return View::make('mandatements.mandats.edit', 
            [
            'mandat' => $mandat,
            'user'=>$user,
            'exercices' => $exercices,
            'imputations' => $imputations,
            'creanciers' => $creanciers
            ]);

    }



    public function show($id)
    {
        $user=User::where('id','=',Session::get('id'))->first();
        $mandat=Mandat::find($id);
        if(!$mandat) return;
        $exercices = $this->getListeExercices();

        $imputations=Imputation::where('idmandat','=',$mandat->id)->get();
        $creanciers=Creancier::where('idmandat','=',$mandat->id)->get();

        return View::make('mandatements.mandats.show', 
            [
            'mandat' => $mandat,
            'user'=>$user,
            'imputations' => $imputations,
            'creanciers' => $creanciers
            ]);
     }
 


    public function update($id,MandatRequest $request)
    {

        $delete_imputation=$request->delete_imputation;
        $delete_creancier=$request->delete_creancier;
        $refresh=$request->refresh;

        if($delete_imputation>0) {
            Imputation::destroy($delete_imputation);
            return Redirect::to('mandatements/mandats/'.$id.'/edit');
        }
        if($delete_creancier>0) {
            Creancier::destroy($delete_creancier);
            return Redirect::to('mandatements/mandats/'.$id.'/edit');
        }
        $mandat = Mandat::find($id);
        $date_valid_orig=$mandat->DateValidUS;
        $mandat->exercice = $request->exercice;
        $mandat->statut_mdt = $request->statut_mdt;
        $mandat->type = (!isset($request->type) || ($request->type==''))?"P":$request->type;

        $date = $request->date_sai;
        $mandat->date_sai = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $date = $request->date_valid;
        $mandat->date_valid = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $date = $request->date_valid_dir;
        $mandat->date_valid_dir = ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;

        $mandat->observation_val = $request->observation_val;
        $mandat->observation = $request->observation;
        $mandat->observation_dir = $request->observation_dir;
        $mandat->save();

        $comptes=["CLR"=>"","CPF"=>"","ASE"=>"","AVI"=>"","CSR"=>""];
        $comptes['CLR']=Parametre::where('ref','=','CPT_COMPTE_CLR')->first()->value;
        $comptes['CPF']=Parametre::where('ref','=','CPT_COMPTE_CPF')->first()->value;
        $comptes['ASE']=Parametre::where('ref','=','CPT_COMPTE_ASE')->first()->value;
        $comptes['AVI']=Parametre::where('ref','=','CPT_COMPTE_AVI')->first()->value;
        $comptes['CSR']=Parametre::where('ref','=','CPT_COMPTE_AVI')->first()->value;

        //Passage en compta
        //
        if(($date_valid_orig==null) && ($mandat->date_valid!=null)) {
            $mandat = Mandat::find($id);
            $mandat->statut_mdt="VAL";
            $mandat->save();
            foreach($comptes as $type_imp=>$compte) {
                $imputations=Imputation::where('idmandat','=',$id)
                    ->where('type_imp','=',$type_imp)
                    ->get();
                $montant_debit=0;
                $montant_credit=0;

                foreach($imputations as $imputation) {
                    $journal=Journal::where('imputation_mdt_id','=',$imputation->id)
                        ->where('debit','>','0')->where('credit','=','0')->first();
                    if(!$journal) $journal=new Journal;
                    $journal->date=$mandat->DateValidUS;
                    $journal->numcpt=$imputation->cpt_imp;
                    $journal->ref="MDT ".$id;
                    $journal->libelle=$imputation->designation;
                    $journal->debit=$imputation->montant;
                    $journal->credit=0;
                    $journal->enc=0;
                    $journal->imputation_mdt_id=$imputation->id;
                    $journal->save();

                    //Compensation
                    $journal=Journal::where('imputation_mdt_id','=',$imputation->id)
                        ->where('debit','=','0')->where('credit','>','0')->first();
                    if(!$journal) $journal=new Journal;
                    $journal->date=$mandat->DateValidUS;
                    $journal->numcpt=$comptes[$imputation->type_imp];
                    $journal->ref="MDT ".$id;
                    $journal->libelle=$imputation->designation;
                    $journal->debit=0;
                    $journal->credit=$imputation->montant;
                    $journal->enc=0;
                    $journal->imputation_mdt_id=$imputation->id;
                    $journal->save();
               }
            }
        }

        if($refresh==true) {
            return Redirect::to('/mandatements/mandats/'.$id.'/edit/');
        }
        return Redirect::to('mandatements/mandats/');
    }
 

    public function destroy($id)
    {
        Mandat::destroy($id);
 
        return Redirect::to('/mandatements/mandats/');
    }


    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 exercices sur 2 ans
     */
     /*
    publ
    public function getListeExercicesBi()
    {
        $exercices = $this->getListeExercices();
        $nb_exercices=count($exercices );
        $k=0;$t=array();
        foreach($exercices as $exercice) {
            $k++;
            $exercice_min=intval($exercice)-1;
            $exercice_max=intval($exercice)+1;
            if($k%2==0) {
                $t[$exercice_min."-".$exercice]=$exercice_min." - ".$exercice;
                if($k<$nb_exercices) $t[$exercice."-".$exercice_max]=$exercice." - ".$exercice_max;
            }
        }
        arsort($t);
        $t['*']='Tous';
        return $t;
    }
    */
 
}