<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\{Ticket, Client, Visit, Invoice, WorkOrder};
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        $isTechnician = auth()->user()->isTechnician();
        $stats = [
            'tickets_open'       => Ticket::where('status','open')->count(),
            'tickets_inprogress' => Ticket::where('status','in_progress')->count(),
            'tickets_resolved'   => Ticket::where('status','resolved')->whereMonth('resolved_at',now()->month)->count(),
            'sla_breach'         => Ticket::where('sla_status','breach')->whereNotIn('status',['resolved','closed'])->count(),
            'clients_active'     => Client::where('is_active',1)->count(),
            'visits_today'       => Visit::where('visit_date',now()->toDateString())->where('status','scheduled')->count(),
            'invoices_overdue'   => $isTechnician ? null : Invoice::where('status','overdue')->count(),
            'revenue_month'      => $isTechnician ? null : Invoice::where('status','paid')->whereMonth('paid_at',now()->month)->sum('total'),
        ];

        $recentTickets = Ticket::with(['client','assignedTo'])
            ->orderByDesc('created_at')->limit(10)->get();

        $todayVisits = Visit::with(['client','technician'])
            ->where('visit_date',now()->toDateString())
            ->orderBy('visit_time_start')->get();

        $slaBreaches = Ticket::with('client')
            ->where('sla_status','breach')
            ->whereNotIn('status',['resolved','closed'])
            ->orderBy('sla_solve_deadline')->limit(5)->get();

        $ticketsByPriority = Ticket::whereNotIn('status',['resolved','closed'])
            ->select('priority', DB::raw('count(*) as count'))
            ->groupBy('priority')->pluck('count','priority');

        return view('admin.dashboard.index', compact('stats','recentTickets','todayVisits','slaBreaches','ticketsByPriority'));
    }
}
