<?php
use Plugin\ItemShop\ItemShop;

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

function itemshopPurchasesCoreEsc($value) { return htmlspecialchars((string)$value,ENT_QUOTES,'UTF-8'); }
function itemshopPurchasesCoreDate($value) {
    try {
        $d=new DateTimeImmutable((string)$value,new DateTimeZone('UTC'));
        return $d->setTimezone(new DateTimeZone(date_default_timezone_get()))->format('Y-m-d H:i');
    } catch(Throwable $e) { return (string)$value; }
}
function itemshopPurchasesCoreCurrency($value) {
    $m=array('WCOINC'=>'WCoinC','WCOINP'=>'WCoinP','GOBLINPOINT'=>'Goblin Points');
    $k=strtoupper((string)$value); return $m[$k] ?? $k;
}

$shop=new ItemShop();
if(!$shop->schemaReady()) throw new Exception('Arsenal no está disponible en este reino.');
$orders=$shop->getAccountPurchaseHistory((string)$_SESSION['username'],100);

echo '<div class="page-title"><span>'.itemshopPurchasesCoreEsc(lang('itemshop_purchases_title',true) ?: 'Mis compras').'</span></div>';
echo '<p><strong>Reino:</strong> '.itemshopPurchasesCoreEsc($shop->getRealmLabel()).'. Se muestran únicamente entregas reales confirmadas.</p>';
echo '<div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>Orden</th><th>Fecha</th><th>Producto</th><th>Precio</th><th>Estado</th></tr></thead><tbody>';
if(count($orders)<1) echo '<tr><td colspan="5">Todavía no tienes compras confirmadas en este reino.</td></tr>';
foreach($orders as $row) {
    echo '<tr><td>#'.(int)$row['id'].'</td><td>'.itemshopPurchasesCoreEsc(itemshopPurchasesCoreDate($row['created_at'])).'</td><td>'.itemshopPurchasesCoreEsc($row['item_name']).'</td><td>'.number_format((int)$row['price_paid']).' '.itemshopPurchasesCoreEsc(itemshopPurchasesCoreCurrency($row['currency'])).'</td><td><span class="label label-success">Entregado</span></td></tr>';
}
echo '</tbody></table></div>';
