<?php

namespace App\Http\Controllers;
use App\Models\ParentEleve;
use App\Models\SchoolYear;
use Illuminate\Http\Request;

class ParentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        try{
            $parents = ParentEleve::where('school_id', auth()->user()->school_id)->orderBy('first_name')->orderBy('last_name')->get();
            return view('pages.parent.index',[
                'parents' => $parents
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'warning',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        try{
            return view('pages.parent.create', ['parent' => []]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'warning',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        if(!$request['id']){
            $validated = $request->validate([
                'phon1' => 'required|numeric|digits between:10,10|unique:parent_eleves,telephon1',
                'phon2' => 'nullable|numeric|digits between:10,10|unique:parent_eleves,telephon2',
                'firstName' => 'required|string',
                'latsName' => 'required|string',
                'sexe' => 'required|string',
                'profession' => 'required|string',
            ]);

            // Save User.
            $year = SchoolYear::where('status', '1')->first();
            $dts = ParentEleve::create([
                'first_name' => strtolower($validated['firstName']),
                'last_name' => strtolower($validated['latsName']),
                'sexe' => $validated['sexe'],
                'profession' => strtolower($validated['profession']),
                'telephon1' => $validated['phon1'],
                'telephon2' => $validated['phon2'] ?? null,
                'school_id' => auth()->user()->school_id,
                'school_year_id' => $year->id
            ]);
        }
        $val1 = $request['id'] ?? $dts['id'];
        $val2 = $request['info'] ? $request['info']:0;
        return redirect()->route('student.create',$val1.'_'.$val2)->with([
            'str' => 'info',
            'msg' => 'Ajouter les informations de l\'élève maintenant.'
        ]);;
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        try{
            $data = ParentEleve::find($id);
            return view('pages.parent.detail', ['data' => $data]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        try{
            $data = ParentEleve::find($id);
            return view('pages.parent.create', ['parent' => $data]);
        }
        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([
            'phon1' => 'required|numeric|digits between:10,10',
            'phon2' => 'nullable|numeric|digits between:10,10',
            'firstName' => 'required|string',
            'latsName' => 'required|string',
            'sexe' => 'required|string',
            'profession' => 'required|string',
            'messagerie' => 'nullable|integer',
            'status' => 'nullable|integer',
        ]);
        $parent = ParentEleve::find($id);
        $parent->update([
            'first_name' => $validated['firstName'],
            'last_name' => $validated['latsName'],
            'sexe' => $validated['sexe'],
            'profession' => $validated['profession'],
            'telephon1' => $validated['phon1'],
            'telephon2' => $validated['phon2'] ?? null,
            'messagerie' => $validated['messagerie'] ?? '0',
            'status' => $validated['status'] ?? '0'
        ]);
        return redirect()->route('student.index')->with([
            'str' => 'info',
            'msg' => 'Mise à jour effectué .'
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function search(Request $request){
        try{
            $parent = ParentEleve::where('id', $request['data'])->first();
            return response()->json($parent);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(String $id)
    {
        try{
            $parent = ParentEleve::Where('id',$id)->where('school_id', auth()->user()->school_id)->first();
            if ($parent) {
                $parent->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Parent d\'élève supprimé avec succès !'
                ]);
            } 
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }


    public function search2(Request $request){
        try{
            $data = ParentEleve::where('telephon1', $request['data'])->orWhere('telephon2', $request['data'])->where('school_id', auth()->user()->school_id)->first();
            return response()->json($data);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }
}
