<?php

namespace App\Livewire\Chart;

use App\Models\Expense;
use App\Models\Payroll;
use App\Models\Purchase;
use Livewire\Component;

class OutletExpense extends Component
{
    public array $outlets = [];

    public array $expenses = [];

    public array $backgroundColors = [];

    public array $borderColors = [];

    public function mount(array $outlets)
    {
        $expensesData = [];

        foreach ($outlets as $id => $name) {
            $expenseTotal = Expense::where('outlet_id', $id)->sum('amount');

            $purchaseTotal = auth()->user()->hasRole(['Developer', 'Owner']) ? Purchase::where('outlet_id', $id)->sum('total') : 0;

            $payrollTotal = Payroll::whereHas('user.outlets', fn ($q) => $q->where('outlet_id', $id))->sum('total_salary');

            $total = $expenseTotal + $purchaseTotal + $payrollTotal;

            $expensesData[$name] = $total;
        }

        $this->outlets = array_values($outlets);

        $this->expenses = array_values($expensesData);

        // random colors
        $count = count($this->outlets);
        $this->backgroundColors = randomColors($count, 0.2);
        $this->borderColors = randomColors($count, 1.0);
    }

    public function render()
    {
        return view('livewire.chart.outlet-expense');
    }
}
