<?php

namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;

class Sponsor extends Component
{

    use WithFileUploads;

    public $records, $name, $fiscal_code, $vat, $address, $zip_code,$nation_id,$province_id,$city_id,$phone,$email,$enabled, $dataId, $update = false, $add = false;
    public $first_name, $last_name;
    public $from_date, $to_date, $subscription_date, $amount, $file, $file_old, $updateContract = false, $addContract = false, $contractId;
    public $isItaly = true;

    public $searchTxt;
    public $search;

    public $contracts = array();

    public $showReset = false;
    protected $rules = [
        'name' => 'required'
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'from_date.required' => 'La data è obbligatoria',
        'to_date.required' => 'La data è obbligatoria',
        'subscription_date.required' => 'La data è obbligatoria',
    ];

    public function resetFields(){
        $this->name = '';
        $this->first_name = '';
        $this->last_name = '';
        $this->fiscal_code = '';
        $this->vat = '';
        $this->address = '';
        $this->zip_code = '';
        $this->nation_id = null;
        $this->province_id = null;
        $this->city_id = null;
        $this->phone = '';
        $this->email = '';
        $this->enabled = true;
        $this->contracts = array();
        $this->emit('load-data-table');
    }

    public function resetContract(){
        $this->from_date = '';
        $this->to_date = '';
        $this->subscription_date = '';
        $this->amount = 0;
        $this->file = '';
        $this->file_old = '';
    }

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

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

        $this->sortField = $field;
    }

    public function mount()
    {

        if (isset($_GET["new"]))
            $this->add();

    }

    public function search()
    {
        if ($this->searchTxt != '')
        {
            $this->search = $this->searchTxt;
            $this->showReset = true;
        }
    }
    public function resetSearch()
    {
        $this->showReset = false;
        $this->searchTxt = '';
        $this->search = $this->searchTxt;
    }

    public function render()
    {
        //if ($this->search != '')
        //    $this->records = \App\Models\Sponsor::where('name', 'LIKE', '%' . $this->search . '%')->orWhere('first_name', 'LIKE', '%' . $this->search . '%')->orWhere('last_name', 'LIKE', '%' . $this->search . '%')->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->get();
        //else
            $this->records = \App\Models\Sponsor::get();

        $this->contracts = array();
        if ($this->dataId > 0)
            $this->contracts = \App\Models\SponsorContract::where('sponsor_id', $this->dataId)->orderBy('from_date', 'asc')->get();

        return view('livewire.sponsor');
    }

    public function hydrate()
    {
        $this->emit('load-select');
    }

    public function checkIsItaly()
    {
        $n = \App\Models\Nation::findOrFail($this->nation_id);
        $this->isItaly = $n->is_italy;
    }

    public function add()
    {
        $this->resetFields();
        $this->resetContract();
        $this->emit('load-select');
        $this->add = true;
        $this->update = false;
    }

    public function store()
    {
        $this->validate();
        try {
            \App\Models\Sponsor::create([
                'name' => $this->name,
                'first_name' => $this->first_name,
                'last_name' => $this->last_name,
                'fiscal_code' => $this->fiscal_code,
                'vat' => $this->vat,
                'address' => $this->address,
                'zip_code' => $this->zip_code,
                'nation_id' => $this->nation_id,
                'province_id' => $this->province_id,
                'city_id' => $this->city_id,
                'phone' => $this->phone,
                'email' => $this->email,
                'enabled' => $this->enabled
            ]);
            session()->flash('success','Sponsor creato');
            $this->resetFields();
            $this->add = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id){
        $this->emit('load-select');
        try {
            $sponsor = \App\Models\Sponsor::findOrFail($id);
            if( !$sponsor) {
                session()->flash('error','Sponsor non trovato');
            } else {
                $this->name = $sponsor->name;
                $this->first_name = $sponsor->first_name;
                $this->last_name = $sponsor->last_name;
                $this->fiscal_code = $sponsor->fiscal_code;
                $this->vat = $sponsor->vat;
                $this->address = $sponsor->address;
                $this->zip_code = $sponsor->zip_code;
                $this->nation_id = $sponsor->nation_id;
                $this->province_id = $sponsor->province_id;
                $this->city_id = $sponsor->city_id;
                $this->phone = $sponsor->phone;
                $this->email = $sponsor->email;
                $this->enabled = $sponsor->enabled;
                $this->dataId = $sponsor->id;
                $this->update = true;
                $this->add = false;
                $this->emit('load-provinces', $this->nation_id, 'provinceClass');
                $this->emit('load-cities', $this->province_id, 'cityClass');
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            \App\Models\Sponsor::whereId($this->dataId)->update([
                'name' => $this->name,
                'first_name' => $this->first_name,
                'last_name' => $this->last_name,
                'fiscal_code' => $this->fiscal_code,
                'vat' => $this->vat,
                'address' => $this->address,
                'zip_code' => $this->zip_code,
                'nation_id' => $this->nation_id,
                'province_id' => $this->province_id,
                'city_id' => $this->city_id,
                'phone' => $this->phone,
                'email' => $this->email,
                'enabled' => $this->enabled
            ]);
            session()->flash('success','Sponsor 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();
    }

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

    public function addContract()
    {
        $this->resetContract();
        $this->addContract = true;
        $this->updateContract = false;
    }

    public function storeContract()
    {
        $rules = [
            'from_date' => 'required|date',
            'to_date' => 'required|date',
            'subscription_date' => 'required|date'
        ];
        $this->validate($rules);
        try {

            $name = '';
            try{

                if ($this->file)
                {
                    $name = md5($this->file . microtime()).'.'.$this->file->extension();
                    $this->file->storeAs('public', $name);
                }
            } catch (\Exception $ex) {
                //session()->flash('error','Errore (' . $ex->getMessage() . ')');
            }

            \App\Models\SponsorContract::create([
                'sponsor_id' => $this->dataId,
                'from_date' => $this->from_date,
                'to_date' => $this->to_date,
                'subscription_date' => $this->subscription_date,
                'amount' => $this->currencyToDouble($this->amount),
                'file' => $name
            ]);
            session()->flash('success','Contratto creato');
            $this->resetContract();
            $this->addContract = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function editContract($id){
        // $this->emit('load-select');
        try {
            $sponsorContract = \App\Models\SponsorContract::findOrFail($id);
            if( !$sponsorContract) {
                session()->flash('error','Contratto non trovato');
            } else {
                $this->from_date = $sponsorContract->from_date ? date("Y-m-d", strtotime($sponsorContract->from_date)) : "";
                $this->to_date = $sponsorContract->to_date ? date("Y-m-d", strtotime($sponsorContract->to_date)) : "";
                $this->subscription_date = $sponsorContract->subscription_date ? date("Y-m-d", strtotime($sponsorContract->subscription_date)) : "";
                $this->amount = formatPrice($sponsorContract->amount);
                $this->file_old = $sponsorContract->file;
                $this->contractId = $sponsorContract->id;
                $this->updateContract = true;
                $this->addContract = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function updateContract()
    {
        $rules = [
            'from_date' => 'required|date',
            'to_date' => 'required|date',
            'subscription_date' => 'required|date'
        ];
        $this->validate($rules);
        try {

            $name = '';
            try{

                if ($this->file)
                {
                    $name = md5($this->file . microtime()).'.'.$this->file->extension();
                    $this->file->storeAs('public', $name);
                }
            } catch (\Exception $ex) {
                //session()->flash('error','Errore (' . $ex->getMessage() . ')');
            }

            \App\Models\SponsorContract::whereId($this->contractId)->update([
                'from_date' => $this->from_date,
                'to_date' => $this->to_date,
                'subscription_date' => $this->subscription_date,
                'amount' => $this->currencyToDouble($this->amount),
                'file' => $name != '' ? $name : $this->file_old,
            ]);
            session()->flash('success','Contratto aggiornato');
            $this->resetContract();
            $this->updateContract = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancelContract()
    {
        $this->addContract = false;
        $this->updateContract = false;
        $this->resetContract();
    }

    public function removeFile()
    {
        $this->file_old = '';
    }

    public function deleteContract($id)
    {
        try{
            \App\Models\SponsorContract::find($id)->delete();
            session()->flash('success',"Contratto eliminato");
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $e->getMessage() . ')');
        }
    }

    public function getNation($nation)
    {
        if ($nation > 0)
        {
            $ret = \App\Models\Nation::findOrFail($nation);
            return $ret->name;
        }
        return "";
    }

    public function getProvince($province)
    {
        if ($province > 0)
        {
            $ret = \App\Models\Province::findOrFail($province);
            return $ret->name;
        }
        return "";
    }

    public function getCity($city)
    {
        if ($city > 0)
        {
            $ret = \App\Models\City::findOrFail($city);
            return $ret->name;
        }
        return "";
    }

    function currencyToDouble($val)
    {
        $x = str_replace("€", "", $val);
        $x = str_replace(".", "", $x);
        $x = str_replace(",", ".", $x);
        return floatval(trim($x));
    }
}
