<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Log;
use App\Helpers\InventoryHelper;
use App\Models\SRO_VT_SHARD\Char;

class PlayerModalWithInventory extends Component
{
    public $isOpen = false;
    public $playerData = null;
    public $equipment = [];
    public $loading = false;

    protected $listeners = [
        'player-modal-open' => 'openModal',
        'player-modal-close' => 'closeModal'
    ];

    public function openModal($playerData)
    {
        $this->loading = true;
        $this->playerData = $playerData;
        $this->isOpen = true;

        // Load equipment data
        $this->loadEquipment($playerData['charName'] ?? null);

        $this->loading = false;
    }

    public function closeModal()
    {
        $this->isOpen = false;
        $this->playerData = null;
        $this->equipment = [];
        $this->loading = false;
    }

    private function loadEquipment($charName)
    {
        try {
            if (!$charName) {
                $this->equipment = [];
                return;
            }

            // Find character by name
            $character = Char::where('CharName16', $charName)->first();

            if (!$character) {
                $this->equipment = [];
                return;
            }

            // Get enhanced equipment data with proper opt_level values
            $equipmentData = InventoryHelper::getEnhancedCharacterEquipment($character->CharID);

            // Debug: Log raw equipment data
            Log::info('🔍 Raw equipment data for ' . $charName, ['equipment_data' => $equipmentData]);

            // Format for component
            $this->equipment = [];
            foreach ($equipmentData as $item) {
                $this->equipment[] = [
                    'slot' => $item['slot'],
                    'item_id' => $item['item_id'],
                    'name' => $item['name'],
                    'icon_path' => $item['icon_path'],
                    'rarity' => $item['rarity'],
                    'opt_level' => $item['opt_level'],
                    'ref_obj_id' => $item['ref_obj_id'] ?? $item['RefItemID'] ?? null
                ];
            }

            // Debug: Log processed equipment
            Log::info('🔍 Processed equipment for ' . $charName, ['processed_equipment' => $this->equipment]);

        } catch (\Exception $e) {
            Log::error('Error loading equipment in modal: ' . $e->getMessage());
            $this->equipment = [];
        }
    }

    public function render()
    {
        return view('livewire.player-modal-with-inventory');
    }
}
