<?php
/**
 * Perfil de jugador — Nexora V6 Custom
 * Advanced public profile: portrait + read-only equipped items.
 */
if (!defined('access') || !access) {
    die();
}

$h = function ($s) {
    return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
};

$pageTitle = (function_exists('lang') && lang('profiles_txt_2', true)) ? lang('profiles_txt_2', true) : 'Character Profile';

echo '<div class="nexora-profile-page nexora-profile-player">';
echo '<header class="nexora-profile-page-header"><h1 class="nexora-profile-page-title">' . $h($pageTitle) . '</h1><span class="nexora-profile-page-line" aria-hidden="true"></span></header>';

loadModuleConfigs('profiles');
if (!mconfig('active')) {
    message('error', lang('error_47', true));
    echo '</div>';
    return;
}
if (!isset($_GET['req'])) {
    message('error', lang('error_25', true));
    echo '</div>';
    return;
}

try {
    $weProfiles = new weProfiles();
    $weProfiles->setType('player');
    $weProfiles->setRequest($_GET['req']);
    $cData = $weProfiles->data();

    $classCode = (int) $cData[2];
    $charClassKey = isset($custom['character_class'][$classCode][1]) ? $custom['character_class'][$classCode][1] : '';
    $charClassName = isset($custom['character_class'][$classCode][0]) ? $custom['character_class'][$classCode][0] : '';
    $hasCmd = isset($custom['character_class'][$classCode]['base_stats']['cmd'])
        && (int) $custom['character_class'][$classCode]['base_stats']['cmd'] > 0;

    $onlineStatus = 0;
    $onlineCharactersCache = loadCache('online_characters.cache');
    if (is_array($onlineCharactersCache) && in_array($cData[1], $onlineCharactersCache, true)) {
        $onlineStatus = 1;
    }

    $profileRealm = class_exists('NexoraRealm') ? NexoraRealm::active() : '';
    $profileRealmLabel = class_exists('NexoraRealm') ? NexoraRealm::label($profileRealm) : '';
    $bannerUrl = class_exists('ProfileEquipment', false)
        ? ProfileEquipment::profileCardBannerUrl($classCode)
        : '';
    $portraitUrl = class_exists('ProfileEquipment', false)
        ? ProfileEquipment::profilePortraitUrl($classCode)
        : (function_exists('getPlayerClassAvatar') ? getPlayerClassAvatar($classCode, false, false) : '');
    $heroStyle = $bannerUrl !== ''
        ? ' style="--nex-player-banner:url(' . $h($bannerUrl) . ')"'
        : '';

    // Equipment is deliberately separate from the normal profile cache.
    // Inventory is read only on this page and may refresh independently.
    $equipment = null;
    $equipmentError = '';
    if (class_exists('ProfileEquipment', false)) {
        try {
            $equipmentService = new ProfileEquipment($cData[1], $profileRealm);
            $equipment = $equipmentService->getPublicEquipment();
        } catch (Exception $equipmentException) {
            $equipmentError = 'El perfil está disponible, pero el equipamiento no pudo consultarse en este momento.';
        }
    } else {
        $equipmentError = 'El módulo de equipamiento no está disponible.';
    }

    $equipmentItems = array();
    if (is_array($equipment) && isset($equipment['items']) && is_array($equipment['items'])) {
        foreach ($equipment['items'] as $eqItem) {
            if (isset($eqItem['slot'])) $equipmentItems[$eqItem['slot']] = $eqItem;
        }
    }

    $equipmentSlots = class_exists('NexoraItemDecoder', false)
        ? NexoraItemDecoder::slotDefinitions()
        : array();

    $equipmentApi = __BASE_URL__ . 'api/character-equipment.php?req=' . rawurlencode(base64url_encode($cData[1]));
    if ($profileRealm !== '') $equipmentApi .= '&realm=' . rawurlencode($profileRealm);

    // Zen travels with the profile cache (index 15), avoiding a second Character SELECT *.
    $zenDisplay = isset($cData[15]) ? number_format((int) $cData[15]) : '—';

    $statCap = 32767;
    $statPct = function ($v) use ($statCap) {
        $v = (int) $v;
        if ($v < 0) $v = 0;
        if ($v > $statCap) $v = $statCap;
        return (int) round(100 * $v / $statCap);
    };

    $renderEquipmentSlot = function ($slot, $item) use ($h) {
        $occupied = is_array($item) && !empty($item['occupied']);
        $slotKey = isset($slot['key']) ? $slot['key'] : 'slot';
        $slotLabel = isset($slot['label']) ? $slot['label'] : 'Slot';
        $rarity = $occupied && isset($item['rarity']) ? $item['rarity'] : 'empty';
        $name = $occupied && isset($item['name']) ? $item['name'] : $slotLabel;
        $image = $occupied && isset($item['image']) ? $item['image'] : '';
        $details = $occupied && isset($item['details']) && is_array($item['details']) ? $item['details'] : array();
        $level = $occupied && isset($item['level']) ? (int)$item['level'] : null;
        ?>
        <button type="button"
            class="nexora-equipment-slot nexora-equipment-slot--<?php echo $h($slotKey); ?> rarity-<?php echo $h($rarity); ?><?php echo $occupied ? ' is-occupied' : ' is-empty'; ?>"
            data-equipment-slot="<?php echo $h($slotKey); ?>"
            aria-label="<?php echo $h($occupied ? $name : $slotLabel . ' vacío'); ?>">
            <span class="nexora-equipment-slot-label"><?php echo $h($slotLabel); ?></span>
            <span class="nexora-equipment-slot-visual">
                <?php if ($occupied && $image !== '') { ?>
                    <img src="<?php echo $h($image); ?>" alt="<?php echo $h($name); ?>" loading="lazy" decoding="async">
                <?php } elseif ($occupied) { ?>
                    <span class="nexora-equipment-item-code"><?php echo $h(isset($item['code']) ? $item['code'] : '?'); ?></span>
                <?php } else { ?>
                    <span class="nexora-equipment-empty-mark" aria-hidden="true">+</span>
                <?php } ?>
            </span>
            <?php if ($occupied) { ?>
            <span class="nexora-equipment-tooltip" role="tooltip">
                <strong class="nexora-equipment-tooltip-name"><?php echo $h($name); ?></strong>
                <?php if ($level !== null) { ?><span class="nexora-equipment-tooltip-level">+<?php echo (int)$level; ?></span><?php } ?>
                <?php if (!empty($details)) { ?>
                <span class="nexora-equipment-tooltip-details">
                    <?php foreach ($details as $detail) { ?><span><?php echo $h($detail); ?></span><?php } ?>
                </span>
                <?php } ?>
            </span>
            <?php } ?>
        </button>
        <?php
    };
    ?>
    <article class="nexora-player-card <?php echo $h($charClassKey); ?>">
        <div class="nexora-player-layout">
            <div class="nexora-player-col nexora-player-col--hero">
                <div class="nexora-player-hero"<?php echo $heroStyle; ?>>
                    <div class="nexora-player-hero-glow" aria-hidden="true"></div>
                    <div class="nexora-player-avatar">
                        <?php if ($portraitUrl !== '') { ?>
                            <img class="nexora-player-avatar-image" src="<?php echo $h($portraitUrl); ?>" alt="<?php echo $h($charClassName); ?>" decoding="async">
                        <?php } else { ?>
                            <span class="nexora-player-avatar-letter"><?php echo $h(substr($charClassKey !== '' ? $charClassKey : '?', 0, 2)); ?></span>
                        <?php } ?>
                    </div>
                    <h2 class="nexora-player-name"><?php echo $h($cData[1]); ?></h2>
                    <p class="nexora-player-class"><?php echo $h($charClassName); ?></p>
                    <span class="nexora-player-status <?php echo $onlineStatus ? 'is-online' : 'is-offline'; ?>">
                        <?php echo $onlineStatus ? $h(lang('profiles_txt_18', true)) : $h(lang('profiles_txt_19', true)); ?>
                    </span>
                </div>

                <div class="nexora-player-highlights">
                    <div class="nexora-player-highlight">
                        <span class="nexora-player-highlight-label"><?php echo $h(lang('profiles_txt_7', true)); ?></span>
                        <span class="nexora-player-highlight-value"><?php echo $h(number_format((int) $cData[3])); ?></span>
                    </div>
                    <div class="nexora-player-highlight">
                        <span class="nexora-player-highlight-label"><?php echo $h(lang('profiles_txt_20', true)); ?></span>
                        <span class="nexora-player-highlight-value"><?php echo $h(number_format((int) $cData[14])); ?></span>
                    </div>
                    <div class="nexora-player-highlight">
                        <span class="nexora-player-highlight-label"><?php echo $h(lang('profiles_txt_15', true)); ?></span>
                        <span class="nexora-player-highlight-value"><?php echo $h(number_format((int) $cData[10])); ?></span>
                    </div>
                </div>

                <?php if (check_value($cData[12])) { ?>
                <div class="nexora-player-guild-strip">
                    <span class="nexora-player-guild-label"><?php echo $h(lang('profiles_txt_16', true)); ?></span>
                    <span class="nexora-player-guild-value"><?php echo guildProfile($cData[12]); ?></span>
                </div>
                <?php } ?>

                <div class="nexora-player-zen-strip">
                    <span class="nexora-player-zen-label">ZEN</span>
                    <span class="nexora-player-zen-value"><?php echo $h($zenDisplay); ?></span>
                </div>
            </div>

            <div class="nexora-player-col nexora-player-col--stats">
                <section class="nexora-player-section">
                    <h3 class="nexora-player-section-title"><?php echo $h(nexora_lang('nexora_prof_battle', 'Registro de batalla')); ?></h3>
                    <div class="nexora-player-stats">
                        <?php if (check_value($cData[4])) { ?>
                        <div class="nexora-player-stat">
                            <span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_8', true)); ?></span>
                            <span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[4])); ?></span>
                        </div>
                        <?php } ?>
                        <?php if (check_value($cData[11])) { ?>
                        <div class="nexora-player-stat">
                            <span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_9', true)); ?></span>
                            <span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[11])); ?></span>
                        </div>
                        <?php } ?>
                        <div class="nexora-player-stat">
                            <span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_15', true)); ?></span>
                            <span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[10])); ?></span>
                        </div>
                        <?php if ($profileRealmLabel !== '') { ?>
                        <div class="nexora-player-stat">
                            <span class="nexora-player-stat-label">Reino</span>
                            <span class="nexora-player-stat-value"><?php echo $h($profileRealmLabel); ?></span>
                        </div>
                        <?php } ?>
                    </div>
                </section>

                <section class="nexora-player-section">
                    <h3 class="nexora-player-section-title"><?php echo $h(nexora_lang('nexora_prof_attributes', 'Atributos')); ?></h3>
                    <div class="nexora-player-attr-bars" aria-hidden="true">
                        <span class="nexora-player-attr-bar" title="STR"><i style="width:<?php echo (int) $statPct($cData[5]); ?>%;--nex-bar:#e04252"></i></span>
                        <span class="nexora-player-attr-bar" title="AGI"><i style="width:<?php echo (int) $statPct($cData[6]); ?>%;--nex-bar:#4d8cff"></i></span>
                        <span class="nexora-player-attr-bar" title="VIT"><i style="width:<?php echo (int) $statPct($cData[7]); ?>%;--nex-bar:#3ecf7b"></i></span>
                        <span class="nexora-player-attr-bar" title="ENE"><i style="width:<?php echo (int) $statPct($cData[8]); ?>%;--nex-bar:#f59e32"></i></span>
                    </div>
                    <div class="nexora-player-stats nexora-player-stats--attrs">
                        <div class="nexora-player-stat"><span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_10', true)); ?></span><span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[5])); ?></span></div>
                        <div class="nexora-player-stat"><span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_11', true)); ?></span><span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[6])); ?></span></div>
                        <div class="nexora-player-stat"><span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_12', true)); ?></span><span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[7])); ?></span></div>
                        <div class="nexora-player-stat"><span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_13', true)); ?></span><span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[8])); ?></span></div>
                        <?php if ($hasCmd) { ?>
                        <div class="nexora-player-stat"><span class="nexora-player-stat-label"><?php echo $h(lang('profiles_txt_14', true)); ?></span><span class="nexora-player-stat-value"><?php echo $h(number_format((int) $cData[9])); ?></span></div>
                        <?php } ?>
                    </div>
                </section>
            </div>
        </div>

        <section class="nexora-player-section nexora-equipment-section"
            data-equipment-root
            data-equipment-api="<?php echo $h($equipmentApi); ?>"
            data-equipment-online="<?php echo $onlineStatus ? '1' : '0'; ?>">
            <div class="nexora-equipment-heading">
                <div>
                    <h3 class="nexora-player-section-title">Equipamiento</h3>
                    <p class="nexora-equipment-source" data-equipment-source><?php echo $h(is_array($equipment) && !empty($equipment['source_label']) ? $equipment['source_label'] : 'Lectura pública del personaje'); ?></p>
                </div>
                <button type="button" class="nexora-equipment-refresh" data-equipment-refresh <?php echo class_exists('ProfileEquipment', false) ? '' : 'disabled'; ?>>Actualizar equipo</button>
            </div>

            <div class="nexora-equipment-message<?php echo $equipmentError === '' ? ' is-hidden' : ''; ?>" data-equipment-message>
                <?php echo $h($equipmentError !== '' ? $equipmentError : (is_array($equipment) && !empty($equipment['warning']) ? $equipment['warning'] : '')); ?>
            </div>

            <div class="nexora-equipment-grid" data-equipment-grid>
                <?php foreach ($equipmentSlots as $slotIndex => $slot) {
                    $slotItem = isset($equipmentItems[$slot['key']]) ? $equipmentItems[$slot['key']] : null;
                    $renderEquipmentSlot($slot, $slotItem);
                } ?>
                <div class="nexora-equipment-center" aria-hidden="true">
                    <?php if ($portraitUrl !== '') { ?><img src="<?php echo $h($portraitUrl); ?>" alt="" loading="lazy" decoding="async"><?php } ?>
                    <span><?php echo $h($charClassKey !== '' ? $charClassKey : 'MU'); ?></span>
                </div>
            </div>

            <p class="nexora-equipment-note">Se muestran únicamente los slots equipados. Inventario, baúl y datos privados de la cuenta permanecen ocultos.</p>
        </section>
    </article>
    <script src="<?php echo $h(__PATH_TEMPLATE_JS__ . 'nexora-profile-equipment.js?v=4.0.0'); ?>" defer></script>
    <?php
} catch (Exception $e) {
    message('error', $e->getMessage());
}
echo '</div>';
