<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Sale;
use App\Models\Client;
use Carbon\Carbon;

class Reports extends Component
{
    public $range = 'today'; 
    public $customStartDate;
    public $customEndDate;

    public function mount()
    {
        $this->customStartDate = date('Y-m-d');
        $this->customEndDate = date('Y-m-d');
    }

    public function render()
    {
        $query = Sale::with('client');

        if ($this->range == 'today') {
            $query->whereDate('sale_date', Carbon::today());
        } elseif ($this->range == 'week') {
            $query->whereBetween('sale_date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()]);
        } elseif ($this->range == 'month') {
            $query->whereMonth('sale_date', Carbon::now()->month);
        }

        $sales = $query->latest('sale_date')->get();

        $total_usd = $sales->sum('total_usd');
        $total_sales_count = $sales->count();
        $average_ticket = $total_sales_count > 0 ? $total_usd / $total_sales_count : 0;

        $inactive_clients = Client::whereDoesntHave('sales', function ($q) {
            $q->where('sale_date', '>=', Carbon::now()->subDays(30));
        })->get();

        return view('livewire.reports', [
            'sales' => $sales,
            'total_usd' => $total_usd,
            'total_sales_count' => $total_sales_count,
            'average_ticket' => $average_ticket,
            'inactive_clients' => $inactive_clients
        ]);
    }
}