<?php

namespace App\Http\Livewire\Box;

use App\Models\BankAccount;
use App\Models\Record;
use Carbon\Carbon;
use Livewire\Component;

class IndexBox extends Component
{
    public $sale = 0, $movement = 0, $advance = 0, $date, $consult = false;
    public $banks;
    protected $listeners = ['render', 'getsale', 'getmovement', 'getAdvance'];

    public function mount()
    {
        $this->date = Carbon::now();
    }

    public function render()
    {
        return view('livewire.box.index-box')
            ->layout('app');
    }

    public function getsale($total)
    {
        $this->sale = $total['total'];
    }
    public function getmovement($total)
    {
        $this->movement = $total['total'];
    }
    public function getAdvance($total)
    {
        $this->advance = $total['total'];
    }

    public function getCallTotal()
    {
        $this->emitTo('bank.cash-counter', 'render');
        $this->emitTo('box.today-sale', 'sendTotal');
        $this->emitTo('box.today-movement', 'sendTotal');
        $this->emitTo('box.today-advance', 'sendTotal');
        $this->consult = true;
        $this->banks = BankAccount::all();
    }

    public function save()
    {
        if ($this->consult) {
            $record = Record::whereDate('date_record', $this->date)->first();
            if ($record) {
                $record->update([
                    'total_record' => $this->sale + $this->movement + $this->advance,
                ]);
                $this->emit('notify', 'Actualizado');
            } else {
                Record::create([
                    'date_record' => $this->date,
                    'total_record' => $this->sale + $this->movement + $this->advance,
                ]);
                $this->emit('notify', 'Registrado');
            }
            $this->emitTo('box.record-box', 'render');
        } else {
            $this->emit('error', ['title' => 'Consulta antes de registrar']);
        }
    }
}
