<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Helpers\InventoryHelper;
use App\Models\SRO_VT_SHARD\Char;

class InventoryController extends Controller
{
    /**
     * Show character inventory page
     *
     * @param Request $request
     * @param int $charId
     * @return \Illuminate\View\View
     */
    public function show(Request $request, $charId)
    {
        try {
            // Get character information
            $character = Char::where('CharID', $charId)->first();

            if (!$character) {
                abort(404, 'Character not found');
            }

            // Get character equipment
            $equipmentData = InventoryHelper::getCharacterEquipment($charId);

            // Format equipment data for the component
            $formattedEquipment = [];
            foreach ($equipmentData as $item) {
                $formattedEquipment[] = [
                    'slot' => $item['slot'],
                    'item_id' => $item['item_id'],
                    'name' => $item['name'],
                    'icon_path' => $item['icon_path'],
                    'rarity' => $item['rarity'],
                    'opt_level' => $item['opt_level']
                ];
            }

            return view('inventory.show', [
                'character' => $character,
                'equipment' => $formattedEquipment,
                'charId' => $charId
            ]);

        } catch (\Exception $e) {
            Log::error('Error loading inventory page: ' . $e->getMessage());
            return back()->with('error', 'Error loading character inventory');
        }
    }

    /**
     * Get character equipment as JSON (for AJAX requests)
     *
     * @param Request $request
     * @param int $charId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEquipment(Request $request, $charId)
    {
        try {
            // Validate character exists
            $character = Char::where('CharID', $charId)->first();

            if (!$character) {
                return response()->json([
                    'success' => false,
                    'message' => 'Character not found'
                ], 404);
            }

            // Get equipment data
            $equipmentData = InventoryHelper::getCharacterEquipment($charId);

            // Process the data for frontend
            $processedEquipment = [];
            foreach ($equipmentData as $item) {
                $processedEquipment[] = [
                    'slot' => $item['slot'],
                    'item_id' => $item['item_id'],
                    'name' => $item['name'],
                    'icon_path' => $item['icon_path'],
                    'image_url' => InventoryHelper::processIconPath($item['icon_path']),
                    'rarity' => $item['rarity'],
                    'grade' => InventoryHelper::getItemGrade($item['rarity']),
                    'opt_level' => $item['opt_level'],
                    'slot_name' => InventoryHelper::getSlotName($item['slot'])
                ];
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'character_id' => $charId,
                    'character_name' => $character->CharName16,
                    'equipment' => $processedEquipment
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Error fetching equipment data: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Error fetching equipment data'
            ], 500);
        }
    }

    /**
     * Get full character inventory as JSON
     *
     * @param Request $request
     * @param int $charId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInventory(Request $request, $charId)
    {
        try {
            // Validate character exists
            $character = Char::where('CharID', $charId)->first();

            if (!$character) {
                return response()->json([
                    'success' => false,
                    'message' => 'Character not found'
                ], 404);
            }

            // Get full inventory data
            $inventoryData = InventoryHelper::getCharacterInventory($charId);

            // Separate equipment and inventory items
            $equipment = [];
            $inventory = [];

            foreach ($inventoryData as $item) {
                $processedItem = [
                    'slot' => $item['slot'],
                    'item_id' => $item['item_id'],
                    'name' => $item['name'],
                    'icon_path' => $item['icon_path'],
                    'image_url' => InventoryHelper::processIconPath($item['icon_path']),
                    'rarity' => $item['rarity'],
                    'grade' => InventoryHelper::getItemGrade($item['rarity']),
                    'opt_level' => $item['opt_level'],
                    'variance' => $item['variance'],
                    'type_ids' => $item['type_ids'],
                    'slot_name' => InventoryHelper::getSlotName($item['slot'])
                ];

                if (InventoryHelper::isEquipmentSlot($item['slot'])) {
                    $equipment[] = $processedItem;
                } else {
                    $inventory[] = $processedItem;
                }
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'character_id' => $charId,
                    'character_name' => $character->CharName16,
                    'equipment' => $equipment,
                    'inventory' => $inventory
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Error fetching inventory data: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Error fetching inventory data'
            ], 500);
        }
    }
}
