<?php

namespace App\Http\Livewire;

use App\Http\Middleware\TenantMiddleware;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class Subscription extends Component
{

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

    public $records;

    public $dataId;
    public $update = false;
    public $add = false;

    public $name;
    public $causal_id;
    public $sub_causal_id;
    public $subscription_price;
    public $prices;
    public $enabled;

    public $msgPrices = '';

    public $course_subscriptions = [];

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

    protected $rules = [
        'name' => 'required',
        'subscription_price' => 'required|min:0|not_in:0'
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'subscription_price.required' => 'Deve essere maggiore di zero',
        'subscription_price.not_in' => 'Deve essere maggiore di zero',
    ];

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    public function resetFields()
    {
        $this->name = '';
        $this->causal_id = null;
        $this->sub_causal_id = null;
        $this->subscription_price = 0;
        $this->prices = [];
        $this->prices[] = array('course_subscription_id' => null, 'price' => 0);
        $this->enabled = true;

        $this->emit('load-data-table');
    }


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

        $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->where('enabled', true)->orderBy('name', 'asc')->get();
    }

    public function render()
    {
        $this->records = \App\Models\Subscription::all();

        return view('livewire.subscription');
    }

    public function add()
    {
        $this->resetFields();

        $this->add = true;
        $this->update = false;

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

    public function store()
    {
        $this->validate();
        try {
            $this->msgPrices = '';

            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 = 'Non è possibile aggiungere più volte la stessa tipologia di pagamento';

            if ($this->msgPrices == '') {
                $subscription = new \App\Models\Subscription();

                $subscription->name = $this->name;
                $subscription->subscription_price = currencyToDouble($this->subscription_price);
                $subscription->prices = json_encode($this->prices);
                $subscription->enabled = $this->enabled;

                $causal = "PAGAMENTO ABBONAMENTO";
                $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();
                }
                $subscription->causal_id = $cp->id;

                $causal = "PAGAMENTO ISCRIZIONE";
                $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();
                }
                $subscription->sub_causal_id = $ci->id;

                $subscription->save();

                session()->flash('success', 'Abbonamento 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 {
            $subscription = \App\Models\Subscription::findOrFail($id);

            if (!$subscription) {
                session()->flash('error', 'Abbonamento non trovato');
            } else {
                $this->name = $subscription->name;
                $this->enabled = $subscription->enabled;
                $this->causal_id = $subscription->causal_id;
                $this->sub_causal_id = $subscription->sub_causal_id;
                $this->subscription_price = formatPrice($subscription->subscription_price);
                $this->prices = array();
                if ($subscription->prices != null) {
                    foreach (json_decode($subscription->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->dataId = $subscription->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 {
            $this->msgPrices = '';

            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 = 'Non è possibile aggiungere più volte la stessa tipologia di pagamento';

            if ($this->msgPrices == '') {
                \App\Models\Subscription::whereId($this->dataId)->update([
                    'name' => $this->name,
                    'causal_id' => $this->causal_id,
                    'sub_causal_id' => $this->sub_causal_id,
                    'subscription_price' => currencyToDouble($this->subscription_price),
                    'prices' => json_encode($this->prices),
                    'enabled' => $this->enabled
                ]);
                session()->flash('success', 'Abbonamento 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\Subscription::find($id)->delete();
            session()->flash('success', "Abbonamento 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 duplicate($id, $isMultiple)
    {
        $subscription = \App\Models\Subscription::findOrFail($id);
        $new_subscription = $subscription->replicate();
        $new_subscription->save();

        if (!$isMultiple)
            $this->edit($new_subscription->id);
    }

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

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

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