<?php

namespace App\Http\Controllers;

use App\Models\Ticket;
use App\Models\Subscriber;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TicketController extends Controller
{
    public function index(Request $request)
    {
        $query = Ticket::with('subscriber');

        if ($request->filled('status') && $request->status !== 'All') {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('ticket_number', 'like', "%{$search}%")
                  ->orWhere('subject', 'like', "%{$search}%")
                  ->orWhere('subscriber_name', 'like', "%{$search}%");
            });
        }

        $openCount = Ticket::where('status', 'Open')->count();
        $inProgressCount = Ticket::where('status', 'In Progress')->count();
        $urgentCount = Ticket::where('status', 'Urgent')->orWhere('priority', 'Critical')->count();
        $resolvedCount = Ticket::where('status', 'Resolved')->orWhere('status', 'Closed')->count();

        $tickets = $query->orderBy('updated_at', 'desc')->paginate(10);
        $subscribers = Subscriber::orderBy('name', 'asc')->get();

        return view('admin.tickets.index', compact(
            'tickets',
            'subscribers',
            'openCount',
            'inProgressCount',
            'urgentCount',
            'resolvedCount'
        ));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'subscriber_id' => 'nullable|exists:subscribers,id',
            'description' => 'required|string',
            'assignee' => 'nullable|string',
            'priority' => 'required|in:Low,Normal,High,Critical',
            'status' => 'required|in:Open,In Progress,Urgent,Resolved,Closed',
        ]);

        $lastTicket = Ticket::orderBy('id', 'desc')->first();
        $nextId = $lastTicket ? ($lastTicket->id + 1) : 1;
        $ticketNum = 'TCK-' . str_pad($nextId, 5, '0', STR_PAD_LEFT);

        $subscriberName = null;
        if (!empty($request->subscriber_id)) {
            $sub = Subscriber::find($request->subscriber_id);
            $subscriberName = $sub ? $sub->name : null;
        }

        Ticket::create([
            'ticket_number' => $ticketNum,
            'subscriber_id' => $request->subscriber_id,
            'subscriber_name' => $subscriberName ?? 'Guest / Walk-in',
            'subject' => $request->subject,
            'description' => $request->description,
            'assignee' => $request->assignee ?? 'Unassigned',
            'priority' => $request->priority,
            'status' => $request->status,
            'notify_create' => $request->has('notify_create'),
            'notify_resolve' => $request->has('notify_resolve'),
        ]);

        return redirect()->route('admin.tickets.index')->with('success', "Ticket {$ticketNum} opened successfully!");
    }

    public function updateStatus(Request $request, Ticket $ticket)
    {
        $ticket->update(['status' => $request->status]);
        return redirect()->route('admin.tickets.index')->with('success', "Ticket {$ticket->ticket_number} status updated to {$request->status}.");
    }
}
