<?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 Illuminate\Support\Facades\Auth;
use App\Http\Requests\MandatRequest;
use Request;
use Response;
use App\Models\Parametre;
use App\Models\Journal;

class MandatsController extends Controller {


    private $menu='mandatements';
    private $submenu='mandats';
    private $menu_home='mandatement';

    public function index($exercice="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_VISU")) return redirect('home');

        $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,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'mandats' => $mandats,
            'exercice' => $exercice,
            'exercices' => $exercices,
        ]);
    }

    public function index_generations($exercice="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_MAJ")) return redirect('home');

        $list_exercice="";
        $this->submenu="mandats_generations";
        $mandats=Mandat::where('statut_transfert','=','ATR')->orderby('id','DESC')->get();
        return View::make('mandatements.mandats.index_generation', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            '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()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_AJO")) return redirect('home');

        $exercices = $this->getListeExercices();
        $mode="create";
        return View::make('mandatements.mandats.create',
        [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,"mode"=>$mode,
            '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('mandats/'.$mandat->id.'/edit');
     }

    public function edit($id,$mode="edit")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_MAJ")) return redirect('home');

        $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.'.$mode,
            [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,"mode"=>$mode,
            'mandat' => $mandat,
            'exercices' => $exercices,
            'imputations' => $imputations,
            'creanciers' => $creanciers
            ]);

    }

    public function show($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_VISU")) return redirect('home');

        return $this->edit($id,"show");
     }

    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('mandats/'.$id.'/edit');
        }
        if($delete_creancier>0) {
            Creancier::destroy($delete_creancier);
            return Redirect::to('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=="0000-00-00") && ($mandat->date_valid!="0000-00-00")) {
            $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($request->reload_form==true) {
            return Redirect::to('/mandats/'.$id);
        }
        if($refresh==true) {
            return Redirect::to('/mandats/'.$id.'/edit/');
        }
        return Redirect::to('mandats/');
    }


    public function destroy($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("MDT_SUP")) return redirect('home');

        Mandat::destroy($id);
        return Redirect::to('/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;
    }


}
