<?php
namespace App\Http\Controllers;

use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\Asset;
use App\Models\User;
use App\Models\NexusNotification;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $user    = auth()->user();
        $isAgent = $user->hasAnyRole(['admin','superadmin','jefe_soporte','agente']);

        // ── Métricas de tickets ───────────────────────────────────────────────
        $baseQuery = $isAgent
            ? Ticket::query()
            : Ticket::where('requester_id', $user->id);

        $ticketStats = [
            'total'      => (clone $baseQuery)->count(),
            'open'       => (clone $baseQuery)->open()->count(),
            'closed'     => (clone $baseQuery)->closed()->count(),
            'unassigned' => $isAgent ? Ticket::open()->unassigned()->count() : 0,
            'mine'       => $isAgent ? Ticket::open()->forAgent($user->id)->count() : 0,
        ];

        // ── SLA ───────────────────────────────────────────────────────────────
        $slaStats = [];
        if ($isAgent) {
            $total     = Ticket::closed()->whereNotNull('sla_resolution_due')->count();
            $onTime    = Ticket::closed()->where('sla_resolution_breached', false)->count();
            $slaStats  = [
                'compliance' => $total > 0 ? round(($onTime / $total) * 100) : 100,
                'breached'   => Ticket::open()->where('sla_resolution_breached', true)->count(),
                'warning'    => Ticket::open()
                    ->whereNotNull('sla_resolution_due')
                    ->where('sla_resolution_due', '>', now())
                    ->where('sla_resolution_due', '<=', now()->addHours(2))
                    ->count(),
            ];
        }

        // ── Tickets por estado (para gráfico) ─────────────────────────────────
        $byStatus = TicketStatus::active()
            ->withCount(['tickets' => function($q) use ($isAgent, $user) {
                if (!$isAgent) $q->where('requester_id', $user->id);
            }])
            ->get();

        // ── Carga por agente (solo agentes/admins) ────────────────────────────
        $agentLoad = [];
        if ($isAgent) {
            $agentLoad = User::role(['agente','jefe_soporte'])
                ->withCount(['assignedTickets' => fn($q) => $q->open()])
                ->orderByDesc('assigned_tickets_count')
                ->limit(8)
                ->get();
        }

        // ── Tickets recientes ─────────────────────────────────────────────────
        $recentTickets = (clone $baseQuery)
            ->with(['status','priority','assignee'])
            ->latest()
            ->limit(5)
            ->get();

        // ── Activos (solo agentes) ────────────────────────────────────────────
        $assetStats = [];
        if ($isAgent) {
            $assetStats = [
                'total'         => Asset::count(),
                'active'        => Asset::where('status','active')->count(),
                'in_repair'     => Asset::where('status','in_repair')->count(),
                'warranty_soon' => Asset::whereNotNull('warranty_until')
                    ->where('warranty_until', '>', now())
                    ->where('warranty_until', '<=', now()->addDays(30))
                    ->count(),
            ];
        }

        // ── Actividad reciente (7 días) ───────────────────────────────────────
        $weeklyCreated = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i);
            $weeklyCreated[] = [
                'day'   => $date->format('D'),
                'count' => (clone $baseQuery)->whereDate('created_at', $date)->count(),
            ];
        }

        return view('dashboard', compact(
            'user', 'isAgent', 'ticketStats', 'slaStats',
            'byStatus', 'agentLoad', 'recentTickets', 'assetStats', 'weeklyCreated'
        ));
    }
}
