<?php

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

class RecordOUT extends Component
{

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

    public $sortField ='date';
    public $sortAsc = false;

    public $typeOUT = "OUT";

    public $fromPage = '';

    public $multiP = false;

    public $multiMonthTo = 0;
    public $multiYearTo = 0;
    public $multiMonthFrom = 0;
    public $multiYearFrom = 0;

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

        $this->sortField = $field;
    }

    public $records, $dataId, $member_id, $supplier_id,
    $causal_id,
    $payment_method_id,
    $origin_id,
    $date,
    $month,
    $year,
    $type,
    $amount,
    $note,
    $commercial, $update = false, $add = false;

    public $filterSupplier = 0, $filterPaymentMethod = 0, $filterCausals = [], $filterFrom = '', $filterTo = '', $filterCommercial = 0;

    public $hasFilter = false;

    public $total = 0;

    public $selectedFilter = '';

    public $multipleIds = [];
    public $multipleAction = '';

    public $selectId = 0;

    public $causals = array();
    public $payments = array();
    public $banks = array();
    public $suppliers = array();

    public $rows = array();

    protected $rules = [
        'supplier_id' => 'required',
        'payment_method_id' => 'required',
        'rows.*.causal_id' => 'required',
        'rows.*.amount' => 'required'
        //'causal_id' => 'required',
        //'amount' => 'required'
    ];

    protected $messages = [
        'supplier_id.required' => 'Il fornitore è obbligatorio',
        'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
        'rows.*.amount.required' => 'L\'importo è obbligatorio',
        'rows.*.causal_id.required' => 'La causale è obbligatoria'
    ];

    public function getSupplierProperty()
    {
        $ret = null;
        if ($this->supplier_id > 0)
        {
            $ret = \App\Models\Supplier::findOrFail($this->supplier_id);
        }
        return $ret;
    }

    public function getCausalProperty()
    {
        $ret = null;
        if ($this->causal_id > 0)
        {
            $ret = \App\Models\Causal::findOrFail($this->causal_id);
        }
        return $ret;
    }

    public function resetFields(){
        $this->member_id = null;
        $this->supplier_id = null;
        //$this->causal_id = null;
        $this->payment_method_id = null;
        $this->origin_id = null;
        $this->date = date("Y-m-d");
        //$this->month = date("n");
        //$this->year = date("Y");
        $this->type = 'OUT';
        //$this->note = '';
        //$this->amount = null;
        $this->commercial = 1;
        $this->rows = array();
        $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),  'amount' => null, 'note' => '', 'commercial' => 0);
        $this->emit('load-data-table');
    }

    public function getCausale($records, $indentation)
    {
        foreach($records as $record)
        {
            $this->causals[] = array('id' => $record->id, 'name' => $record->getTree());
            if(count($record->childs))
                $this->getCausale($record->childs, $indentation + 1);
        }
    }

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

    public function mount()
    {

        if (isset($_GET["from"]))
        {
            $this->fromPage = $_GET["from"];
        }

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

        $this->multiMonthFrom = date("n");
        $this->multiYearFrom = date("Y");
        $this->multiMonthTo = date("n");
        $this->multiYearTo = date("Y");

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

        $this->causals = array();

        $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->orderBy('name')->get(), 0);

        $this->suppliers = \App\Models\Supplier::select('name','id')->orderBy('name')->get();
        $this->payments = \App\Models\PaymentMethod::select('id', 'name')->whereIn('type', array('ALL', 'OUT'))->where('enabled', true)->orderBy('name')->get();
        $this->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'OUT'))->orderBy('name')->get();
    }

    public function updatedPaymentMethodId() {
        if ($this->payment_method_id) {
            $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
            $this->origin_id = $payment_method->origin_id ?? null;
        }
    }

    public function getCausal($causal)
    {
        $ret = '';
        if ($causal > 0)
        {
            $ret = \App\Models\Causal::findOrFail($causal)->getTree();
        }
        return $ret;
    }

    public function search()
    {
        $this->hasFilter = true;
    }

    public function disableSearch()
    {
        $this->filterSupplier = 0;
        $this->filterPaymentMethod = 0;
        $this->filterCausals = [];
        $this->filterTo = '';
        $this->filterFrom = '';
        $this->filterCommercial = 0;
        $this->hasFilter = false;
        $this->hasFilter = false;

    }

    public function render()
    {
        $datas = [];

        if (false)
        {
            if ($this->hasFilter)
            {

                $datas = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method');
                /*if ($this->filterCommercial > 0)
                {
                    $datas = $datas->where('commercial', $this->filterCommercial == 1 ? true : false);
                }*/
                if ($this->filterSupplier > 0)
                {
                    $datas = $datas->where('supplier_id', $this->filterSupplier);
                }
                if ($this->filterPaymentMethod > 0)
                {
                    $datas = $datas->where('payment_method_id', $this->filterPaymentMethod);
                }
                /*if (sizeof($this->filterCausals) > 0)
                {
                    $datas = $datas->whereIn('causal_id', $this->filterCausals);
                }*/
                if ($this->filterFrom != '')
                {
                    $datas = $datas->where('date', '>=', $this->filterFrom);
                }
                if ($this->filterTo != '')
                {
                    $datas = $datas->where('date', '<=', $this->filterTo);
                }
                //$this->records = $datas->orderBy('date', 'DESC')->get();

                $this->records = $datas->get();

                //$this->total = $this->records->sum('amount');

                $this->total = 0;
                foreach($this->records as $r)
                {
                    foreach($r->rows as $rr)
                    {
                        $this->total += $rr->amount;
                    }
                }

            }
            else
            {
                if ($this->selectedFilter == '')
                {
                    $this->records = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method')->limit(20)->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
                }
                else
                {
                    if ($this->selectedFilter == 0)
                    {
                        $fromDate = date("Y-m-d");
                        $toDate = date("Y-m-d");
                    }
                    if ($this->selectedFilter == 1)
                    {
                        $fromDate = date("Y-m-01");
                        $toDate = date("Y-m-t");
                    }
                    if ($this->selectedFilter == 2)
                    {
                        $fromDate = date("Y-01-01");
                        $toDate = date("Y-12-31");
                    }
                    if ($this->selectedFilter == 3)
                    {
                        $fromDate = date("2000-01-01");
                        $toDate = date("Y-12-31");
                    }
                    $this->records = \App\Models\Record::where('type', 'OUT')->whereBetween('date', [$fromDate, $toDate])->with('supplier', 'payment_method')->get();
                }
            }

            foreach($this->records as $r)
            {
                $r->total = $r->getTotal();
                $r->supplier = $r->supplier ? $r->supplier->name : '';
                $r->payment = $r->payment_method ? $r->payment_method->name : '';
            }
        }

        /*if ($this->sortField != '')
        {
            if ($this->sortAsc)
                $this->records = $this->records->sortBy($this->sortField);
            else
                $this->records = $this->records->sortByDesc($this->sortField);
        }
        else
            $this->records = $this->records->sortByDesc('id');*/

        return view('livewire.records_out');
    }

    public function executeMultipleAction(){

        if ($this->multipleAction == 'delete')
            $this->multipleDelete();

    }

    public function add()
    {

        $this->emit('load-select');
        //if ($this->hasFilter)
            $this->emit('hide-search');
        $this->resetFields();
        $this->add = true;
        $this->update = false;
        $this->emit('setEdit', true);
    }

    public function store()
    {
        $this->emit('refresh');

        $this->validate();
        try {
            $record = \App\Models\Record::create([
                'member_id' => $this->member_id,
                'supplier_id' => $this->supplier_id,
                //'causal_id' => $this->causal_id,
                'payment_method_id' => $this->payment_method_id,
                'origin_id' => $this->origin_id,
                'date' => $this->date,
                //'month' => $this->month,
                //'year' => $this->year,
                //'note' => $this->note,
                'type' => $this->type,
                //'amount' => $this->currencyToDouble($this->amount),
                'commercial' => $this->commercial,
            ]);

            $this->dataId = $record->id;
            $tot = 0;
            foreach($this->rows as $row)
            {
                foreach($row["when"] as $x => $y)
                {
                    $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
                }
                \App\Models\RecordRow::create([
                    'record_id' => $this->dataId,
                    'causal_id' => $row["causal_id"],
                    'note' => $row["note"],
                    'amount' => $this->currencyToDouble($row["amount"]),
                    'commercial' => $row["commercial"],
                    'when' => json_encode($row["when"])
                ]);
                $tot += $this->currencyToDouble($row["amount"]);
            }
            $record->amount = $tot;
            $record->save();

            session()->flash('success','Movimento 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();
        if (!isset($_GET["from"]) && $this->fromPage == '')
            $this->fromPage = 'out';
        $this->emit('setEdit', true);
        $this->emit('load-select');
        //if ($this->hasFilter)
            $this->emit('hide-search');
        try {
            $record = \App\Models\Record::findOrFail($id);
            if( !$record) {
                session()->flash('error','Movimento non trovato');
            } else {
                $this->member_id = $record->member_id;
                $this->supplier_id = $record->supplier_id;
                //$this->causal_id = $record->causal_id;
                $this->payment_method_id = $record->payment_method_id;
                $this->origin_id = $record->origin_id;
                $this->date = date("Y-m-d", strtotime($record->date));
                //$this->month = $record->month;
                //$this->year = $record->year;
                //$this->note = $record->note;
                $this->type = $record->type;
                //$this->amount = formatPrice($record->amount);
                $this->commercial = $record->commercial;
                $this->dataId = $record->id;
                $this->update = true;
                $this->add = false;

                $this->rows = \App\Models\RecordRow::where('record_id', $this->dataId)->select('causal_id', 'note', 'commercial', 'when', 'amount')->get()->toArray();
                foreach($this->rows as $i => $r)
                {
                    $this->rows[$i]['amount'] = formatPrice($this->rows[$i]['amount']);
                    $this->rows[$i]['when'] = json_decode($this->rows[$i]['when']);
                }

            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->emit('refresh');
        $this->validate();
        try {
            \App\Models\Record::whereId($this->dataId)->update([
                'member_id' => $this->member_id,
                'supplier_id' => $this->supplier_id,
                //'causal_id' => $this->causal_id,
                'payment_method_id' => $this->payment_method_id,
                'origin_id' => $this->origin_id,
                'date' => $this->date,
                //'month' => $this->month,
                //'year' => $this->year,
                //'note' => $this->note,
                'type' => $this->type,
                //'amount' => $this->currencyToDouble($this->amount),
                'commercial' => $this->commercial,
            ]);

            $tot = 0;

            // Elimino le righe
            \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
            // Inserisco le righe
            foreach($this->rows as $row)
            {
                foreach($row["when"] as $x => $y)
                {
                    $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
                }
                \App\Models\RecordRow::create([
                    'record_id' => $this->dataId,
                    'causal_id' => $row["causal_id"],
                    'note' => $row["note"],
                    'amount' => $this->currencyToDouble($row["amount"]),
                    'commercial' => $row["commercial"],
                    'when' => json_encode($row["when"])
                ]);
                $tot += $this->currencyToDouble($row["amount"]);
            }

            $rec = \App\Models\Record::findOrFail($this->dataId);
            $rec->amount = $tot;
            $rec->save();

            session()->flash('success','Movimento 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->emit('setEdit', false);
        $this->resetFields();
    }

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

    public function multipleDelete()
    {
        try{
            foreach($this->multipleIds as $id)
            {
                \App\Models\Record::find($id)->delete();
            }
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
        $this->multipleAction = '';
    }

    /*
    public function createReceipt()
    {

        $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->first();
        if ($receipt != null)
        {
            $receipt->update([
                'member_id' => $this->member_id,
                'supplier_id' => $this->supplier_id,
                'causal_id' => $this->causal_id,
                'payment_method_id' => $this->payment_method_id,
                'date' => date("Y-m-d", strtotime($this->date)),
                'month' => $this->month,
                'year' => $this->year,
                'type' => $this->type,
                'amount' => $this->currencyToDouble($this->amount),
                'commercial' => $this->commercial,
                'status' => 1,

            ]);
        }
        else
        {
            $number = 1;
            $exist = \App\Models\Receipt::where('year', $this->year)->orderBy('number', 'DESC')->first();
            if ($exist != null)
                $number = $exist->number + 1;

            $receipt = \App\Models\Receipt::create([
                'record_id' => $this->dataId,
                'member_id' => $this->member_id,
                'supplier_id' => $this->supplier_id,
                'causal_id' => $this->causal_id,
                'payment_method_id' => $this->payment_method_id,
                'number' => $number,
                'date' => $this->date,
                'month' => $this->month,
                'year' => $this->year,
                'type' => $this->type,
                'amount' => $this->currencyToDouble($this->amount),
                'commercial' => $this->commercial,
                'status' => 1,
            ]);
        }


    }

    public function removeReceipt()
    {
        $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
        $receipt->status = 99;
        $receipt->save();
        $this->currentReceip = $receipt;
    }

    */

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

    public function addRow()
    {
        $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),  'amount' => null, 'note' => '', 'commercial' => 0);
        $this->emit('load-select');
    }

    public function delRow($idx)
    {
        unset($this->rows[$idx]);
        // $this->emit('load-select');
    }

    public function addPeriod($idx)
    {
        $x = sizeof($this->rows[$idx]['when']) - 1;
        $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
        $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
        //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
    }

    public function delPeriod($idx, $xxx)
    {
        array_splice($this->rows[$idx]['when'], $xxx, 1);
        // $this->emit('load-select');
    }

    public function getTotal()
    {
        $total = 0.00;
        foreach($this->rows as $r)
        {
            $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
        }
        return formatPrice($total);
        // $this->emit('load-select');
    }

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

    public function multiPeriod()
    {
        $this->multiP = true;
    }

    public function multiPeriodCreate($idx)
    {

        $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
        $this->rows[$idx]['when'] = [];
        foreach ($period as $dt) {
            if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
                $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
        }

        $this->multiP = false;

    }

    public function multiPeriodCancel()
    {
        $this->multiP = false;
    }

}
