<?php

namespace App\Http\Livewire;

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

class PaymentMethod extends Component
{
    public $records, $name, $enabled, $money, $type, $corrispettivo_fiscale, $dataId, $origin_id, $destination_id, $update = false, $add = false;
    public $paymentMethods = [];
    public $showHidden = false;

    public $origins = [];
    public $destinations = [];

    protected $rules = [
        'name' => 'required'
    ];

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

    public $sortField = 'name';
    public $sortAsc = true;

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

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortAsc = ! $this->sortAsc;
        } else {
            $this->sortAsc = true;
        }

        $this->sortField = $field;
    }

    public function resetFields()
    {
        $this->name = '';
        $this->money = false;
        $this->type = 'ALL';
        $this->corrispettivo_fiscale = false;
        $this->enabled = true;
        $this->emit('load-data-table');
    }

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

        $this->origins = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['OUT', 'ALL'])->get();
        $this->destinations = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['IN', 'ALL'])->get();

        $this->loadPaymentMethodOptions();
    }

    public function hide($id)
    {
        try {
            \App\Models\PaymentMethod::whereId($id)->update(['hidden' => true]);
            session()->flash('success', 'Metodo di pagamento nascosto');
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function show($id)
    {
        try {
            \App\Models\PaymentMethod::whereId($id)->update(['hidden' => false]);
            session()->flash('success', 'Metodo di pagamento ripristinato');
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function toggleShowHidden()
    {
        $this->showHidden = !$this->showHidden;
    }

    public function render()
    {
        if ($this->showHidden) {
            $this->records = \App\Models\PaymentMethod::all();
        } else {
            $this->records = \App\Models\PaymentMethod::where(function ($query) {
                $query->where('hidden', false)->orWhereNull('hidden');
            })->get();
        }

        // foreach ($this->records as $r) {

        //     dd($r, $r->origin);
        //     $r->origin = $r->origin ? $r->origin->name : '';
        //     $r->destination = $r->destination ? $r->destination->name : '';
        // }

        return view('livewire.payment_method');
    }

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

    public function store()
    {
        $this->validate();
        try {
            \App\Models\PaymentMethod::create([
                'name' => $this->name,
                'origin_id' => $this->origin_id != "" ? $this->origin_id : null,
                'destination_id' => $this->destination_id != "" ? $this->destination_id : null,
                'money' => $this->money,
                'type' => $this->type,
                'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Metodo di pagamento creato');
            $this->resetFields();
            $this->add = false;
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id)
    {
        try {
            $payment_method = \App\Models\PaymentMethod::findOrFail($id);
            if (!$payment_method) {
                session()->flash('error', 'Metodo di pagamento non trovato');
            } else {
                $this->name = $payment_method->name;
                $this->enabled = $payment_method->enabled;
                $this->corrispettivo_fiscale = $payment_method->corrispettivo_fiscale;
                $this->money = $payment_method->money;
                $this->type = $payment_method->type;
                $this->origin_id = $payment_method->origin_id;
                $this->destination_id = $payment_method->destination_id;
                $this->dataId = $payment_method->id;
                $this->update = true;
                $this->add = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            \App\Models\PaymentMethod::whereId($this->dataId)->update([
                'name' => $this->name,
                'origin_id' => $this->origin_id != "" ? $this->origin_id : null,
                'destination_id' => $this->destination_id != "" ? $this->destination_id : null,
                'money' => $this->money,
                'type' => $this->type,
                'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Metodo di pagamento aggiornato');
            $this->resetFields();
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

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

    protected function loadPaymentMethodOptions()
    {
        $this->paymentMethods = [
            ['name' => 'Contanti', 'code' => 'MP01'],
            ['name' => 'Assegno', 'code' => 'MP02'],
            ['name' => 'Assegno circolare', 'code' => 'MP03'],
            ['name' => 'Contanti presso Tesoreria', 'code' => 'MP04'],
            ['name' => 'Bonifico', 'code' => 'MP05'],
            ['name' => 'Vaglia cambiario', 'code' => 'MP06'],
            ['name' => 'Bollettino bancario', 'code' => 'MP07'],
            ['name' => 'Carta di credito', 'code' => 'MP08'],
            ['name' => 'RID', 'code' => 'MP09'],
            ['name' => 'RID utenze', 'code' => 'MP10'],
            ['name' => 'RID veloce', 'code' => 'MP11'],
            ['name' => 'Riba', 'code' => 'MP12'],
            ['name' => 'MAV', 'code' => 'MP13'],
            ['name' => 'Quietanza erario stato', 'code' => 'MP14'],
            ['name' => 'Giroconto su conti di contabilità speciale', 'code' => 'MP15'],
            ['name' => 'Domiciliazione bancaria', 'code' => 'MP16'],
            ['name' => 'Domiciliazione postale', 'code' => 'MP17']
        ];
    }
}
