<?php

namespace App\Http\Livewire\Bank;

use App\Models\Advance;
use App\Models\BankAccount;
use App\Models\Sale;
use Livewire\Component;

class CashCounter extends Component
{
    protected  $listeners = ['render'];
    public function render()
    {
        // Contador de movimientos
        $banks = BankAccount::all();
        foreach ($banks as $bank) {
            $movement_sum = 0;
            // Suma de los adelantos de una cuenta
            $advances_sum = Advance::with(['Sale'])
                ->where('bank_account_id', $bank->id)
                ->get()->sum('total_advance');
            foreach ($bank->Movement as $movement) {
                $movement_sum += $movement->total_movement;
            }
            $bank->update([
                'total' => ($movement_sum + $advances_sum)
            ]);
        }
        // Contador de ventas
        $sales = Sale::where('condition_id', 2)->get();
        foreach ($sales as $sale) {
            $gain = $sale->total_sale - ($sale->Advance->sum('total_advance') + $sale->total_discount_sale);
            $bank_money = $sale->BankAccount->total;
            $sale->BankAccount->update([
                'total' => $bank_money + $gain
            ]);
        }
        // Contador de adelantos
        $advances = Advance::all();

        return view('livewire.bank.cash-counter', compact('advances', 'banks', 'sales'));
    }
}
