<?php

namespace App\Http\Controllers;

use App\Models\Matter;
use App\Models\Setting;
use App\Models\LevelMatter;
use App\Models\LibelleBilan;
use App\Models\SchoolMatter;
use App\Models\PrimaryMatter;
use App\Models\LibelleBilanMatter;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class MatterController 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.matters.index',[
                'type' => $this->tryEnseignement($data)
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(string $val)
    {
        try{
            $data = Setting::where('school_id',auth()->user()->school_id)->first();
            $bilan = LibelleBilan::where('type', in_array($val, ['Collège - Lycée','Lycée','Collège']) ? 'generale':$val)->get();
            $matters = in_array($val, ['Collège - Lycée','Lycée','Collège']) ? $this->getMatters($data->musique_aplastique):[];
            return view('pages.matters.create', [
                'valeur' => $val,
                'matters' => $matters,
                'bilans' => $bilan,
                'libelle' => in_array($val, ['Collège - Lycée','Lycée','Collège']) ? 'Bilan':'Formation'
            ]);
        }
        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)
    {
        try{
            $matter = $request['name'];
            $abrege = $request['abrege'];
            $bilan = $request['bilan'];
            $valInit = $request['type'];
            $request['type'] = changeVal($request['type']);
            $validated = $request->validate([
                'type' => 'required|string',
            ]);
            if(count($matter) > 0){
                // $this->deleteData(auth()->user()->school_id); // Delete data
                if(in_array($request['type'], ['secondaire', 'technique'])){
                    $this->saveConduiteSchool(15, $request['type']); // id conduite = 15
                }
                for($i = 0; $i < sizeof($matter); $i++){
                    if($matter[$i] && !($this->verifyMatterSchool($this->existeData($matter[$i],$abrege[$i]), $validated['type']))){
                        SchoolMatter::create([
                            'school_id' => auth()->user()->school_id,
                            'matter_id' => $this->existeData($matter[$i],$abrege[$i]),
                            'type' => $validated['type'],
                        ]);
                        $verify = LibelleBilanMatter::where('libelle_bilan_id', $bilan[$i])->where('matter_id', $this->existeData($matter[$i],$abrege[$i]))->where('type', $validated['type'])->count();
                        if(!$verify){
                            LibelleBilanMatter::create([
                                'libelle_bilan_id' => $bilan[$i],
                                'matter_id' => $this->existeData($matter[$i],$abrege[$i]),
                                'type' => $validated['type'],
                                'bilan' => $this->incrementValeurBilan($bilan[$i], $validated['type'])
                            ]);
                        }
                    }
                }
                return redirect()->route('matiere.index')->with([
                    'str' => 'success',
                    'msg' => 'Matière ajoutée '.$valInit,
                    'string' => $valInit
                ]);
            }
            else{
                return back()->with([
                    'str' => 'danger',
                    'msg' => 'Une erreur est survenue !'
                ]);
            }
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function matter(Request $request, $id)
    {
        try{
            $validated = $request->validate([
                'name' => 'required|string',
                'abrege' => 'nullable|string',
            ]);
            $matter = Matter::where('id', $id)->where('status', '1')->first();
            if($matter){
                $matter->update([
                    'libelle' => $validated['name'],
                    'abbreviated' => $validated['abrege'] ?? '---'
                ]);
            }
            return redirect()->route('matiere.index')->with([
                'str' => 'info',
                'msg' => 'Discipline mise à jour !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        try{
            $val = $request->validate([
                'matter' => 'required|string',
                'libelle' => 'required|string',
            ]);
            $dt = SchoolMatter::where('matter_id', $val['matter'])->where('school_id', auth()->user()->school_id)->where('type', changeVal($val['libelle']))->first();
            if($dt){
                $dt->delete();
                LevelMatter::where('matter_id', $val['matter'])->where('school_id', auth()->user()->school_id)->where('type', changeVal($val['libelle']))->delete();
            }
            return redirect()->route('matiere.index')->with([
                'str' => 'info',
                'msg' => 'Discipline désactivée !'
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue !'
            ]);
        }
    }

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


    protected function incrementValeurBilan($bilan, $type){
        $val = LibelleBilanMatter::where('libelle_bilan_id', $bilan)->where('type', $type)->max('bilan');
        return $val ? ++$val:1;
    }

    /**
     * Remove the specified resource from storage.
     */
    protected function existeData($name,$abrege){
        $data = Matter::where('libelle', $name)->orWhere('abbreviated', $abrege)->first();
        if(!$data){
            $data = Matter::create([
                'libelle' => $name,
                'abbreviated' => $abrege ?? null,
            ]);
        }
        return $data['id']; 
    }

    /**
     * Remove the specified resource from storage.
     */
    protected function tryEnseignement($dts){
        $tab = []; $i = 0; $primaire = 0; $cycle = 0;
        $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], 
                    'id' => $item['id'],
                    'libelle' => verifyPrimaire($dts->school->typeEnseignements),
                    'data' => PrimaryMatter::orderBy('libelle', 'ASC')->get()
                ];$primaire++;
            }
            elseif(!$cycle && ($item['id'] == 3 || $item['id'] == 4)){
                $tab[] = [
                    'nbre' => $i+=1,
                    'tab' => $data[$i], 
                    'id' => $item['id'],
                    'libelle' => verifySeconde($dts->school->typeEnseignements),
                    'data' => $this->schoolMatterLevel('secondaire')
                ]; $cycle++;
            }
            elseif($item['id'] == 5 || $item['id'] == 6){
                $val = $item['type_enseignement'];
                $tab[] =[
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'id' => $item['id'],
                    'libelle' => $val,
                    'data' => $this->schoolMatterLevel($val)
                ];
            }
        }
        return $tab;
    }


    protected function saveConduiteSchool($matter, $type)
    {
        $verify = SchoolMatter::where('school_id', auth()->user()->school_id)->where('matter_id', $matter)->where('type', $type,)->count();
        if(!$verify){
            SchoolMatter::create([
                'school_id' => auth()->user()->school_id,
                'matter_id' => $matter,
                'type' => $type,
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    protected function verifyMatterSchool($matter, $type)
    {
        $exist = SchoolMatter::where('school_id', auth()->user()->school_id)->where('matter_id', $matter)->where('type', $type)->count();
        return $exist ?? 0;
    }


    protected function schoolMatterLevel($val){
        $matters =  DB::table('matters')
        ->join('school_matter', 'matters.id', '=', 'school_matter.matter_id')
        ->select('matters.id', 'matters.libelle', 'matters.abbreviated', 'school_matter.matter_id')
        ->where('school_matter.school_id', '=', auth()->user()->school_id)
        ->where('school_matter.type', '=', $val)
        ->where('school_matter.status', '=', '1')
        ->orderBy('matters.libelle')
        ->get();

        return $matters;
    }


    protected function getMatters($val)
    {
        $matters =  DB::table('matters')
        ->join('libelle_bilan_matter', 'matters.id', '=', 'libelle_bilan_matter.matter_id')
        ->select('matters.id', 'matters.libelle', 'matters.abbreviated', 'libelle_bilan_matter.libelle_bilan_id')
        ->where('matters.libelle', '!=', 'Mixte')
        ->orderBy('matters.libelle')
        ->get(); 
        if(!$val){
            $matters = $matters->where('libelle', '!=', 'Arts plastique')->where('libelle', '!=', 'Musique');
        }

        return $matters;
    }
}