<?php

namespace App\Http\Livewire;
use App\Http\Middleware\TenantMiddleware;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
class Course extends Component
{

    protected $listeners = ['setCausal' => 'setCausal', 'setSubscriptionCausal' => 'setSubscriptionCausal'];

    public $records, $parent_id, $name, $enabled, $dataId, $update = false, $add = false;
    public $course_type_id,
        $course_duration_id,
        $course_frequency_id,
        $course_level_id,
        $causal_id,
        $category_id,
        $sub_causal_id,
        $max_members,
        $instructor_id,
        $year,
        $price,
        $subscription_price,
        $months,
        $when,
        $prices,
        $type,
        $date_from, $date_to;

    public $categories = array();

    public $selectedYear = '';

    public $msgPrices = '';
    public $msgWhen = '';

    public $course_types = [];
    public $course_durations = [];
    public $course_frequencies = [];
    public $course_levels = [];
    public $course_subscriptions = [];
    public $instructors = [];
    public $causals = [];

    public $course_years = [];

    public $monthList = [];

    public $typeIN = 'IN';
    public $setSubscriptionCausal = 'setSubscriptionCausal';

    // public $selectedMonthList = [];

    protected $rules = [
        'name' => 'required',
        'course_frequency_id' => 'required',
        'course_level_id' => 'required',
        'date_from' => 'required',
        'date_to' => 'required',
        'year' => 'required',
        'subscription_price' => 'required|min:0|not_in:0',
        /*'course_type_id' => 'required',
        'course_duration_id' => 'required',

        'causal_id' => 'required',
        'sub_causal_id' => 'required',*/
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'subscription_price.required' => 'Deve essere maggionre di zero',
        'subscription_price.not_in' => 'Deve essere maggionre di zero',
        /*'causal_id' => 'Campo obbligatorio',
        'sub_causal_id' => 'Campo obbligatorio',*/
    ];
    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }
    public function resetFields(){
        $this->name = '';
        $this->parent_id = null;
        $this->course_type_id = null;
        $this->course_duration_id = null;
        $this->course_frequency_id = null;
        $this->course_level_id = null;
        $this->category_id = null;
        $this->causal_id = null;
        $this->sub_causal_id = null;
        $this->max_members = 0;
        $this->instructor_id = null;
        $this->year = null;
        $this->price = 0;
        $this->subscription_price = 0;
        $this->date_from = null;
        $this->date_to = null;
        $this->months = array();
        $this->enabled = true;
        $this->type = 'standard';
        $this->when = array();
        $this->when[] = array('day' => array(), 'from' => '', 'to' => '');
        $this->prices = [];
        $this->prices[] = array('course_subscription_id' => null, 'price' => 0);
        $this->emit('load-data-table');
    }

    public function getCategories($records, $indentation)
    {
        foreach($records as $record)
        {
            // $this->categories[] = array('id' => $record->id, 'name' => str_repeat(" / ", $indentation) . $record->name);
            $this->categories[] = array('id' => $record->id, 'name' => $record->getTree(), 'indentation' => $indentation);
            if(count($record->childs))
                $this->getCategories($record->childs, $indentation + 1);
        }
    }

    public function mount(){

        if(Auth::user()->level != env('LEVEL_ADMIN', 0))
            return redirect()->to('/dashboard');

        $this->categories = array();

        $this->getCategories(\App\Models\Category::select('id', 'name')->where('parent_id', null)->get(), 0);

        for($i=date("Y"); $i<=date("Y") + 1; $i++)
        {
            $this->monthList[$i][1] = "Gennaio";
            $this->monthList[$i][2] = "Febbraio";
            $this->monthList[$i][3] = "Marzo";
            $this->monthList[$i][4] = "Aprile";
            $this->monthList[$i][5] = "Maggio";
            $this->monthList[$i][6] = "Giugno";
            $this->monthList[$i][7] = "Luglio";
            $this->monthList[$i][8] = "Agosto";
            $this->monthList[$i][9] = "Settembre";
            $this->monthList[$i][10] = "Ottobre";
            $this->monthList[$i][11] = "Novembre";
            $this->monthList[$i][12] = "Dicembre";
        }
        $this->course_types = \App\Models\CourseType::select('*')->where('enabled', true)->get();
        $this->course_durations = \App\Models\CourseDuration::select('*')->where('enabled', true)->get();
        $this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->get();
        $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->where('enabled', true)->get();
        $this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->get();
        $this->causals = \App\Models\Causal::select('*')->where('type', 'IN')->where('enabled', true)->get();
        $this->instructors = \App\Models\User::select('*')->where('level', 2)->get();

        $this->course_years = \App\Models\Course::select('year')->where('year', '<>', '')->groupBy('year')->pluck('year');

    }

    public function render()
    {
        if (isset($_GET["year"]))
            $this->selectedYear = $_GET["year"];
        else
            // $this->selectedYear =  sizeof($this->course_years) > 0 ? $this->course_years[0] : '';
            $this->selectedYear = date("Y") . "-" . (date("Y") + 1);

        $this->records = \App\Models\Course::where('parent_id', null)->where('year', $this->selectedYear)->with('type', 'duration')->get();
        return view('livewire.course');
    }

    public function add()
    {
        $this->resetFields();
        $this->add = true;
        $this->update = false;

        $this->emit('setEdit', true);
    }

    /*
    public function addLevel($parent_id)
    {
        $this->resetFields();
        $this->parent_id = $parent_id;
        $this->add = true;
        $this->update = false;
    }
    */
    public function store()
    {
        $this->validate();
        try {

            $this->msgPrices = '';
            $this->msgWhen = '';

            if ($this->type == 'standard') {
                if ($this->when[0]['from'] == '')
                    $this->msgWhen = 'Devi inserire almeno un giorno';
            }
    
            if ($this->prices[0]['course_subscription_id'] == null)
                $this->msgPrices = 'Devi inserire almeno un prezzo';
            
            $subscriptions = array_column($this->prices, 'course_subscription_id');
            $unique_subscriptions = array_unique($subscriptions);
            if (count($subscriptions) != count($unique_subscriptions))
                $this->msgPrices = 'È possibile aggiungere solo un abbonamento per ciascun tipo';

            if ($this->msgPrices == '' &&  $this->msgWhen == '')
            {

                $course = new \App\Models\Course();

                $course->name = $this->name;
                $course->parent_id = $this->parent_id;
                $course->course_type_id = $this->course_type_id;
                $course->course_duration_id = $this->course_duration_id;
                $course->course_frequency_id = $this->course_frequency_id;
                $course->course_level_id = $this->course_level_id;
                $course->date_from = $this->date_from;
                $course->date_to = $this->date_to;
                $course->category_id = $this->category_id;
                $course->causal_id = $this->causal_id;
                $course->sub_causal_id = $this->sub_causal_id;
                $course->max_members = $this->max_members;
                $course->instructor_id = $this->instructor_id;
                $course->year = $this->year;
                $course->price = currencyToDouble($this->price);
                $course->subscription_price = currencyToDouble($this->subscription_price);
                $course->months = json_encode($this->months);
                $course->type = $this->type;
                $course->when = json_encode($this->when);
                $course->prices = json_encode($this->prices);
                $course->enabled = $this->enabled;
                $course->save();

                $lev = '';
                if ($this->course_level_id > 0)
                    $lev = \App\Models\CourseLevel::findOrFail($this->course_level_id)->name;

                $freq = '';
                if ($this->course_frequency_id > 0)
                    $freq = \App\Models\CourseFrequency::findOrFail($this->course_frequency_id)->name;

                $mFrom = getMonthName(date("n", strtotime($this->date_from)));
                $mTo = getMonthName(date("n", strtotime($this->date_to)));

                $course_name = $course->name;

                // creo il calendario
                $from = date("Y-m-d", strtotime($this->date_from));
                $to = date("Y-m-d", strtotime($this->date_to));

                $endDate = strtotime($to);

                foreach($this->when as $d)
                {

                    foreach($d["day"] as $dd)
                    {

                        $day = '';
                        switch ($dd) {
                            case 'lun':
                                $day = $days[0];
                                break;
                            case 'mar':
                                $day = $days[1];
                                break;
                            case 'mer':
                                $day = $days[2];
                                break;
                            case 'gio':
                                $day = $days[3];
                                break;
                            case 'ven':
                                $day = $days[4];
                                break;
                            case 'sab':
                                $day = $days[5];
                                break;
                            case 'dom':
                                $day = $days[6];
                                break;
                            default:
                                $day = '';
                                break;
                        }
                        
                        if ($day != '')
                        {
                            for($i = strtotime($day, strtotime($from)); $i <= $endDate; $i = strtotime('+1 week', $i))
                            {

                                // Controllo che non esiste un corso così
                                $exist = \App\Models\Calendar::where('from', date('Y-m-d ' . $d["from"] . ":00", $i))->where('to', date('Y-m-d ' . $d["to"] . ":00", $i))->where('name', $course_name)->first();

                                if (!$exist && !in_array(date('Y-m-d', $i), $this->festivita))
                                {

                                    // Creo il calendario del corso
                                    $calendar = new \App\Models\Calendar();
                                    $calendar->course_id = $this->course->id;
                                    $calendar->court_id = null;
                                    $calendar->name = $course_name;
                                    $calendar->course_type_id = null;
                                    $calendar->course_duration_id = null;
                                    $calendar->course_frequency_id = null;
                                    $calendar->course_level_id = null;
                                    $calendar->instructor_id = null;
                                    $calendar->from = date('Y-m-d ' . $d["from"] . ":00", $i);
                                    $calendar->to = date('Y-m-d ' . $d["to"] . ":00", $i);
                                    $calendar->note = '';
                                    $calendar->status = 0;
                                    $calendar->save();

                                }
                                
                            }
                        }
                    }
                }

                // Creo le causali di pagamento
                //$causal = "PAGAMENTO CORSO [nome corso]-LIVELLO-FREQUENZA-ANNO-[tipo abbonamento]-[mese inizio]/[mese fine]

                /*
                $causal = "PAGAMENTO CORSO " . $this->name . " - " . $lev . " - " . $freq . " - " . $this->year . " - " . $mFrom . "/" . $mTo;
                $cp = \App\Models\Causal::where('name', $causal)->first();
                if (!$cp)
                {
                    $cp = new \App\Models\Causal();
                    $cp->name = $causal;
                    $cp->type = "IN";
                    $cp->parent_id = null;
                    $cp->money = false;
                    $cp->corrispettivo_fiscale = false;
                    $cp->no_receipt = false;
                    $cp->user_status = false;
                    $cp->no_first = false;
                    $cp->no_records = false;
                    $cp->enabled = true;
                    $cp->save();
                }
                $course->causal_id = $cp->id;

                $causal = "PAGAMENTO ISCRIZIONE " . $this->name . " - " . $lev . " - " . $freq . " - " . $this->year . " - " . $mFrom . "/" . $mTo;
                $ci = \App\Models\Causal::where('name', $causal)->first();
                if (!$ci)
                {
                    $ci = new \App\Models\Causal();
                    $ci->name = $causal;
                    $ci->type = "IN";
                    $ci->parent_id = null;
                    $ci->money = false;
                    $ci->corrispettivo_fiscale = false;
                    $ci->no_receipt = false;
                    $ci->user_status = false;
                    $ci->no_first = false;
                    $ci->no_records = false;
                    $ci->enabled = true;
                    $ci->save();
                }
                $course->sub_causal_id = $ci->id;
                */

                $course->save();

                session()->flash('success','Corso creato');
                $this->resetFields();
                $this->add = false;
                $this->emit('setEdit', false);
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id){
        $this->resetFields();
        try {
            $course = \App\Models\Course::findOrFail($id);
            if( !$course) {
                session()->flash('error','Corso non trovato');
            } else {
                $this->name = $course->name;
                $this->enabled = $course->enabled;
                $this->parent_id = $course->parent_id;
                $this->course_type_id = $course->course_type_id;
                $this->course_duration_id = $course->course_duration_id;
                $this->course_frequency_id = $course->course_frequency_id;
                $this->course_level_id = $course->course_level_id;
                $this->date_from = $course->date_from;
                $this->date_to = $course->date_to;
                $this->category_id = $course->category_id;
                $this->causal_id = $course->causal_id;
                $this->sub_causal_id = $course->sub_causal_id;
                $this->max_members = $course->max_members;
                $this->instructor_id = $course->instructor_id;
                $this->year = $course->year;
                $this->price = formatPrice($course->price);
                $this->subscription_price = formatPrice($course->subscription_price);
                $this->months = json_decode($course->months);
                $this->when = array();
                if ($course->when != null)
                {
                    foreach(json_decode($course->when) as $z)
                    {
                        $this->when[] = array("day" => $z->day, "from" => $z->from, "to" => $z->to);
                    }
                }
                else
                {
                    $this->when[] = array('day' => array(), 'from' => '', 'to' => '');
                }

                $this->prices = array();
                if ($course->prices != null)
                {
                    foreach(json_decode($course->prices) as $z)
                    {
                        $this->prices[] = array("course_subscription_id" => $z->course_subscription_id, "price" => $z->price);
                    }
                }
                else
                {
                    $this->prices[] = array('course_subscription_id' => null, 'price' => 0);
                }
                $this->type = $course->type;
                $this->dataId = $course->id;
                $this->update = true;
                $this->add = false;
            }
            $this->emit('setEdit', true);
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            \App\Models\Course::whereId($this->dataId)->update([
                'name' => $this->name,
                'parent_id' => $this->parent_id,
                'course_type_id' => $this->course_type_id,
                'course_duration_id' => $this->course_duration_id,
                'course_frequency_id' => $this->course_frequency_id,
                'course_level_id' => $this->course_level_id,
                'date_from' => $this->date_from,
                'date_to' => $this->date_to,
                'category_id' => $this->category_id,
                'causal_id' => $this->causal_id,
                'sub_causal_id' => $this->sub_causal_id,
                'max_members' => $this->max_members,
                'instructor_id' => $this->instructor_id,
                'year' => $this->year,
                'price' => currencyToDouble($this->price),
                'subscription_price' => currencyToDouble($this->subscription_price),
                'months' => json_encode($this->months),
                'type' => $this->type,
                'when' => json_encode($this->when),
                'prices' => json_encode($this->prices),
                'enabled' => $this->enabled
            ]);
            session()->flash('success','Corso aggiornato');
            $this->resetFields();
            $this->update = false;
            $this->emit('setEdit', false);
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancel()
    {
        $this->add = false;
        $this->update = false;
        $this->resetFields();
        $this->emit('setEdit', false);
    }

    public function delete($id)
    {
        try{
            \App\Models\Course::find($id)->delete();
            session()->flash('success',"Corso eliminato");
            return redirect(request()->header('Referer'));
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $e->getMessage() . ')');
        }
    }

    public function setCausal($id, $idx)
    {
        $this->causal_id = $id;
    }

    public function setSubscriptionCausal($id, $idx)
    {
        $this->sub_causal_id = $id;
    }

    public function setCategory($id)
    {
        $this->category_id = $id;
    }

    public function duplicate($id, $isMultiple){
        $course = \App\Models\Course::findOrFail($id);
        $newCourse = $course->replicate();
        $newYear = date("Y") . "-" . (date("Y") + 1);
        if ($course->year != '')
        {
            list($u, $y) = explode("-", $course->year);
            $newYear = ($u + 1) . "-" . ($u + 2);
        }
        $newCourse->year = $newYear;
        $newCourse->save();
        if (!$isMultiple)
            $this->edit($newCourse->id);
    }

    public function duplicateMultiple($ids){
        foreach($ids as $id)
        {
            $this->duplicate($id, true);
        }
        return redirect()->to('/courses');
    }

    public function setDay($idx, $d)
    {

        if (in_array($d, $this->when[$idx]["day"]))
        {
            $i = array_search($d, $this->when[$idx]["day"]);
            array_splice($this->when[$idx]["day"], $i, 1);

        }
        else
        {
            $this->when[$idx]["day"][] = $d;
        }

    }

    public function addRow()
    {
        $this->when[] = array('day' => array(), 'from' => '', 'to' => '');
    }

    public function delRow($idx)
    {
        unset($this->when[$idx]);
    }

    public function addPrice()
    {
        $this->prices[] = array('course_subscription_id' => null, 'price' => 0);
    }

    public function delPrice($idx)
    {
        unset($this->prices[$idx]);
    }

}
