<?php

namespace App\Http\Controllers;

use App\Models\Serie;
use App\Models\Level;
use App\Models\Amount;
use App\Models\Setting;
use App\Models\Scolarity;
use App\Models\SchoolYear;
use Illuminate\Http\Request;

class ScolarityController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        try{
            $data = Setting::where('school_id', auth()->user()->school_id)->first();
            return view('pages.scolarity.index',[
                'data' => $this->typeEnseignement($data),
                'year' => $this->yearActif()
            ]);                 
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {
        $id = getIdLevel($request['type']);
        if(sizeof($id) != 1){
            $dts = Level::where('type_enseignement_id', $id[0])->orWhere('type_enseignement_id', $id[1])->where('status', '1')->get();
        }
        else{
            $dts = Level::where('type_enseignement_id', $id[0])->where('status', '1')->orderBy('id')->get();
        }
        return response()->json($dts);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try{
            $val = $request->validate([
                'type' => 'required|string',
                'amount' => 'required|string',
                'year' => 'required|integer',
                'statut' => 'required|string',
                'level' => 'nullable|integer',
                'serie' => 'nullable|integer'
            ]);
            $type = changeVal($val['type']);
            if(!$this->verifyScolarity($type, $val['year'], $val['statut'], $val['level'], $val['serie'])){
                $this->verifyAmount($val['amount']) ? 
                Scolarity::create([
                    'type' => $type,
                    'niveau' => $val['level'] ? '0':'1',
                    'serie' => $val['serie'] ? '0':'1',
                    'amount_id' => $this->verifyAmount($val['amount']),
                    'school_id' => auth()->user()->school_id,
                    'school_year_id' => $val['year'],
                    'level_id' => $val['level'] ?? null,
                    'serie_id' => $val['serie'] ?? null,
                ]):null; 
                return back()->with([
                    'lib' => $val['type'],
                    'str' => $this->verifyAmount($val['amount']) ? 'success':'danger',
                    'msg' => $this->verifyAmount($val['amount']) ? 'Enregistrement effectué.':'Une erreur est survenue.'
                ]);
            }
            else{
                return back()->with([
                    'lib' => $val['type'],
                    'str' => 'warning',
                    'msg' => 'Erreur, tentative de duplication !'
                ]);
            }
        }
        catch (\Exception $e) {
            return back()->with([
                'lib' => $val['type'],
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request)
    {
        $item = changeVal($request['type']);
        if($item == 'superieur'){
            $dts = Serie::where('type', $item)->get();
        }
        else{
            $dts = Serie::where('type', $item)->where(strtolower($request['level']), '1')->get();
        }
        return response()->json($dts);
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id)
    {
        try{
            $data = Scolarity::where('id', $id)->where('school_year_id', $this->yearActif()->id)->delete();
            return back()->with([
                'lib' => $request['type'],
                'str' => 'info',
                'msg' => 'Suppression effectuée avec succès !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'lib' => $request['type'],
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }


    protected function typeEnseignement($dts)
    {
        $tab = []; $i = 0; $primaire = 0; $cycle = 0;
        $school = auth()->user()->school_id;
        $year = $this->yearActif();
        $data = [1 => 'realtime-reorder', 2 => 'basic-col-reorder', 3 => 'saving-reorder', 4 => 'predefine-reorder', 5 => null];
        foreach ($dts->school->typeEnseignements as $item) {
            if(!$primaire && ($item['id'] == 1 || $item['id'] == 2)){
                $tab[] = [
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'libelle' => verifyPrimaire($dts->school->typeEnseignements),
                    'data' => Scolarity::where('type', 'primaire')->where('school_year_id', $year->id)->where('school_id', auth()->user()->school_id)->orderBy('level_id')->get()
                ];$primaire++;
            }
            elseif(!$cycle && ($item['id'] == 3 || $item['id'] == 4)){
                $tab[] = [
                    'nbre' => $i+=1,
                    'tab' => $data[$i], 
                    'libelle' => verifySeconde($dts->school->typeEnseignements),
                    'data' => Scolarity::where('type', 'secondaire')->where('school_year_id', $year->id)->where('school_id', auth()->user()->school_id)->orderBy('level_id')->get()
                ];$cycle++;
            }
            elseif($item['id'] == 5){
                $val = $item['type_enseignement'];
                $tab[] =[
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'libelle' => $val,
                    'data' => Scolarity::where('type', 'technique')->where('school_year_id', $year->id)->where('school_id', auth()->user()->school_id)->orderBy('level_id')->get()
                ];
            }
            elseif($item['id'] == 6){
                $val = $item['type_enseignement'];
                $tab[] =[
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'libelle' => $val,
                    'data' => Scolarity::where('type', 'superieur')->where('school_year_id', $year->id)->where('school_id', auth()->user()->school_id)->orderBy('level_id')->get()
                ];
            }
        }
        return $tab;
    }


    protected function verifyAmount($val)
    {
        $item = str_replace(' ', '', $val);
        $exist = Amount::where('montant', $item)->first();
        if(!$exist){
            $exist = Amount::create(['montant' => $item]);
        }
        return $exist->id ?? null;
    }


    protected function verifyScolarity($type, $year, $item, $level = null, $serie = null)
    {
        $count = Scolarity::where('type', $type)->where('niveau', '1')->where('serie', '1')->where('school_year_id', $year)->where('school_id', auth()->user()->school_id)->count();
        if(!$count){
            if($item == 'oui'){
                $count = Scolarity::where('type', $type)->where('school_year_id', $year)->where('school_id', auth()->user()->school_id)->count();
            }
            else{
                $count = Scolarity::where('type', $type)->where('level_id', $level)->where('serie_id', $serie)->where('school_year_id', $year)->where('school_id', auth()->user()->school_id)->count();
            }
        }
        return $count;
    }


    protected function yearActif(){
        $dts = SchoolYear::where('status', '1')->first();
        return $dts;
    }
}
