<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Session;
use App\MembreJury;
use Illuminate\Http\Request;

class MembreJuryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $keyword = $request->get('search');
        $perPage = 25;

        if (!empty($keyword)) {
            $membrejury = MembreJury::where('nom', 'LIKE', "%$keyword%")
                ->join('grade', ['gestjury_membre_jury.grade'=> 'grade.idGrade'])
                ->orWhere('prenoms', 'LIKE', "%$keyword%")
                ->orWhere('email', 'LIKE', "%$keyword%")
                ->orWhere('phone', 'LIKE', "%$keyword%")
                ->orWhere('description', 'LIKE', "%$keyword%")
                ->orWhere('qualite', 'LIKE', "%$keyword%")
                ->orWhere('sexe', 'LIKE', "%$keyword%")
                ->orWhere('type', 'LIKE', "%$keyword%")
                ->orWhere('matricule', 'LIKE', "%$keyword%")
                ->latest()->paginate($perPage);
        } else {
            $membrejury = MembreJury::latest()
            ->join('grade', ['gestjury_membre_jury.grade'=> 'grade.idGrade'])
            ->paginate($perPage);
        }

        return view('admin.membre-jury.index', compact('membrejury'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
         # Update enseignants
         $enseignants = DB::connection(session::get('gestjury_database'))->table('enseignant')->get();
         foreach ($enseignants as $enseignant) {
            $is_jury_member = DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
                                 ->where(['matricule'=> $enseignant->matricule])->exists();
            if (!$is_jury_member) {
                DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')->insert([
                    'nom' => $enseignant->nom, 
                    'prenoms'=> $enseignant->prenom, 
                    'email'=> $enseignant->email, 
                    'phone'=> $enseignant->phone, 
                    'description'=> $enseignant->nom.'  '.$enseignant->prenom, 
                    'qualite'=> 'Mr',
                    'sexe'=> $enseignant->sexe,
                    'grade'=> $enseignant->idGrade,
                    'type'=> 'interne',
                    'matricule'=> $enseignant->matricule,
                ]);
            }
        }
        $grades = DB::connection(session::get('gestjury_database'))->table('grade')->get();
        return view('admin.membre-jury.create')->with([
            'grades'=>$grades,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        
        $requestData = $request->all();
        $already_exist = DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where([
                ['nom', '=', $requestData['nom']],
                ['prenoms', '=', $requestData['prenoms']],
            ])->exists();
        $already_exist2 = DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where([
                ['email', '=', $requestData['email']],
            ])->exists();
        if ($already_exist || $already_exist2) {
            return redirect('admin/membre-jury')->with('error_message', 'Un membre de jury avec ces informations existe déjà !');
        }
        DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')->insert([
            'nom' => $requestData['nom'], 
            'prenoms'=> $requestData['prenoms'],
            'email'=> $requestData['email'],
            'phone'=> $requestData['phone'],
            'description'=> $requestData['description'],
            'qualite'=> $requestData['qualite'],
            'sexe'=> $requestData['sexe'],
            'grade'=> $requestData['id_grade'],
            'type'=> 'externe',
            // 'matricule'=> $requestData['matricule'],
        ]);
        return redirect('admin/membre-jury')->with('success', 'Membre de jury créé!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $membrejury = MembreJury::findOrFail($id);

        return view('admin.membre-jury.show', compact('membrejury'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $membrejury = MembreJury::findOrFail($id);
        $grades = DB::connection(session::get('gestjury_database'))->table('grade')->get();
        return view('admin.membre-jury.edit', compact('membrejury'))->with([
            'grades'=>$grades,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(Request $request, $id)
    {
        $requestData = $request->all();
        $membrejury = MembreJury::findOrFail($id);
        //dd($membrejury->type);
        $already_exist = DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where([
                ['nom', '=', $requestData['nom']],
                ['prenoms', '=', $requestData['prenoms']],
                ['id', '!=', $id]
            ])->exists();
        $already_exist2 = DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where([
                ['email', '=', $requestData['email']],
                ['id', '!=', $id]
            ])->exists(); // || $already_exist2
        if ($already_exist) {
            return redirect('admin/membre-jury')->with('error_message', 'Un membre de jury avec ces informations existe déjà !');
        }
        if($membrejury->type =='interne') {
            DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where(['id'=> $membrejury->id])
            ->update([
                'description'=> $requestData['description']
            ]);
        }else{
            DB::connection(session::get('gestjury_database'))->table('gestjury_membre_jury')
            ->where(['id'=> $membrejury->id])
            ->update([
                'nom' => $requestData['nom'], 
                'prenoms'=> $requestData['prenoms'],
                'email'=> $requestData['email'],
                'phone'=> $requestData['phone'],
                'description'=> $requestData['description'],
                'qualite'=> $requestData['qualite'],
                'sexe'=> $requestData['sexe'],
                'grade'=> $requestData['id_grade'],
                'type'=> 'externe',
                // 'matricule'=> $requestData['matricule'],
            ]);
        }
        $membrejury->update($requestData);
        return redirect('admin/membre-jury')->with('flash_message', 'MembreJury modifié!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        MembreJury::destroy($id);

        return redirect('admin/membre-jury')->with('flash_message', 'MembreJury supprimé!');
    }
}
