<?php

namespace App\Http\Controllers;

use App\Http\Requests\SchoolRequest;
use App\Models\School;
use App\Models\User;
use App\Jobs\SendMailJob;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class SchoolController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        try{
            $school = School::where('status', '0')->get();
            return view('pages.school.detail', ['schools' => $school]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('pages.school.create', ['school' => null, 'user' => null]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(SchoolRequest $request)
    {
        // Ajoute les info concernant l'etablissamant en reccuperant son id.
        $school = School::create([
            'name_school' => $request['nameSchool'],
            'num_autorisation' => $request['numAutorastion'],
            'code_school' => $request['codeSchool'],
            'belonging' => $request['belonging']
        ]);

        // Générer un mot de passe pour l'utilisateur de 6 caractères au moins.
        // $mpd = generatePwd();
        $mpd = '000000';

        // Ajouter les info d'user en base.
        if($school->id){
            $user = User::create([
                'first_name' => strtolower($request['firstUser']),
                'last_name' => strtolower($request['lastuser']),
                'sexe' => $request['sexeUser'],
                'telephon' => $request['numPhon'],
                'email' => $request['emailUser'],
                'role_id' => 2,
                'school_id' => $school->id,
                'password' => Hash::make($mpd),
                'remember_token' => Str::random(10),
            ]);
        }
        
        $url = explode("user", url()->previous())[0].'login';
        dispatch(new SendMailJob($user, $mpd, $url));

        // Redirection sur la liste des établissement
        return redirect()->route('dashboard')->with([
            'str' => 'success',
            'msg' => 'Enrégistrement effectué avec success !'
        ]);
    }

    

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        try{
            $school = School::findOrFail($id);
            $user = User::where('school_id', $id)->where('role_id', '2')->first();
            return view('pages.school.create',['school' => $school, 'user' => $user]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'nameSchool' => 'required|string|max:100',
            'numAutorastion' => 'required|string',
            'codeSchool' => 'required|string',
            'firstUser' => 'required|string|min:3',
            'lastuser' => 'required|string',
            'emailUser' => 'required|email',
            'numPhon' => 'required|numeric',
        ]);

        // Trouver school à mettre à jour
        $school = School::findOrFail($id);
        $user = User::where('school_id', $id)->where('role_id', '2')->first();

        // Mettre à jour les informations school
        $school->update([
            'name_school' => $validated['nameSchool'],
            'num_autorisation' => $validated['numAutorastion'],
            'code_school' => $validated['codeSchool'],
            'belonging' => $request['belonging'],
            'status' => $request['status'] ? '1':'0'
        ]);

        $user->update([
            'first_name' => strtolower($validated['firstUser']),
            'last_name' => strtolower($validated['lastuser']),
            'telephon' => $validated['numPhon'],
            'email' => $validated['emailUser'],
        ]);
        
        return redirect()->route('dashboard')->with([
            'str' => 'info',
            'msg' => 'Mis à jour effectué avec succès'
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try{
            $school = School::find($id);
            if ($school) {
                $school->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Etablissement supprimé avec succès !'
                ]);
            } 
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'warning',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

}
