<?php
namespace App\Http\Controllers;

use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\TicketCategory;
use App\Models\TicketPriority;
use App\Models\TicketType;
use App\Models\NexusNotification;
use App\Services\TicketService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

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

    public function index()
    {
        $user    = auth()->user();
        $tickets = Ticket::with(['status','priority'])
            ->where('requester_id', $user->id)
            ->latest()
            ->paginate(10);
        $stats = [
            'open'   => Ticket::where('requester_id', $user->id)->open()->count(),
            'closed' => Ticket::where('requester_id', $user->id)->closed()->count(),
            'total'  => Ticket::where('requester_id', $user->id)->count(),
        ];
        return view('portal.index', compact('tickets', 'stats'));
    }

    public function create()
    {
        $categories = TicketCategory::where('active', true)->whereNull('parent_id')->with('children.children')->get();
        $priorities = TicketPriority::where('active', true)->get();
        $types      = TicketType::where('active', true)->get();
        return view('portal.create', compact('categories', 'priorities', 'types'));
    }

    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',
            'attachments'   => 'nullable|array|max:5',
            'attachments.*' => 'file|max:10240|mimes:jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,txt,zip',
        ]);

        $ticket = $this->ticketService->create($data, auth()->id());

        // Guardar adjuntos
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $this->saveAttachment($file, $ticket->id, null);
            }
        }

        return redirect()->route('portal.show', $ticket)
            ->with('success', "Tu solicitud {$ticket->number} fue registrada correctamente.");
    }

    public function show(Ticket $ticket)
    {
        abort_unless($ticket->requester_id === auth()->id(), 403);
        $ticket->load(['status','priority','category','type','comments.user','history','attachments.user']);
        return view('portal.show', compact('ticket'));
    }

    public function addComment(Request $request, Ticket $ticket)
    {
        abort_unless($ticket->requester_id === auth()->id(), 403);
        $request->validate([
            'body'          => 'required|string',
            'attachments'   => 'nullable|array|max:3',
            'attachments.*' => 'file|max:10240|mimes:jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,txt,zip',
        ]);

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

        // Guardar adjuntos del comentario
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $this->saveAttachment($file, $ticket->id, $comment->id);
            }
        }

        $ticket->addHistory('commented', 'Comentario del solicitante');
        return back()->with('success', 'Mensaje enviado.');
    }

    private function saveAttachment($file, int $ticketId, ?int $commentId): void
    {
        $stored = $file->store("tickets/{$ticketId}", 'public');
        TicketAttachment::create([
            'ticket_id'     => $ticketId,
            'comment_id'    => $commentId,
            'user_id'       => auth()->id(),
            'original_name' => $file->getClientOriginalName(),
            'stored_name'   => basename($stored),
            'path'          => $stored,
            'mime_type'     => $file->getMimeType(),
            'size'          => $file->getSize(),
        ]);
    }

    public function satisfaction(Request $request, Ticket $ticket)
    {
        abort_unless($ticket->requester_id === auth()->id(), 403);
        abort_unless($ticket->status->is_final, 422);
        $request->validate([
            'score'   => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:500',
        ]);
        $ticket->update([
            'satisfaction_score'   => $request->score,
            'satisfaction_comment' => $request->comment,
        ]);
        $ticket->addHistory('satisfaction', "Satisfacción calificada: {$request->score}/5");
        return back()->with('success', '¡Gracias por tu calificación!');
    }

    public function notifications()
    {
        $notifications = NexusNotification::forUser(auth()->id())->latest()->paginate(20);
        NexusNotification::forUser(auth()->id())->unread()->update(['read_at' => now()]);
        return view('portal.notifications', compact('notifications'));
    }
}
