<?php

namespace Modules\MultiPOS\Livewire\Reports;

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

class SuperAdminUsageReport extends Component
{
    use LivewireAlert;

    public $selectedMonth;
    public $selectedYear;
    public $machines = [];

    public function mount()
    {
        $this->selectedMonth = Carbon::now()->month;
        $this->selectedYear = Carbon::now()->year;
        $this->loadReport();
    }

    public function loadReport()
    {
        $startDate = Carbon::create($this->selectedYear, $this->selectedMonth, 1)->startOfMonth();
        $endDate = Carbon::create($this->selectedYear, $this->selectedMonth, 1)->endOfMonth();

        $machines = PosMachine::with(['restaurant', 'branch'])
            ->where('status', 'active')
            ->get();

        $this->machines = [];

        foreach ($machines as $machine) {
            $stats = PosMachineUsageService::getMachineStats($machine->id, $startDate, $endDate);
            
            $this->machines[] = [
                'machine' => $machine,
                'restaurant' => $machine->restaurant,
                'branch' => $machine->branch,
                'total_orders' => $stats['total_orders'],
                'revenue' => $stats['net_sales'],
                'last_seen' => $machine->last_seen_at,
            ];
        }

        // Sort by restaurant name, then branch name
        usort($this->machines, function ($a, $b) {
            $restaurantCompare = strcmp($a['restaurant']->name ?? '', $b['restaurant']->name ?? '');
            if ($restaurantCompare !== 0) {
                return $restaurantCompare;
            }
            return strcmp($a['branch']->name ?? '', $b['branch']->name ?? '');
        });
    }

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

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

    public function render()
    {
        return view('multipos::livewire.reports.super-admin-usage-report');
    }
}

