<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Ticket;
use App\Models\TicketReply;
use App\Services\EmailService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TicketController extends Controller
{
    protected EmailService $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->emailService = $emailService;
    }

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $allCategories = \App\Models\TicketCategory::active()->ordered()->get();

        // If user is not logged in, show only categories that don't require login
        if (!auth()->check()) {
            $categories = $allCategories->where('requires_login', false);
        } else {
            $categories = $allCategories;
        }

        $requiresLoginCount = $allCategories->where('requires_login', true)->count();
        $totalCount = $allCategories->count();

        // If all categories require login and user is not logged in
        if ($totalCount > 0 && $requiresLoginCount === $totalCount && !auth()->check()) {
            return redirect()->route('login')->with('error', __('app.You must login to create a ticket.'));
        }

        // Get user's licenses for the related license dropdown
        $licenses = auth()->check() ? auth()->user()->licenses()->with('product')->get() : collect();

        return view('user.tickets.create', compact('categories', 'licenses'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        
        $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'],
            'product_version' => ['nullable','string'],
            'browser_info' => ['nullable','string'],
            'invoice_id' => ['nullable','exists:invoices,id'],
            'category_id' => ['required','exists:ticket_categories,id'],
        ]);

        $category = \App\Models\TicketCategory::find($validated['category_id']);
        if (!$category) {
            return back()->withErrors(['category_id' => 'Invalid category selected'])->withInput();
        }

        // If category requires login, ensure user is authenticated
        if ($category->requires_login && !Auth::check()) {
            return redirect()->route('login');
        }

        // If category requires a valid purchase code, validate it
        $license = null;
        if ($category->requires_valid_purchase_code) {
            if (empty($validated['purchase_code'])) {
                return back()->withErrors(['purchase_code' => 'Purchase code is required for this category'])->withInput();
            }

            // First try to find an existing license record
            $license = \App\Models\License::where('purchase_code', $validated['purchase_code'])->first();

            if (!$license) {
                // Try to verify via Envato service if available
                try {
                    $envatoService = app(\App\Services\EnvatoService::class);
                    $sale = $envatoService->verifyPurchase($validated['purchase_code']);
                } catch (\Throwable $e) {
                    $sale = null;
                }

                if (!$sale && !$license) {
                    return back()->withErrors(['purchase_code' => 'Invalid purchase code'])->withInput();
                }

                // Optionally create license record for authenticated user
                if ($sale && Auth::check()) {
                    $product = null;
                    if (!empty($validated['product_slug'])) {
                        $product = \App\Models\Product::where('slug', $validated['product_slug'])->first();
                    }

                    if ($product) {
                        $license = \App\Models\License::create([
                            'purchase_code' => $validated['purchase_code'],
                            'product_id' => $product->id,
                            'user_id' => Auth::id(),
                            'license_type' => 'regular',
                            'status' => 'active',
                            'support_expires_at' => data_get($sale, 'supported_until') ? date('Y-m-d', strtotime(data_get($sale, 'supported_until'))) : null,
                        ]);
                    }
                }
            }
        } else {
            // If purchase_code provided for non-requiring category, still attempt verification (optional)
            if (!empty($validated['purchase_code']) && Auth::check() && Auth::user()->hasEnvatoAccount()) {
                $envatoService = app(\App\Services\EnvatoService::class);
                $sale = $envatoService->verifyPurchase($validated['purchase_code']);
                if ($sale) {
                    $product = \App\Models\Product::where('slug', $validated['product_slug'])->first();
                    if ($product) {
                        $license = \App\Models\License::create([
                            'purchase_code' => $validated['purchase_code'],
                            'product_id' => $product->id,
                            'user_id' => Auth::id(),
                            'license_type' => 'regular',
                            'status' => 'active',
                            'support_expires_at' => data_get($sale, 'supported_until') ? date('Y-m-d', strtotime(data_get($sale, 'supported_until'))) : null,
                        ]);
                    }
                }
            }
        }

        $ticketData = [
            'user_id' => Auth::check() ? Auth::id() : null, // Can be null for guests
            'subject' => $validated['subject'],
            'priority' => $validated['priority'],
            'status' => 'open',
            'content' => $validated['content'],
            'license_id' => $license?->id,
            'category_id' => $category->id,
            'product_version' => $validated['product_version'] ?? null,
            'browser_info' => $validated['browser_info'] ?? null,
        ];

        // If created from an invoice, attach invoice and link license/product
        if (!empty($validated['invoice_id'])) {
            $invoice = \App\Models\Invoice::with('license','product')->find($validated['invoice_id']);
            if ($invoice) {
                $ticketData['invoice_id'] = $invoice->id;
                // prefer invoice license if exists
                if ($invoice->license) {
                    $ticketData['license_id'] = $invoice->license->id;
                }
                // if purchase_code not provided, try to set from invoice license
                if (empty($ticketData['purchase_code']) && $invoice->license?->purchase_code) {
                    $ticketData['purchase_code'] = $invoice->license->purchase_code;
                }
            }
        }

        if (!empty($validated['purchase_code'])) {
            $ticketData['purchase_code'] = $validated['purchase_code'];
        }

        $ticket = Ticket::create($ticketData);
        

        // Send email notifications
        try {

            // Send notification to user (if authenticated)
            if (Auth::check() && $ticket->user) {
                $userResult = $this->emailService->sendTicketCreated($ticket->user, [
                    'ticket_id' => $ticket->id,
                    'ticket_subject' => $ticket->subject,
                    'ticket_status' => $ticket->status,
                ]);
            }

            // Send notification to admin
            $adminResult = $this->emailService->sendAdminTicketCreated([
                'ticket_id' => $ticket->id,
                'ticket_subject' => $ticket->subject,
                'customer_name' => $ticket->user ? $ticket->user->name : 'Guest User',
                'customer_email' => $ticket->user ? $ticket->user->email : 'No email provided',
                'ticket_priority' => $ticket->priority,
            ]);
        } catch (\Exception $e) {
        }

        // Redirect based on user authentication status
        if (Auth::check()) {
            return redirect()->route('user.tickets.show', $ticket)->with('success', 'Ticket created successfully');
        } else {
            // For guests, redirect to support ticket view
            return redirect()->route('support.tickets.show', $ticket)->with('success', 'Ticket created successfully. You can view it using the ticket ID: ' . $ticket->id);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Ticket $ticket)
    {
        // Allow viewing ticket if it has no user_id (for guests) or if user is logged in and is ticket owner or admin
        abort_unless(
            !$ticket->user_id || // Guest ticket
            (Auth::check() && ($ticket->user_id === Auth::id() || Auth::user()->hasRole('admin'))), // Logged in user
            403
        );

        $ticket->load(['user','replies.user']);
        return view('user.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);
        $validated = $request->validate([
            'message' => ['required','string'],
        ]);
        
        $reply = TicketReply::create([
            'ticket_id' => $ticket->id,
            'user_id' => Auth::id(),
            'message' => $validated['message'],
        ]);

        // Send email notification to admin when user replies
        try {
            
            $result = $this->emailService->sendAdminTicketReply([
                'ticket_id' => $ticket->id,
                'ticket_subject' => $ticket->subject,
                'customer_name' => $ticket->user ? $ticket->user->name : 'Guest User',
                'customer_email' => $ticket->user ? $ticket->user->email : 'No email provided',
                'reply_message' => $validated['message'],
            ]);
            
        } catch (\Exception $e) {
        }

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