<?php

namespace App\Http\Controllers;

use App\Models\ParentEleve;
use App\Models\SchoolYear;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

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.'
            ]);
        }
    }


    public function dataTable(){
        $query = ParentEleve::where('school_id', auth()->user()->school_id)->orderBy('first_name')->orderBy('last_name')->get();
        $counter = 0;
        return DataTables::of($query)
        ->addColumn('counter', function() use (&$counter) {
            return ('<p class="m-0 pt-2">'.($counter < 9 ? '0'.++$counter : ++$counter).'</p>');
        })
        ->addColumn('firstName', function ($row) {
            return ('<p class="m-0 pt-2">'.strtoupper($row->first_name).'</p>');
        })
        ->addColumn('lastName', function ($row) {
            return ('<p class="m-0 pt-2">'.ucwords($row->last_name).'</p>');
        })
        ->addColumn('sexe', function ($row) {
            return ('<p class="m-0 pt-2">'.ucwords($row->sexe == 'F' ? 'Femme':'Homme').'</p>');
        })
        ->addColumn('profession', function ($row) {
            return ('<p class="m-0 pt-2">'.ucwords($row->profession).'</p>');
        })
        ->addColumn('telephon', function ($row) {
            return ('<p class="m-0 pt-2">'.ucwords($row->telephon1).'</p>');
        })
        ->addColumn('nombre', function ($row) {
            return ('<p class="m-0 pt-2">'.(count($row->students) <= 9 ? '0'.count($row->students):count($row->students)).'</p>');
        })
        ->addColumn('message', function ($row) {
            return ('<p class="m-0 pt-2">'.($row->messagerie ? 'Oui':'non').'</p>');
        })
        ->addColumn('action', function ($row) {
            $url_1 = route('parent.show',$row->id); $url_2 = route('parent.edit',$row->id);
            return ('<span class="card-block remove-label m-0 text-center">
                <a href="'.$url_1.'" class="btn btn-inverse btn-outline-inverse btn-icons mr-1" title="Detail"><i class="fas fa-eye m-0"></i></a>
                <a href="'.$url_2.'" class="btn btn-inverse btn-outline-inverse btn-icons mr-1" title="Edit"><i class="fas fa-edit m-0"></i></a>
                <button class="btn btn-inverse btn-outline-inverse btn-icons deleteBtn pb-2" data-id="'.$row->id.'"><i class="far fa-trash-alt"></i></button>
            </span>');
        })
        ->rawColumns(['counter', 'firstName', 'lastName', 'sexe', 'profession', 'telephon', 'nombre', 'message', 'action'])
        ->make(true);
    }

    /**
     * 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{
            $dts = ParentEleve::where('id', $request['id'])->first();
            $data = [
                'id' => strtoupper($dts->id),
                'first' => strtoupper($dts->first_name),
                'last' => ucwords($dts->last_name),
                'created' => date('d/m/Y', strtotime($dts->created_at)),
                'nombre' => (count($dts->students) <= 9 ? '0'.count($dts->students):count($dts->students))
            ];
            return response()->json($data);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        try{
            $val = $request->validate([
                'id' => 'required|string'
            ]);
            $parent = ParentEleve::Where('id', $val['id'])->where('school_id', auth()->user()->school_id)->first();
            if ($parent) {
                $parent->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Suppression effectuée avec succes.'
                ]);
            } 
        }
        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 !'
            ]);
        }
    }
}
