<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\SupportTicket;
use App\Models\SupportTicketReply;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    public function index()
    {
        $tickets = auth()->user()->supportTickets()
            ->with(['product','replies'])
            ->latest()
            ->paginate((int) setting('items_per_page', 15));

        $stats = [
            'open'        => auth()->user()->supportTickets()->where('status','open')->count(),
            'in_progress' => auth()->user()->supportTickets()->where('status','in_progress')->count(),
            'resolved'    => auth()->user()->supportTickets()->whereIn('status',['resolved','closed'])->count(),
        ];

        return view('customer.support.index', compact('tickets','stats'));
    }

    public function create()
    {
        $products = auth()->user()->licenses()
            ->where('status','active')
            ->with('product')
            ->get()
            ->pluck('product')
            ->unique('id');

        return view('customer.support.create', compact('products'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'subject'     => 'required|string|max:255',
            'description' => 'required|string|min:20',
            'category'    => 'required|in:general,billing,technical,license',
            'priority'    => 'required|in:low,medium,high,urgent',
            'product_id'  => 'nullable|exists:products,id',
        ]);

        $ticket = SupportTicket::create([
            'ticket_number' => SupportTicket::generateNumber(),
            'user_id'       => auth()->id(),
            'subject'       => $data['subject'],
            'description'   => $data['description'],
            'category'      => $data['category'],
            'priority'      => $data['priority'],
            'product_id'    => $data['product_id'] ?? null,
            'status'        => 'open',
            'last_reply_at' => now(),
        ]);

        return redirect()->route('customer.support.show', $ticket)
            ->with('success', "Ticket {$ticket->ticket_number} created. We'll respond shortly.");
    }

    public function show(SupportTicket $ticket)
    {
        abort_if($ticket->user_id !== auth()->id(), 403);
        $ticket->load(['product','replies.user','assignee']);
        return view('customer.support.show', compact('ticket'));
    }

    public function reply(Request $request, SupportTicket $ticket)
    {
        abort_if($ticket->user_id !== auth()->id(), 403);
        abort_if(in_array($ticket->status, ['resolved','closed']), 422, 'Ticket is closed.');

        $request->validate(['content' => 'required|string|min:5']);

        SupportTicketReply::create([
            'ticket_id'      => $ticket->id,
            'user_id'        => auth()->id(),
            'content'        => $request->content,
            'is_admin_reply' => false,
        ]);

        $ticket->update(['last_reply_at' => now(), 'status' => 'open']);

        return back()->with('success', 'Reply sent.');
    }

    public function close(SupportTicket $ticket)
    {
        abort_if($ticket->user_id !== auth()->id(), 403);
        $ticket->update(['status' => 'closed', 'resolved_at' => now()]);
        return back()->with('success', 'Ticket closed.');
    }
}
