<?php namespace App\Http\Controllers;

use Auth\AuthController;
use App\Models\User;
use App\Models\Role2;
use App\Models\Imputation;
use App\Models\Mandat;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use View;
use DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\ImputationRequest;
use Request;
use Response;
use App\Models\Parametre;


class ImputationsController extends Controller {

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

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

        $exercices = $this->getListeExercicesBi();
        if($exercice!="*") {
            if($exercice=="") $exercice=(intval(date('Y'))-1)."-".intval(date('Y'));
            $list_exercice="";

            if(strlen($exercice)==9)  $list_exercice=explode('-',$exercice);
            if($list_exercice!='')
                    $obj_mandats = Mandat::wherein('exercice',$list_exercice);
            else  $obj_mandats = Mandat::where('id','<>','');
            $mandats=$obj_mandats->orderby('id','DESC')->pluck('id')->toArray();

            $imputations=Imputation::orderby('id')->whereIn('idmandat',$mandats)->get();
        } else {
            $imputations=Imputation::orderby('id')->get();
        }

        return View::make('mandatements.imputations.index', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'imputations' => $imputations,
            'exercice' => $exercice,
            'exercices' => $exercices,
        ]);
    }

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

        $comptes=$this->getListeComptes();
        $mode="create";
        $frame=0;
        return View::make('mandatements/imputations.create',
            [
                'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,"mode"=>$mode,
                "comptes"=>$comptes,"frame"=>$frame,
            ]);
    }

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

        $comptes=$this->getListeComptes();
        $mandat=Mandat::find($mandat_id);
        $mode="create";
        $frame=1;
        return View::make('mandatements.imputations.create', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'mandat' => $mandat,"comptes"=>$comptes,
            "frame"=>$frame,"mode"=>$mode
        ]);
    }

    public function store(ImputationRequest $request)
    {
        $mode_frame=$request->mode_frame;
        $imputation = $this->setData($request);

        if($mode_frame) {
            $msg="L'imputation a été créée";
            Session::flash('message', $msg);
            return Redirect::back()->with('msg', $msg);
        }
        return Redirect::to('imputations/');
    }

    public function edit($id,$mode="edit",$frame="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        if(!$user->hasRole('ADMINISTRATEUR')) {
            if(($mode=="edit") && !$user->can("IMP_MAJ")) return redirect('home');
            else if(!$user->can("IMP_VISU")) return redirect('home');
        }

        $imputation=Imputation::find($id);
        $comptes=$this->getListeComptes();

        return View::make('mandatements.imputations.'.$mode, [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,"mode"=>$mode,
            'imputation' => $imputation,
            'frame' => $frame,
            "comptes" => $comptes
        ]);
    }

    public function edit_avec_mandat($id,$id_mandat="",$mode="edit",$frame=false)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        if(!$user->hasRole('ADMINISTRATEUR')) {
            if(($mode=="edit") && !$user->can("IMP_MAJ")) return redirect('home');
            else if(!$user->can("IMP_VISU")) return redirect('home');
        }

        $mandat="";
        if($id_mandat) $mandat=Mandat::find($id_mandat);
        if($mandat) $frame=true;
        $imputation=Imputation::find($id);
        $comptes=$this->getListeComptes();

        return View::make('mandatements.imputations.'.$mode, [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,"mode"=>$mode,
            'imputation' => $imputation,
            'frame' => $frame,
            'mandat' => $mandat, "comptes" => $comptes
        ]);
    }

    public function show_frame($id,$id_mandat)
    {
        return $this->show($id,$id_mandat,true);
    }

    public function show($id,$id_mandat="",$frame=false)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if($id_mandat) return $this->edit_avec_mandat($id,$id_mandat,"show",$frame);
        return $this->edit($id,"show",$frame);
    }

    public function update($id,ImputationRequest $request)
    {
        $mode_frame=$request->mode_frame;
        $imputation = $this->setData($request,$id);

        if($mode_frame) {
            $msg="L'imputation a été modifiée";
            Session::flash('message', $msg);
            return Redirect::back()->with('msg', $msg);
        }
        return Redirect::to('imputations/');
    }

    public function destroy($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("IMP_SUP")) return redirect('home');
        if($imputation->IsSupprimable) Imputation::destroy($id);
        return Redirect::to('imputations/');
    }

    public function setData($request,$id="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        if($id=="") $imputation =  new Imputation;
        else $imputation = Imputation::find($id);

        if(isset($request->idmandat) && $request->idmandat) $imputation->idmandat = $request->idmandat;
        $imputation->cpt_imp = $request->cpt_imp;
        $imputation->designation = $request->designation;
        $imputation->montant = $request->montant;
        $imputation->type_imp = $request->type_imp;
        $imputation->obs = $request->obs;
        $imputation->save();
        return $imputation;
    }

    /**
     * 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;
    }

    /**
     * Listes des exercices
     */
    public function getListeExercices()
    {
        $exercices = DB::table('mandats')->select('exercice')->distinct('exercice')->pluck('exercice')->toArray();

        return $exercices;
    }

    /**
     * Listes des exercices sur 2 ans
     */
    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;
    }

}
