<?php

namespace App\Http\Controllers;

use App\Models\Ticket;
use App\Models\TicketReply;
use App\Services\LicenseAutoRegistrationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TicketController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $tickets = Ticket::where('user_id', Auth::id())->latest()->paginate(15);
        return view('tickets.index', compact('tickets'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('tickets.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, LicenseAutoRegistrationService $licenseService)
    {
        $validated = $request->validate([
            'subject' => ['required','string','max:255'],
            'priority' => ['required','in:low,medium,high'],
            'content' => ['required','string'],
            'purchase_code' => ['nullable','string'],
            'product_slug' => ['nullable','string'],
        ]);

        // Auto-register license if purchase code is provided
        $license = null;
        if (!empty($validated['purchase_code'])) {
            $productId = null;
            if (!empty($validated['product_slug'])) {
                $product = \App\Models\Product::where('slug', $validated['product_slug'])->first();
                $productId = $product?->id;
            }

            $registrationResult = $licenseService->autoRegisterLicense($validated['purchase_code'], $productId);

            if ($registrationResult['success']) {
                $license = $registrationResult['license'];
            } else {
                // If license registration failed, still allow ticket creation but show warning
                // You might want to add this to the session flash or log it
            }
        }

        $ticket = Ticket::create([
            'user_id' => Auth::id(),
            'subject' => $validated['subject'],
            'priority' => $validated['priority'],
            'status' => 'open',
            'content' => $validated['content'],
            'license_id' => $license?->id,
        ]);

        return redirect()->route('tickets.show', $ticket)->with('success', 'Ticket created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(Ticket $ticket)
    {
        abort_unless($ticket->user_id === Auth::id() || Auth::user()?->hasRole('admin'), 403);
        $ticket->load(['user','replies.user']);
        return view('tickets.show', compact('ticket'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Ticket $ticket)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Ticket $ticket)
    {
        abort_unless($ticket->user_id === Auth::id() || Auth::user()?->hasRole('admin'), 403);
        $validated = $request->validate([
            'subject' => ['sometimes','string','max:255'],
            'priority' => ['sometimes','in:low,medium,high'],
            'status' => ['sometimes','in:open,pending,resolved,closed'],
            'content' => ['sometimes','string'],
        ]);

        $ticket->update($validated);

        return back()->with('success', 'Ticket updated');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Ticket $ticket)
    {
        abort_unless($ticket->user_id === Auth::id() || Auth::user()?->hasRole('admin'), 403);
        $ticket->delete();
        return redirect()->route('tickets.index')->with('success', 'Ticket deleted');
    }

    public function reply(Request $request, Ticket $ticket)
    {
        abort_unless($ticket->user_id === Auth::id() || Auth::user()?->hasRole('admin'), 403);
        
        // Check if ticket is already closed
        if ($ticket->status === 'closed') {
            return back()->with('error', 'Cannot reply to a closed ticket');
        }
        
        $validated = $request->validate([
            'message' => ['required','string'],
            'close_ticket' => ['sometimes','boolean'],
            'action' => ['sometimes','in:reply,reply_and_close'],
        ]);
        
        // Create the reply
        $reply = TicketReply::create([
            'ticket_id' => $ticket->id,
            'user_id' => Auth::id(),
            'message' => $validated['message'],
        ]);

        // Handle closing the ticket
        $shouldClose = false;
        $message = 'Reply added';
        
        if ($request->has('action') && $request->action === 'reply_and_close') {
            $shouldClose = true;
            $message = 'Reply added and ticket closed';
        } elseif ($request->has('close_ticket') && $request->close_ticket) {
            $shouldClose = true;
            $message = 'Reply added and ticket closed';
        }
        
        if ($shouldClose) {
            $ticket->update(['status' => 'closed']);
        }

        return back()->with('success', $message);
    }
}
