<?php

namespace App\Listeners;

use App\Models\Classe;
use App\Models\Payment;
use App\Models\AnnexFee;
use App\Models\Scolarity;
use App\Events\PaymentGetEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class PaymentGetListener
{

    public function handle(PaymentGetEvent $event): void
    {
        $class = $this->getClass($event->classe);
        if(!$this->verifyPayment($event->inscription, $class['type'], $event->year, $event->school)){
            $annexFee = $this->annexFee($class['type'], $event->year, $event->school, $class['level_id'], $class['serie_id']);
            $scolarity = $this->scolarity($class['type'], $event->year, $event->school, $class['level_id'], $class['serie_id']);
            ($annexFee && $scolarity) ? 
            $this->savePayment($class['type'], $event->school, $annexFee, $event->year, $event->inscription, $scolarity) :
            null;
        }
    }


    protected function getClass($id){
        $classe = Classe::find($id);
        return $classe;
    }


    protected function annexFee($type, $year, $school, $level = null, $serie = null){
        $val = AnnexFee::where('type', $type)->where('niveau', '1')->where('serie', '1')->where('school_year_id', $year)->where('school_id', $school)->first();
        if(!$val){
            $val = AnnexFee::where('type', $type)->where('level_id', $level)->where('serie_id', $serie)->where('school_year_id', $year)->where('school_id', $school)->first();
        }
        return $val ? $val->id : null;
    }


    protected function scolarity($type, $year, $school, $level = null, $serie = null){
        $val = Scolarity::where('type', $type)->where('niveau', '1')->where('serie', '1')->where('school_year_id', $year)->where('school_id', $school)->first();
        if(!$val){
            $val = Scolarity::where('type', $type)->where('level_id', $level)->where('serie_id', $serie)->where('school_year_id', $year)->where('school_id', $school)->first();
        }
        return $val ? $val->id : null;
    }


    protected function verifyPayment($inscription, $type, $year, $school){
        $count = Payment::where('inscription_id', $inscription)->where('type', $type)->where('school_year_id', $year)->where('school_id', $school)->count();
        return $count ?? null;
    }


    protected function savePayment($type, $school, $annexFee, $year, $inscription, $scolarity){
        Payment::create([
            'type' => $type,
            'school_id' => $school,
            'school_year_id' => $year,
            'annex_fee_id' => $annexFee,
            'scolaritie_id' => $scolarity,
            'inscription_id' => $inscription
        ]);
    }
}
