<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SRO_VT_SHARD\RefObjCommon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class ItemDetailsController extends Controller
{
    /**
     * Get detailed item information for tooltip display
     *
     * @param int $itemId
     * @return \Illuminate\Http\Response
     */
    public function getItemDetails($itemId)
    {
        try {
            // Log the request for debugging
            Log::info("Fetching item details for ID: {$itemId}");

            // Find the item by ID
            $refObj = RefObjCommon::find($itemId);

            if (!$refObj) {
                Log::warning("Item not found for ID: {$itemId}");

                // Return simple HTML instead of Blade view for debugging
                $html = '<div class="tooltip-error">Item not found (ID: ' . $itemId . ')</div>';
                return response($html, 404)->header('Content-Type', 'text/html');
            }

            // Get complete item information
            $itemInfo = $refObj->getCompleteInfo();
            Log::info("Successfully retrieved item info for ID: {$itemId}", ['item_name' => $itemInfo['display_name'] ?? 'Unknown']);

            // For now, return JSON to debug the data
            return response()->json([
                'success' => true,
                'item' => $itemInfo,
                'debug' => 'Data retrieved successfully'
            ]);

        } catch (\Exception $e) {
            // Log error and return JSON error for easier debugging
            Log::error("Error fetching item details for ID {$itemId}: " . $e->getMessage());
            Log::error("Stack trace: " . $e->getTraceAsString());

            return response()->json([
                'error' => true,
                'message' => $e->getMessage(),
                'item_id' => $itemId,
                'trace' => config('app.debug') ? $e->getTraceAsString() : null
            ], 500);
        }
    }

    /**
     * Get item details as JSON (alternative endpoint)
     *
     * @param int $itemId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getItemDetailsJson($itemId)
    {
        try {
            $refObj = RefObjCommon::find($itemId);

            if (!$refObj) {
                return response()->json([
                    'error' => 'Item not found',
                    'item_id' => $itemId
                ], 404);
            }

            $itemInfo = $refObj->getCompleteInfo();

            return response()->json([
                'success' => true,
                'item' => $itemInfo
            ]);

        } catch (\Exception $e) {
            Log::error("Error fetching item details JSON for ID {$itemId}: " . $e->getMessage());

            return response()->json([
                'error' => 'Internal server error',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Search items by name (for autocomplete or search features)
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchItems(Request $request)
    {
        try {
            $query = $request->get('q', '');
            $limit = min($request->get('limit', 10), 50); // Max 50 results

            if (strlen($query) < 2) {
                return response()->json([
                    'results' => [],
                    'message' => 'Query too short'
                ]);
            }

            // Search in RefObjCommon by name patterns
            $items = RefObjCommon::where(function($q) use ($query) {
                $q->where('ObjName128', 'LIKE', "%{$query}%")
                  ->orWhere('CodeName128', 'LIKE', "%{$query}%")
                  ->orWhere('NameStrID128', 'LIKE', "%{$query}%");
            })
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->ID,
                    'name' => $item->getDisplayName(),
                    'code_name' => $item->CodeName128,
                    'rarity' => $item->getRarityName(),
                    'icon_path' => $item->getIconPath(),
                    'type' => $item->getItemType()
                ];
            });

            return response()->json([
                'results' => $items,
                'count' => $items->count(),
                'query' => $query
            ]);

        } catch (\Exception $e) {
            Log::error("Error searching items: " . $e->getMessage());

            return response()->json([
                'error' => 'Search failed',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
