<?php
use Plugin\ItemShop\ItemShop;

if(!isLoggedIn()) redirect(1,'login');

function nexoraPurchaseEsc($value) { return htmlspecialchars((string)$value,ENT_QUOTES,'UTF-8'); }
function nexoraPurchaseDate($value) {
    if(empty($value)) return '—';
    try {
        $d=new DateTimeImmutable((string)$value,new DateTimeZone('UTC'));
        return $d->setTimezone(new DateTimeZone(date_default_timezone_get()))->format('d/m/Y · H:i');
    } catch(Throwable $e) { return (string)$value; }
}
function nexoraPurchaseCurrency($value) {
    $m=array('WCOINC'=>'WCoinC','WCOINP'=>'WCoinP','GOBLINPOINT'=>'Goblin Points');
    $k=strtoupper(trim((string)$value)); return $m[$k] ?? $k;
}
function nexoraPurchaseTraits($snapshot) {
    if(!is_array($snapshot)) return array();
    $traits=array();
    $level=(int)($snapshot['item_level'] ?? 0);
    if($level>0) $traits[]='+'.$level;
    if(!empty($snapshot['has_skill'])) $traits[]='Skill';
    if(!empty($snapshot['has_luck'])) $traits[]='Luck';
    $option=(int)($snapshot['option_level'] ?? 0);
    if($option>0) $traits[]='Option +'.($option*4);
    $excellent=(int)($snapshot['excellent_mask'] ?? 0) & 0x3F;
    if($excellent>0) $traits[]='Excellent '.substr_count(decbin($excellent),'1').'/6';
    if((int)($snapshot['ancient_option'] ?? 0)>0) $traits[]='Ancient';
    if((int)($snapshot['harmony_option'] ?? 0)>0) $traits[]='Harmony';
    $sockets=(int)($snapshot['socket_count'] ?? 0);
    if($sockets>0) $traits[]='Socket '.$sockets.'/5';
    if(!empty($snapshot['option_380'])) $traits[]='380';
    return $traits;
}
function nexoraPurchaseImage($snapshot) {
    if(!is_array($snapshot) || !isset($snapshot['item_section'],$snapshot['item_index'])) return '';
    if(class_exists('ProfileEquipment')) return ProfileEquipment::itemImageUrl((int)$snapshot['item_section'],(int)$snapshot['item_index']);
    return '';
}

$shop=new ItemShop();
if(!$shop->schemaReady()) throw new Exception('Arsenal no está disponible en este reino.');
$orders=$shop->getAccountPurchaseHistory((string)$_SESSION['username'],100);
$products=array();
foreach($orders as $row) { $products[(int)($row['item_id'] ?? 0)]=true; }
$title=lang('itemshop_purchases_title',true) ?: 'Mis compras';
?>
<link rel="stylesheet" href="<?php echo nexoraPurchaseEsc(__PATH_TEMPLATE_CSS__); ?>itemshop-purchases.css?v=171">
<div class="nex-purchases">
    <header class="nex-purchases__header">
        <div>
            <span class="nex-purchases__eyebrow">ARSENAL · <?php echo nexoraPurchaseEsc(strtoupper($shop->getRealmLabel())); ?></span>
            <h1><?php echo nexoraPurchaseEsc($title); ?></h1>
            <p>Historial de entregas reales confirmadas para la cuenta <strong><?php echo nexoraPurchaseEsc($_SESSION['username']); ?></strong>.</p>
        </div>
        <a class="nex-purchases__shop" href="<?php echo nexoraPurchaseEsc(__BASE_URL__); ?>shop/">Abrir Arsenal <span aria-hidden="true">→</span></a>
    </header>

    <div class="nex-purchases__notice">
        <span aria-hidden="true">◆</span>
        <p>Este historial pertenece al reino fijado en tu sesión. Por seguridad no mostramos seriales, posiciones internas del baúl, IP ni datos técnicos de entrega.</p>
    </div>

    <section class="nex-purchases__stats" aria-label="Resumen de compras">
        <div><small>Entregas visibles</small><strong><?php echo number_format(count($orders)); ?></strong></div>
        <div><small>Productos distintos</small><strong><?php echo number_format(count($products)); ?></strong></div>
        <div><small>Reino de la sesión</small><strong><?php echo nexoraPurchaseEsc($shop->getRealmLabel()); ?></strong><em>historial aislado</em></div>
    </section>

    <?php if(count($orders)<1) { ?>
        <section class="nex-purchases__empty">
            <span aria-hidden="true">◇</span>
            <h2>Aún no hay entregas registradas</h2>
            <p>Cuando adquieras una pieza de Arsenal y la entrega termine correctamente, aparecerá aquí.</p>
            <a href="<?php echo nexoraPurchaseEsc(__BASE_URL__); ?>shop/">Explorar Arsenal</a>
        </section>
    <?php } else { ?>
        <section class="nex-purchases__list">
            <?php foreach($orders as $row) {
                $snapshot=$shop->decodeOrderSnapshot($row['item_snapshot'] ?? '');
                $traits=nexoraPurchaseTraits($snapshot);
                $image=nexoraPurchaseImage($snapshot);
                $category=trim((string)($snapshot['category'] ?? ''));
            ?>
                <article class="nex-purchase-card">
                    <div class="nex-purchase-card__visual">
                        <?php if($image!=='') { ?><img src="<?php echo nexoraPurchaseEsc($image); ?>" alt="" loading="lazy"><?php } else { ?><span aria-hidden="true">◇</span><?php } ?>
                    </div>
                    <div class="nex-purchase-card__main">
                        <div class="nex-purchase-card__meta"><span>ORDEN #<?php echo (int)$row['id']; ?></span><time><?php echo nexoraPurchaseEsc(nexoraPurchaseDate($row['created_at'])); ?></time></div>
                        <h2><?php echo nexoraPurchaseEsc($row['item_name']); ?></h2>
                        <?php if($category!=='') { ?><p class="nex-purchase-card__category"><?php echo nexoraPurchaseEsc($category); ?></p><?php } ?>
                        <?php if(count($traits)>0) { ?><div class="nex-purchase-card__traits"><?php foreach($traits as $trait) { ?><span><?php echo nexoraPurchaseEsc($trait); ?></span><?php } ?></div><?php } ?>
                    </div>
                    <div class="nex-purchase-card__ledger">
                        <small>Valor pagado</small>
                        <strong><?php echo number_format((int)$row['price_paid']); ?></strong>
                        <em><?php echo nexoraPurchaseEsc(nexoraPurchaseCurrency($row['currency'])); ?></em>
                        <span class="nex-purchase-card__status"><i aria-hidden="true">✓</i> Entregado</span>
                    </div>
                </article>
            <?php } ?>
        </section>
        <?php if(count($orders)>=100) { ?><p class="nex-purchases__limit">Se muestran las 100 compras confirmadas más recientes de este reino.</p><?php } ?>
    <?php } ?>
</div>
