<?php

namespace App\Http\Controllers;
use App\Models\CuttingSchoolYear;
use App\Models\TypeEnseignement;
use App\Models\SchoolYear;
use App\Models\Cutting;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DecoupageControlle extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(string $item)
    {
        try{
            $year = SchoolYear::where('status', '1')->first();
            $datas = CuttingSchoolYear::where('school_year_id', $year ['id'])->where('type', $item)->get();
            return view('pages.decoupage.index',[
                'datas' => $datas,
                'item' => $item,
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create($item)
    {
        try{
            $year = SchoolYear::where('status', '1')->first();
            $decoup = $item == 'general' ? $year['decoupage']:'semestre';
            $cutting = Cutting::where('libelle', 'like', $decoup.'%')->orderBy('libelle')->get();
            return view('pages.decoupage.create',[
                'data' => $cutting,
                'item' => $item,
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, string $item)
    {
        try{
            // Vérifie que les informations sont correctes
            for($i = 0; $i < count($request['decoupage']); $i++){
                if(!(strtotime($request['dateDebut'][$i]) < strtotime($request['dateFin'][$i]))){
                    return back()->with([
                        'str' => 'danger',
                        'msg' => 'Les informations ne sont pas correctes !'
                    ]);
                }
            }

            // Sauvegarde des données en base ...........................
            $year = SchoolYear::where('status', '1')->first();
            $curentDate = Carbon::now()->format('d-m-Y');
            $i = 0;
            while($i < count($request['decoupage'])){
                CuttingSchoolYear::create([
                    'school_year_id' => $year['id'],
                    'type' => $request['type'],
                    'cutting_id' => $request['decoupage'][$i],
                    'start_date' => $request['dateDebut'][$i],
                    'end_date' => $request['dateFin'][$i],
                    'status' => verifyDateDecoupage($request['dateDebut'][$i], $request['dateFin'][$i], $curentDate)
                ]);
                $i++; 
            }

            return redirect()->route('decoupage.index', $item)->with([
                'str' => 'success',
                'msg' => 'Enregistrement effectué avec succes !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $item, $id)
    {
        try{
            $year = SchoolYear::where('status', '1')->first();
            $datas = CuttingSchoolYear::where('cutting_id', $id)->where('school_year_id', $year['id'])->get();
            return view('pages.decoupage.create',[
                'data' => $datas,
                'item' => $item,
            ]);
            
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $item, $id)
    {
        try{
            $validated = $request->validate([
                'decoupage' => 'required|integer',
                'dateDebut' => 'required|date',
                'dateFin' => 'required|date',
            ]);

            $curentDate = Carbon::now()->format('d-m-Y');
            $status = verifyDateDecoupage($validated['dateDebut'], $validated['dateFin'], $curentDate);
            $year = SchoolYear::where('status', '1')->first();

            if($status == 1){
                $data = CuttingSchoolYear::where('status', '1')->where('school_year_id', $year['id'])->first();
                if($data){
                    $val = verifyDateDecoupage($data['start_date'], $data['end_date'], $curentDate);
                    CuttingSchoolYear::where('status', '1')->where('school_year_id', $year['id'])->update([
                        'status' => $val == 1 ? '0':$val
                    ]);
                }
            }

            // Fait les mis à jours sur le decoupage choisi .............
            $data = CuttingSchoolYear::where('cutting_id', $id)->where('school_year_id', $year['id'])->first();
            if($data){
                CuttingSchoolYear::where('cutting_id', $id)->where('school_year_id', $year['id'])->update([
                    'start_date' => $validated['dateDebut'],
                    'end_date' => $validated['dateFin'],
                    'status' => $status
                ]);
            }

            return redirect()->route('decoupage.index', $item)->with([
                'str' => 'info',
                'msg' => 'Mis à jour effectué avec succes !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $item,$id)
    {
        try{
            $year = SchoolYear::where('status', '1')->first();
            if($id && $year){
                CuttingSchoolYear::where('cutting_id', $id)->where('school_year_id', $year['id'])->delete(); 
            }
            return redirect()->route('decoupage.index', $item)->with([
                'str' => 'info',
                'msg' => 'Suppression effectuée !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }
}
