<?php

namespace App\Http\Livewire;

use Livewire\Component;

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,
        $date_from, $date_to;

    public $categories = array();

    public $selectedYear = '';

    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_type_id' => 'required',
        'course_duration_id' => 'required',
        'course_frequency_id' => 'required',
        'course_level_id' => 'required',
        'causal_id' => 'required',
        'sub_causal_id' => 'required',
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'causal_id' => 'Campo obbligatorio',
        'sub_causal_id' => 'Campo obbligatorio',
    ];

    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 = date("Y");
        $this->price = 0;
        $this->subscription_price = 0;
        $this->date_from = null;
        $this->date_to = null;
        $this->months = array();
        $this->enabled = true;
        $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
        {
            if (date("m") >= env('FISCAL_YEAR_MONTH_FROM', 1))
                $this->selectedYear = date("Y") . "-" . (date("Y") + 1);
            else
                $this->selectedYear = (date("Y") - 1) . "-" . date("Y");
            //$this->selectedYear = $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 {
            \App\Models\Course::create([
                '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),
                'enabled' => $this->enabled
            ]);
            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->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),
                '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 (' . $ex->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');
    }


}
