<?php

namespace Modules\MultiPOS\Livewire\Reports;

use Livewire\Component;
use Modules\MultiPOS\Entities\PosMachine;
use Modules\MultiPOS\Services\PosMachineUsageService;
use Carbon\Carbon;
use Jantinnerezo\LivewireAlert\LivewireAlert;

class PosMachineReport extends Component
{
    use LivewireAlert;

    public $branchId;
    public $startDate;
    public $endDate;
    public $machines = [];
    public $summary = [
        'total_machines' => 0,
        'total_orders' => 0,
        'net_sales' => 0,
        'avg_order_value' => 0,
    ];

    public function mount()
    {
        $this->branchId = branch()->id ?? null;
        $this->startDate = Carbon::now()->startOfWeek()->format('Y-m-d');
        $this->endDate = Carbon::now()->endOfWeek()->format('Y-m-d');
        $this->loadReport();
    }

    public function loadReport()
    {
        if (!$this->branchId) {
            return;
        }

        $startDate = Carbon::parse($this->startDate)->startOfDay();
        $endDate = Carbon::parse($this->endDate)->endOfDay();

        $machines = PosMachine::where('branch_id', $this->branchId)
            ->where('status', 'active')
            ->get();

        $this->machines = [];
        $totalOrders = 0;
        $totalSales = 0;

        foreach ($machines as $machine) {
            $stats = PosMachineUsageService::getMachineStats($machine->id, $startDate, $endDate);
            $this->machines[] = array_merge(['machine' => $machine], $stats);
            $totalOrders += $stats['total_orders'];
            $totalSales += $stats['net_sales'];
        }

        $this->summary = [
            'total_machines' => $machines->count(),
            'total_orders' => $totalOrders,
            'net_sales' => $totalSales,
            'avg_order_value' => $totalOrders > 0 ? $totalSales / $totalOrders : 0,
        ];
    }

    public function updatedStartDate()
    {
        $this->loadReport();
    }

    public function updatedEndDate()
    {
        $this->loadReport();
    }

    public function render()
    {
        return view('multipos::livewire.reports.pos-machine-report');
    }
}

