<?php

namespace App\Livewire\Chart;

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

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

    public array $revenues = [];

    public array $expenses = [];

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

        $expenseData = [];

        foreach ($outlets as $id => $name) {
            $totalRevenue = Order::where('outlet_id', $id)->sum('total');
            $revenueData[$name] = $totalRevenue;

            $expenseTotal = Expense::where('outlet_id', $id)->sum('amount');
            $purchaseTotal = Purchase::where('outlet_id', $id)->sum('total');
            $payrollTotal = Payroll::whereHas('user.outlets', fn ($q) => $q->where('outlet_id', $id))->sum('total_salary');
            $expenseData[$name] = $expenseTotal + $purchaseTotal + $payrollTotal;
        }

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

        $this->revenues = array_values($revenueData);

        $this->expenses = array_values($expenseData);
    }

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