<?php

namespace App\Http\Controllers;

use App\Models\Amount;
use App\Models\Canteen;
use App\Models\Setting;
use App\Models\SchoolYear;
use Illuminate\Http\Request;

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try{
            $val = $request->validate([
                'year' => 'required|string', 
                'amount' => 'required|string',
                'type' => 'required|array'
            ]);

            if(!$this->verifyCanteen($val['type'], $val['year'])){
                $amount = $this->verifyAmount($val['amount']);
                $amount ? 
                Canteen::create([
                    'primaire' => in_array('primaire', $val['type']) ? '1':'0',
                    'secondaire' => in_array('secondaire', $val['type']) ? '1':'0',
                    'technique' => in_array('technique', $val['type']) ? '1':'0',
                    'superieur' => in_array('superieur', $val['type']) ? '1':'0',
                    'amount_id' => $amount,
                    'school_id' => auth()->user()->school_id,
                    'school_year_id' => $val['year']
                ]):null; 
                return back()->with([
                    'lib' => $val['type'],
                    'str' => $amount ? 'success':'danger',
                    'msg' => $amount ? 'Enregistrement effectué.':'Une erreur est survenue.'
                ]);
            }
            else{
                return back()->with([
                    'str' => 'danger',
                    'msg' => 'Erreur, tentative de duplication !'
                ]); 
            }
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        try{
            $val = $request->validate([
                'id' => 'required|string'
            ]);
            $result = Canteen::find($val['id']);
            if($result){
                $result->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Suppression éffectuée !'
                ]);
            }
            else{
                return back()->with([
                    'str' => 'danger',
                    'msg' => 'Une erreur est survenue.'
                ]);
            }
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }



    protected function typeEnseignement($dts)
    {
        $tab = []; $i = 0; $primaire = 0; $cycle = 0;
        foreach ($dts->school->typeEnseignements as $item) {
            if(!$primaire && ($item['id'] == 1 || $item['id'] == 2)){
                $tab[] = ['libelle' => verifyPrimaire($dts->school->typeEnseignements),];$primaire++;
            }
            elseif(!$cycle && ($item['id'] == 3 || $item['id'] == 4)){
                $tab[] = ['libelle' => verifySeconde($dts->school->typeEnseignements)];$cycle++;
            }
            elseif($item['id'] == 5 || $item['id'] == 6){
                $tab[] =['libelle' => $item['type_enseignement']];
            }
        }
        return $tab;
    }


    protected function verifyCanteen($table, $year)
    {
        $i = 0;
        foreach($table as $item){
            $i = Canteen::where($item, '1')->where('school_id', auth()->user()->school_id)->where('school_year_id', $year)->first() ? $i+1:$i;
        }
        return $i;
    }


    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 yearActif(){
        $dts = SchoolYear::where('status', '1')->first();
        return $dts;
    }
}
