<?php
namespace App\Http\Controllers;

use App\Models\Ticket;
use App\Models\TicketCategory;
use App\Models\TicketPriority;
use App\Models\TicketStatus;
use App\Models\TicketType;
use App\Models\Department;
use App\Models\User;
use App\Services\TicketService;
use Illuminate\Http\Request;

class TicketController extends Controller
{
    public function __construct(private TicketService $ticketService) {}

    // ── Lista de tickets ──────────────────────────────────────────────────────
    public function index()
    {
        $statuses   = TicketStatus::active()->get();
        $priorities = TicketPriority::active()->get();
        $categories = TicketCategory::active()->roots()->with('children')->get();
        $agents     = User::active()->agents()->orderBy('name')->get();
        return view('tickets.index', compact('statuses','priorities','categories','agents'));
    }

    // ── Formulario creación ───────────────────────────────────────────────────
    public function create()
    {
        $categories  = TicketCategory::active()->roots()->with('children')->get();
        $priorities  = TicketPriority::active()->get();
        $types       = TicketType::active()->get();
        $departments = Department::active()->orderBy('name')->get();
        $agents      = User::active()->agents()->orderBy('name')->get();
        return view('tickets.create', compact('categories','priorities','types','departments','agents'));
    }

    // ── Guardar ticket ────────────────────────────────────────────────────────
    public function store(Request $request)
    {
        $data = $request->validate([
            'title'         => 'required|string|max:255',
            'description'   => 'required|string',
            'priority_id'   => 'required|exists:ticket_priorities,id',
            'category_id'   => 'nullable|exists:ticket_categories,id',
            'type_id'       => 'nullable|exists:ticket_types,id',
            'department_id' => 'nullable|exists:departments,id',
            'assignee_id'   => 'nullable|exists:users,id',
        ]);

        $ticket = $this->ticketService->create($data, auth()->id());
        return redirect()->route('tickets.show', $ticket)->with('success', "Ticket {$ticket->number} creado.");
    }

    // ── Detalle del ticket ────────────────────────────────────────────────────
    public function show(Ticket $ticket)
    {
        $ticket->load(['status','priority','category','type','requester','assignee',
                       'department','comments.user','history.user','attachments']);
        $statuses   = TicketStatus::active()->get();
        $agents     = User::active()->agents()->orderBy('name')->get();
        $categories = TicketCategory::active()->roots()->with('children')->get();
        $priorities = TicketPriority::active()->get();
        return view('tickets.show', compact('ticket','statuses','agents','categories','priorities'));
    }

    // ── Formulario edición ────────────────────────────────────────────────────
    public function edit(Ticket $ticket)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $categories  = TicketCategory::active()->roots()->with('children')->get();
        $priorities  = TicketPriority::active()->get();
        $types       = TicketType::active()->get();
        $departments = Department::active()->orderBy('name')->get();
        $agents      = User::active()->agents()->orderBy('name')->get();
        return view('tickets.edit', compact('ticket','categories','priorities','types','departments','agents'));
    }

    // ── Actualizar ticket ─────────────────────────────────────────────────────
    public function update(Request $request, Ticket $ticket)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $data = $request->validate([
            'title'         => 'required|string|max:255',
            'description'   => 'required|string',
            'priority_id'   => 'required|exists:ticket_priorities,id',
            'category_id'   => 'nullable|exists:ticket_categories,id',
            'type_id'       => 'nullable|exists:ticket_types,id',
            'department_id' => 'nullable|exists:departments,id',
        ]);
        $ticket->update($data);
        $ticket->addHistory('updated', 'Ticket editado por ' . auth()->user()->name);
        return redirect()->route('tickets.show', $ticket)->with('success', 'Ticket actualizado.');
    }

    // ── Cambiar estado ────────────────────────────────────────────────────────
    public function changeStatus(Request $request, Ticket $ticket)
    {
        $request->validate(['status_id' => 'required|exists:ticket_statuses,id']);
        $this->ticketService->changeStatus($ticket, $request->status_id, $request->comment);
        return back()->with('success', 'Estado actualizado.');
    }

    // ── Asignar agente ────────────────────────────────────────────────────────
    public function assign(Request $request, Ticket $ticket)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $request->validate(['assignee_id' => 'nullable|exists:users,id']);
        $this->ticketService->assign($ticket, $request->assignee_id ?: null);
        return back()->with('success', 'Agente asignado.');
    }

    // ── Agregar comentario ────────────────────────────────────────────────────
    public function addComment(Request $request, Ticket $ticket)
    {
        $request->validate(['body' => 'required|string']);
        $isAgent = auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']);
        $isInternal = $isAgent && $request->boolean('is_internal');

        $comment = $ticket->comments()->create([
            'user_id'     => auth()->id(),
            'body'        => $request->body,
            'is_internal' => $isInternal,
        ]);

        // Registrar primera respuesta del agente
        if ($isAgent && !$ticket->first_response_at) {
            $ticket->update(['first_response_at' => now()]);
        }

        $ticket->addHistory('commented',
            ($isInternal ? '[Nota interna] ' : '') . 'Comentario de ' . auth()->user()->name);

        return back()->with('success', 'Comentario agregado.');
    }

    // ── Vista Kanban ──────────────────────────────────────────────────────────
    public function kanban()
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte','agente']), 403);
        $statuses = TicketStatus::active()->with(['tickets' => function($q) {
            $q->open()->with(['requester','priority','category','assignee'])
              ->orderBy('created_at', 'desc')->limit(30);
        }])->get();
        return view('tickets.kanban', compact('statuses'));
    }
}
