<?php

namespace App\Http\Controllers;

use App\Models\Zone;
use App\Models\Amount;
use App\Models\Setting;
use App\Models\Transport;
use App\Models\SchoolZone;
use App\Models\SchoolYear;
use Illuminate\Http\Request;

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        try{
            $data = SchoolZone::where('school_id', auth()->user()->school_id)->where('status', '1')->get();
            return view('pages.transport.create',[
                'data' => $data
            ]);
        }
        catch (\Exception $e) {
            return back()->with([
                'str' => 'danger',
                'msg' => 'Une erreur est survenue.'
            ]);
        }
    }


    public function addZone(Request $request)
    {
        try{
            $val = $request->validate([
                'libelle' => 'required|string'
            ]);
            $zone = $this->verifyZone($val['libelle']);
            
            if($zone && !$this->verifySchoolZone($zone)){
                SchoolZone::create([
                    'zone_id' => $zone,
                    'school_id' => auth()->user()->school_id
                ]);
                return back()->with([
                    'str' => 'success',
                    'msg' => 'Zone enregistrée avec succes.'
                ]); 
            }
            else{
               return back()->with([
                    'str' => 'danger',
                    'msg' => 'Erreur, tentative de duplication'
                ]); 
            }
        }
        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{
            $val = $request->validate([
                'type' => 'required|string',
                'year' => 'required|string',
                'zone' => 'required|string',
                'amount' => 'required|string',
            ]);
            $type = changeVal($val['type']);
            $last = Transport::where('type', $type)->where('school_year_id', $val['year'])->latest('id')->first();
            if(!$this->verifyGetZone($type, $val['zone'], $val['year'])){
                $amount = $this->verifyAmount($val['amount']);
                $nbre = $last ? explode(' ',$last['libelle'])[1]+1:1;
                $amount ? 
                Transport::create([
                    'type' => $type,
                    'libelle' => 'zone '.$nbre,
                    'amount_id' => $amount,
                    'school_zone_id' => $val['zone'],
                    '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.'
            ]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request)
    {
        try{
            $val = $request->validate([
                'id' => 'required|string',
                'amount' => 'required|string'
            ]);
            $result = Transport::find($val['id']);
            if($result){
                $amount = $this->verifyAmount($val['amount']);
                $result->update(['amount_id' => $amount]);
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Mis à jour éffectué.'
                ]);
            }
            else{
                return back()->with([
                    'str' => 'danger',
                    'msg' => 'Une erreur est survenue.'
                ]);
            }
        }
        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'
            ]);
            $result = Transport::find($val['id']);
            if($result){
                $result->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Zone supprimé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.'
            ]);
        }
    }


    public function delete(Request $request)
    {
        try{
            $val = $request->validate([
                'id' => 'required|string'
            ]);
            $result = SchoolZone::find($val['id']);
            if($result){
                $result->delete();
                return back()->with([
                    'str' => 'info',
                    'msg' => 'Zone supprimé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 verifyZone($valeur)
    {
        $exist = Zone::where('libelle', strtolower($valeur))->first();
        if(!$exist){
            $exist = Zone::create(['libelle' => strtolower($valeur)]);
        }
        return $exist ? $exist->id:null;
    }


    protected function verifySchoolZone($zone)
    {
        $exist = SchoolZone::where('school_id', auth()->user()->school_id)->where('zone_id', $zone)->count();
        return $exist;
    }


    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 verifyGetZone($type, $zone, $year)
    {
        $result = Transport::where('type', $type)->where('school_zone_id', $zone)->where('school_year_id', $year)->count();
        return $result;
    }


    protected function typeEnseignement($dts)
    {
        $tab = []; $i = 0; $primaire = 0; $cycle = 0;
        $school = auth()->user()->school_id;
        $year = $this->yearActif();
        $data = [1 => 'myTable1', 2 => 'myTable2', 3 => 'myTable3', 4 => 'myTable4', 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' => $this->getTransport('primaire')
                ];$primaire++;
            }
            elseif(!$cycle && ($item['id'] == 3 || $item['id'] == 4)){
                $tab[] = [
                    'nbre' => $i+=1,
                    'tab' => $data[$i], 
                    'libelle' => verifySeconde($dts->school->typeEnseignements),
                    'data' => $this->getTransport('secondaire')
                ];$cycle++;
            }
            elseif($item['id'] == 5){
                $val = $item['type_enseignement'];
                $tab[] =[
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'libelle' => $val,
                    'data' => $this->getTransport($val)
                ];
            }
            elseif($item['id'] == 6){
                $val = $item['type_enseignement'];
                $tab[] =[
                    'nbre' => $i+=1, 
                    'tab' => $data[$i], 
                    'libelle' => $val,
                    'data' => $this->getTransport($val)
                ];
            }
        }
        return $tab;
    }


    protected function getTransport($type){
        $data = Transport::join('school_zones', 'school_zones.id', '=', 'transports.school_zone_id')
        ->join('zones', 'zones.id', '=', 'school_zones.zone_id')
        ->join('amounts', 'amounts.id', '=', 'transports.amount_id')
        ->where('transports.type', $type)
        ->where('school_zones.school_id', auth()->user()->school_id)
        ->where('transports.school_year_id', $this->yearActif()->id)
        ->select('transports.id', 'transports.libelle', 'zones.libelle as zone', 'amounts.montant')
        ->get();
        return $data;
    }


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