<?php namespace App\Http\Controllers;

use Auth\AuthController;
use App\User;
use App\Models\Stage;
use App\Models\Classe;
use App\Models\Enseignant;
use App\Models\SessionStage;
use App\Models\TypeStage;
use App\Models\MyApp;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use View;
use App\Http\Requests\SessionStageRequest;
use Illuminate\Http\Request;
use DB;

class SessionsController extends Controller {

    private $menu='stages';
    private $submenu='sessions';

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

        $classe="";
        $sessions = SessionStage::where("date_deb","like",date('Y')."%")->get();
        $classes=Classe::select('id','nom')->orderby("nom","asc")->get()->pluck('nom','id')->toArray();
        if($classes_id=="") $classes_id=Session::get("classe_select");
        if($classes_id) {
            Session::put("classe_select", $classes_id); 
            $sessions=$sessions->where('id_classe','=',$classes_id); 
            $classe=Classe::find($classes_id);
        }

        return View::make('stages.sessions.index', [
            'user' => $user,'menu' => $this->menu,'submenu'=>$this->submenu,
            'sessions' => $sessions,
            'classes' => $classes,'classe' => $classe
        ]);
    }

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

        $sessions = SessionStage::where("date_deb","like",date('Y')."%")->get();
        $classes=Classe::orderby("nom","asc")->get();
        $annee_dep=date('Y');
        $semaines=MyApp::week2day2tab();
        return View::make('stages.sessions.index_calendar', [
            'user' => $user,'menu' => $this->menu,'submenu'=>$this->submenu,
            'sessions' => $sessions,
            'classes' => $classes,
            'semaines' => $semaines
        ]);
    }

    public function create_pop($id_classe,$groupe,$semaine="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("ajouter sessions")) return Redirect::route('home');

        $mode="create";
        $types=array();
        $type_defaut="";
        $types=TypeStage::orderby('nom')->pluck('nom','id')->toArray();
        $classe=Classe::find($id_classe);
        $enseignants = Enseignant::select('id',db::raw("CONCAT(nom,' ',prenom) as nom"))->orderby('nom','ASC')->pluck('nom','id')->toArray();

        $date_debut="";$date_debutUS="";
        if($semaine) {
            $t_periode=MyApp::week2day($semaine);
            $date_debutUS=$t_periode[0];
            $date_debut=date('d/m/Y', strtotime($date_debutUS));
        }

        return View::make('stages.sessions.create_pop', [ 
            'user' => $user,'mode' => $mode,
            'types' => $types,
            'classe' => $classe,'groupe' => $groupe,'enseignants' => $enseignants,"semaine" => $semaine,
            'type_defaut' => $type_defaut,
            'date_debut' => $date_debut,'date_debutUS' => $date_debutUS,
            ]);
    }

    public function store(SessionStageRequest $request)
    {
        $sessionstage = $this->setData($request);
        $msg="La session ".$sessionstage->NomComplet." a été ajoutée";
        Session::flash('message', $msg); 
        return Redirect::back();
    }
 
    public function edit_pop($id,$mode="edit")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("modifier sessions")) return Redirect::route('home');

        $sessionstage = SessionStage::find($id);
        $classe=Classe::find($sessionstage->id_classe);
        $semaine=MyApp::getSemaine($sessionstage->DateDebUS);
        $types=TypeStage::orderby('nom')->pluck('nom','id')->toArray();
        $enseignants = Enseignant::select('id',db::raw("CONCAT(nom,' ',prenom) as nom"))->orderby('nom','ASC')->pluck('nom','id')->toArray();


        return View::make('stages.sessions.'.$mode.'_pop', [ 
            'user' => $user,'mode' => $mode,
            'types' => $types,
            'classe' => $classe,'groupe' => $sessionstage->groupe,'enseignants' => $enseignants,"semaine" => $semaine,
            'sessionstage' => $sessionstage
            ]);
    }

    public function update($id,SessionStageRequest $request)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("modifier sessions")) return Redirect::route('home');

        $sessionstage = $this->setData($request,$id);
        $msg="La session ".$sessionstage->NomComplet." a été mise à jour";
        Session::flash('message', $msg); 
        return Redirect::back();
    }
 
    public function show($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("consulter sessions")) return Redirect::route('home');

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

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

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

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

        $session = SessionStage::find($id);
        $nom=$session->NomComplet;
        if(!$session->CanDelete) {
            $msg="La session ".$nom." ne peut pas être supprimée";
        } else {
            SessionStage::destroy($id);
            $msg="La session ".$nom." a été supprimée";   
        }  
        Session::flash('message', $msg);  
        return Redirect::to('/closepop');
    }



    /*
    private function retour_index()
    {
        $submenu=Session::get('menu_session');
        if($submenu=="sessions configuration")  Redirect::to('sessions_config');
        if($submenu=="sessions en-cours")  Redirect::to('sessions_encours');
        if($submenu=="sessions terminees")  Redirect::to('sessions_terminees');
        return Redirect::to('/sessions');
    }
    */

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

        if($id=="") $sessionstage =  new SessionStage;
        else $sessionstage = SessionStage::find($id);

        $sessionstage->nom=$request->nom;
        $sessionstage->id_classe=$request->id_classe;
        $sessionstage->id_prof=$request->id_prof;
        $color=$request->color;
        if($color==null || $color=="#000000") $color="#F90606"; //Rouge par défaut
        $sessionstage->color=$color;
        $sessionstage->id_prof=$request->id_prof;
        $sessionstage->id_type_stage=$request->id_type_stage;
        $date=$request->date_deb;
        $sessionstage->date_deb= ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $date=$request->date_fin;
        $sessionstage->date_fin= ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
        $sessionstage->save();

        return $sessionstage;
    }


    /*
    public function generation($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        
        $sessionstage = SessionStage::find($id);
        $menu=Session::get('menu_session');

        $t_eleves_avec=Stage::where('id_session','=',$sessionstage->id)->pluck('id_eleve')->toArray();
        $eleves_sans=Eleve::whereNotIn('id',$t_eleves_avec)->where('id_classe','=',$sessionstage->id_classe)->get();
        $eleves_avec=Eleve::whereIn('id',$t_eleves_avec)->where('id_classe','=',$sessionstage->id_classe)->get();
        $eleves=Eleve::where('id_classe','=',$sessionstage->id_classe)->get();


        return View::make('stages.sessions.generate', [ 
            'user' => $user,
            'sessionstage' => $sessionstage,
            'menu' => $menu,
            'eleves' => $eleves,
            'eleves_sans' => $eleves_sans,
            'eleves_avec' => $eleves_avec,
            ]);
    }

    public function set_generation($id,Request $request)
    {
        $sessionstage = SessionStage::find($id);
        $liste_eleves=$request->in_list;
        $t_liste_eleves=explode(";",$liste_eleves);

        $horaires_defaut=[
            "LUNDI"=>"07:00;11:30;13:00;16:30",
            "MARDI"=>"07:00;11:30;13:00;16:30",
            "MERCREDI"=>"07:00;11:30;13:00;16:30",
            "JEUDI"=>"07:00;11:30;13:00;16:30",
            "VENDREDI"=>"07:00;11:30;13:00;15:30",
            "SAMEDI"=>";;;",
        ];
        //Ajout
        foreach($t_liste_eleves as $eleve_id) {
            $existe=Stage::where("id_session","=",$sessionstage->id)->where("id_eleve",'=',$eleve_id)->count();
            if($existe==0) {
                $stage=new Stage;
                $stage->id_session=$sessionstage->id;
                $stage->id_eleve=$eleve_id;
                $date=$sessionstage->date_deb;
                $stage->date_deb= ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
                $date=$sessionstage->date_fin;
                $stage->date_fin= ($date!="")?date('Y-m-d', strtotime(str_replace('/', '-', $date))):null ;
                $stage->statut="INI";
                $stage->horaires=json_encode($horaires_defaut);
                $stage->save();
            }
        }
        return $this->index();

    }
    */
}   