<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\Product;
use App\Models\Ticket;
use App\Services\EnvatoService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class TicketApiController extends Controller
{
    protected $envatoService;

    public function __construct(EnvatoService $envatoService)
    {
        $this->envatoService = $envatoService;
    }

    /**
     * Display a listing of tickets (API)
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Ticket::with(['user', 'category', 'invoice.product']);

            // Apply filters
            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }

            if ($request->filled('priority')) {
                $query->where('priority', $request->priority);
            }

            if ($request->filled('category_id')) {
                $query->where('category_id', $request->category_id);
            }

            if ($request->filled('user_id')) {
                $query->where('user_id', $request->user_id);
            }

            // Search
            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('subject', 'like', "%{$search}%")
                      ->orWhere('content', 'like', "%{$search}%")
                      ->orWhereHas('user', function ($userQuery) use ($search) {
                          $userQuery->where('name', 'like', "%{$search}%")
                                   ->orWhere('email', 'like', "%{$search}%");
                      });
                });
            }

            // Pagination
            $perPage = $request->get('per_page', 15);
            $tickets = $query->latest()->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $tickets->items(),
                'pagination' => [
                    'current_page' => $tickets->currentPage(),
                    'last_page' => $tickets->lastPage(),
                    'per_page' => $tickets->perPage(),
                    'total' => $tickets->total(),
                    'from' => $tickets->firstItem(),
                    'to' => $tickets->lastItem(),
                ]
            ]);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Unable to fetch tickets. Please try again later.'
            ], 500);
        }
    }

    /**
     * Verify purchase code for ticket creation
     */
    public function verifyPurchaseCode(string $purchaseCode): JsonResponse
    {
        try {
            $purchaseCode = trim($purchaseCode);
            
            // Validate purchase code format
            if (empty($purchaseCode) || strlen($purchaseCode) < 10) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid purchase code format'
                ], 400);
            }

            // First, check if this purchase code exists in our database
            $existingLicense = License::with('product')->where('purchase_code', $purchaseCode)->first();

            if ($existingLicense && $existingLicense->product) {
                return response()->json([
                    'success' => true,
                    'product' => [
                        'slug' => $existingLicense->product->slug,
                        'name' => $existingLicense->product->name,
                        'version' => $existingLicense->product->version ?? '1.0.0'
                    ],
                    'license_exists' => true,
                    'license_id' => $existingLicense->id
                ]);
            }

            // If not found in database, try Envato API
            try {
                $sale = $this->envatoService->verifyPurchase($purchaseCode);

                if ($sale && isset($sale['item'])) {
                    $productSlug = data_get($sale, 'item.slug');
                    $productName = data_get($sale, 'item.name');

                    return response()->json([
                        'success' => true,
                        'product' => [
                            'slug' => $productSlug,
                            'name' => $productName,
                            'version' => '1.0.0'
                        ],
                        'license_exists' => false,
                        'sale' => $sale
                    ]);
                }
            } catch (\Throwable $envatoError) {
                // Silently handle Envato API errors
            }

            return response()->json([
                'success' => false,
                'message' => 'Purchase code not found or invalid'
            ], 400);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Unable to verify purchase code. Please try again later.'
            ], 500);
        }
    }
}
