<?php

namespace App\Livewire\Dashboard;

use App\Models\Customer;
use App\Models\ServiceOrder;
use App\Models\Appointment;
use App\Models\Vehicle;
use Carbon\Carbon;
use Livewire\Component;

class Overview extends Component
{
    public $stats = [];
    public $recentServiceOrders = [];
    public $todayAppointments = [];
    public $pendingOrders = [];

    public function mount()
    {
        $this->loadStats();
        $this->loadRecentData();
    }

    public function loadStats()
    {
        $this->stats = [
            'total_customers' => Customer::where('status', 'active')->count(),
            'total_vehicles' => Vehicle::where('status', 'active')->count(),
            'pending_orders' => ServiceOrder::whereIn('status', ['pending', 'in_progress'])->count(),
            'today_appointments' => Appointment::whereDate('scheduled_datetime', today())->count(),
            'monthly_revenue' => ServiceOrder::where('status', 'completed')
                ->whereMonth('completed_at', now()->month)
                ->sum('total_amount'),
            'orders_this_week' => ServiceOrder::whereBetween('created_at', [
                now()->startOfWeek(),
                now()->endOfWeek()
            ])->count(),
        ];
    }

    public function loadRecentData()
    {
        $this->recentServiceOrders = ServiceOrder::with(['customer', 'vehicle', 'assignedTechnician'])
            ->latest()
            ->take(5)
            ->get();

        $this->todayAppointments = Appointment::with(['customer', 'vehicle'])
            ->whereDate('scheduled_datetime', today())
            ->orderBy('scheduled_datetime')
            ->get();

        $this->pendingOrders = ServiceOrder::with(['customer', 'vehicle'])
            ->whereIn('status', ['pending', 'waiting_approval'])
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();
    }

    public function render()
    {
        return view('livewire.dashboard.overview');
    }
}
