<?php
use Plugin\ItemShop\ItemShop;

function itemshopAnalyticsEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function itemshopAnalyticsNum($value, $decimals=0) { return number_format((float)$value, (int)$decimals); }
function itemshopAnalyticsDate($value, $format='Y-m-d H:i') {
    if(empty($value)) return '—';
    try {
        $date = new DateTimeImmutable((string)$value, new DateTimeZone('UTC'));
        return $date->setTimezone(new DateTimeZone(date_default_timezone_get()))->format($format);
    } catch(Throwable $e) { return (string)$value; }
}
function itemshopAnalyticsTrendBuckets($rows, $days) {
    $raw = array();
    foreach((array)$rows as $row) {
        $day = trim((string)($row['day'] ?? ''));
        if($day === '') continue;
        $raw[$day] = array(
            'revenue'=>(int)($row['revenue'] ?? 0),
            'deliveries'=>(int)($row['deliveries'] ?? 0),
            'buyers'=>(int)($row['buyers'] ?? 0),
        );
    }

    if($days <= 30) {
        $out = array();
        $start = new DateTimeImmutable('today -'.($days-1).' days', new DateTimeZone('UTC'));
        for($i=0; $i<$days; $i++) {
            $date = $start->modify('+'.$i.' days');
            $key = $date->format('Y-m-d');
            $row = $raw[$key] ?? array('revenue'=>0,'deliveries'=>0,'buyers'=>0);
            $row['label'] = $date->format('d M');
            $out[] = $row;
        }
        return $out;
    }

    $grouped = array();
    foreach($raw as $day=>$row) {
        try { $date = new DateTimeImmutable($day); } catch(Throwable $e) { continue; }
        if($days <= 90) {
            $monday = $date->modify('monday this week');
            $key = $monday->format('Y-m-d');
            $label = $monday->format('d M');
        } else {
            $key = $date->format('Y-m');
            $label = $date->format('M Y');
        }
        if(!isset($grouped[$key])) $grouped[$key] = array('label'=>$label,'revenue'=>0,'deliveries'=>0,'buyers'=>0);
        $grouped[$key]['revenue'] += (int)$row['revenue'];
        $grouped[$key]['deliveries'] += (int)$row['deliveries'];
        $grouped[$key]['buyers'] += (int)$row['buyers'];
    }
    ksort($grouped);
    return array_values($grouped);
}

$shop = new ItemShop();
if(!$shop->schemaReady()) { message('warning', 'Primero instala las tablas desde Arsenal Nexora → Configuración.'); return; }

$allowedRanges = array(7=>'7 días',30=>'30 días',90=>'90 días',365=>'12 meses');
$range = isset($_GET['range']) ? (int)$_GET['range'] : 30;
if(!isset($allowedRanges[$range])) $range = 30;
$data = $shop->analytics($range, 5);
$summary = is_array($data['summary'] ?? null) ? $data['summary'] : array();
$catalog = is_array($data['catalog'] ?? null) ? $data['catalog'] : array();
$promotions = is_array($data['promotions'] ?? null) ? $data['promotions'] : array();
$trend = itemshopAnalyticsTrendBuckets($data['trend'] ?? array(), $range);
$currency = (string)($data['currency_label'] ?? $shop->currencyLabel());
$revenue = (int)($summary['revenue'] ?? 0);
$deliveries = (int)($summary['deliveries'] ?? 0);
$buyers = (int)($summary['buyers'] ?? 0);
$products = (int)($summary['products'] ?? 0);
$avgTicket = (float)($summary['avg_ticket'] ?? 0);
$rotation = (float)($catalog['rotation_percent'] ?? 0);
$maxRevenue = 0;
$maxDeliveries = 0;
foreach($trend as $bucket) {
    $maxRevenue = max($maxRevenue, (int)$bucket['revenue']);
    $maxDeliveries = max($maxDeliveries, (int)$bucket['deliveries']);
}
?>
<link rel="stylesheet" href="<?php echo itemshopAnalyticsEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=170">
<div id="itemshop-admin-analytics">
    <h1 class="page-header">Analytics · <?php echo itemshopAnalyticsEsc($shop->getRealmLabel()); ?></h1>
    <div class="itemshop-admin-toolbar">
        <a href="index.php?module=itemshop&amp;page=items">← Catálogo</a>
        <a href="index.php?module=itemshop&amp;page=operations">Operaciones</a>
        <a href="index.php?module=itemshop&amp;page=collections">Colecciones</a>
        <a href="index.php?module=itemshop&amp;page=campaigns">Campañas</a>
        <a href="index.php?module=itemshop&amp;page=logs">Entregas</a>
        <a href="index.php?module=itemshop&amp;page=logs&amp;status=test">Datos de prueba</a>
        <a href="<?php echo itemshopAnalyticsEsc(__BASE_URL__); ?>shop/" target="_blank" rel="noopener">Abrir Arsenal público ↗</a>
    </div>

    <div class="itemshop-analytics-head">
        <div>
            <strong>Rendimiento comercial confirmado</strong>
            <span>Solo contabiliza órdenes <code>delivered</code> de la moneda actual <?php echo itemshopAnalyticsEsc($currency); ?>. Las <code>delivered_test</code> quedan fuera de Analytics. No estima vistas, carritos ni compras fallidas.</span>
        </div>
        <div class="itemshop-analytics-ranges" role="navigation" aria-label="Rango Analytics">
            <?php foreach($allowedRanges as $days=>$label) { ?>
                <a class="<?php echo $range === $days ? 'is-active' : ''; ?>" href="index.php?module=itemshop&amp;page=analytics&amp;range=<?php echo (int)$days; ?>"><?php echo itemshopAnalyticsEsc($label); ?></a>
            <?php } ?>
        </div>
    </div>

    <div class="itemshop-analytics-kpis">
        <div><span><?php echo itemshopAnalyticsEsc($currency); ?> consumido</span><strong><?php echo itemshopAnalyticsNum($revenue); ?></strong><small>Saldo retirado por entregas confirmadas</small></div>
        <div><span>Entregas</span><strong><?php echo itemshopAnalyticsNum($deliveries); ?></strong><small><?php echo itemshopAnalyticsNum($deliveries / max(1,$range), 1); ?> por día</small></div>
        <div><span>Compradores únicos</span><strong><?php echo itemshopAnalyticsNum($buyers); ?></strong><small>Cuentas con al menos una compra</small></div>
        <div><span>Ticket medio</span><strong><?php echo itemshopAnalyticsNum($avgTicket); ?></strong><small><?php echo itemshopAnalyticsEsc($currency); ?> por entrega</small></div>
        <div><span>Productos vendidos</span><strong><?php echo itemshopAnalyticsNum($products); ?></strong><small>Configuraciones distintas</small></div>
        <div><span>Rotación publicada</span><strong><?php echo itemshopAnalyticsNum($rotation,1); ?>%</strong><small><?php echo itemshopAnalyticsNum((int)($catalog['sold_active'] ?? 0)); ?> de <?php echo itemshopAnalyticsNum((int)($catalog['active_items'] ?? 0)); ?> activos vendieron</small></div>
    </div>

    <div class="panel panel-default itemshop-admin-panel itemshop-analytics-promo-panel">
        <div class="panel-heading"><strong>Impacto de promociones</strong><span>Se calcula contra el precio normal congelado dentro del snapshot de cada entrega.</span></div>
        <div class="panel-body">
            <div class="itemshop-analytics-health-grid">
                <div><span>Entregas en promo</span><strong><?php echo itemshopAnalyticsNum((int)($promotions['deliveries'] ?? 0)); ?></strong></div>
                <div><span>Share de entregas</span><strong><?php echo itemshopAnalyticsNum((float)($promotions['share_percent'] ?? 0),1); ?>%</strong></div>
                <div><span><?php echo itemshopAnalyticsEsc($currency); ?> en promo</span><strong><?php echo itemshopAnalyticsNum((int)($promotions['revenue'] ?? 0)); ?></strong></div>
                <div><span>Descuento concedido</span><strong><?php echo itemshopAnalyticsNum((int)($promotions['savings'] ?? 0)); ?></strong></div>
            </div>
            <p class="help-block" style="margin-bottom:0">Una entrega cuenta como promocional cuando <code>price_paid</code> es menor que <code>price_wc</code> guardado en su snapshot histórico.</p>
        </div>
    </div>

    <div class="panel panel-default itemshop-admin-panel itemshop-analytics-trend-panel">
        <div class="panel-heading"><strong>Tendencia · <?php echo itemshopAnalyticsEsc($allowedRanges[$range]); ?></strong><span>Volumen confirmado por fecha. Para rangos largos se agrupa visualmente.</span></div>
        <div class="panel-body">
            <?php if($deliveries < 1) { ?>
                <p class="text-muted" style="margin:0">Todavía no hay entregas confirmadas dentro de este período.</p>
            <?php } else { ?>
                <div class="itemshop-analytics-chart" aria-label="Tendencia de ventas">
                    <?php foreach($trend as $bucket) {
                        $rWidth = $maxRevenue > 0 ? max(1, round(((int)$bucket['revenue'] / $maxRevenue) * 100, 1)) : 0;
                        $dWidth = $maxDeliveries > 0 ? max(1, round(((int)$bucket['deliveries'] / $maxDeliveries) * 100, 1)) : 0;
                    ?>
                        <div class="itemshop-analytics-chart-row">
                            <span class="itemshop-analytics-chart-label"><?php echo itemshopAnalyticsEsc($bucket['label']); ?></span>
                            <div class="itemshop-analytics-chart-bars">
                                <div class="itemshop-analytics-bar is-revenue" style="width:<?php echo itemshopAnalyticsEsc($rWidth); ?>%"><span><?php echo itemshopAnalyticsNum((int)$bucket['revenue']); ?> <?php echo itemshopAnalyticsEsc($currency); ?></span></div>
                                <div class="itemshop-analytics-bar is-orders" style="width:<?php echo itemshopAnalyticsEsc($dWidth); ?>%"><span><?php echo itemshopAnalyticsNum((int)$bucket['deliveries']); ?> entregas</span></div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } ?>
        </div>
    </div>

    <div class="itemshop-analytics-columns">
        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Top productos</strong><span>Ordenados por <?php echo itemshopAnalyticsEsc($currency); ?> consumido.</span></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-bordered itemshop-analytics-table">
                    <thead><tr><th>Producto</th><th>Entregas</th><th>Compradores</th><th><?php echo itemshopAnalyticsEsc($currency); ?></th><th>Share</th></tr></thead>
                    <tbody>
                    <?php if(empty($data['top_items'])) { ?><tr><td colspan="5">Sin ventas en el período.</td></tr><?php } ?>
                    <?php foreach((array)($data['top_items'] ?? array()) as $row) {
                        $rowRevenue = (int)($row['revenue'] ?? 0);
                        $share = $revenue > 0 ? ($rowRevenue / $revenue) * 100 : 0;
                    ?>
                        <tr>
                            <td><strong><?php echo itemshopAnalyticsEsc($row['item_name'] ?? ''); ?></strong><br><small>ID #<?php echo (int)($row['item_id'] ?? 0); ?> · última <?php echo itemshopAnalyticsEsc(itemshopAnalyticsDate($row['last_sale'] ?? null,'d/m H:i')); ?></small></td>
                            <td><?php echo itemshopAnalyticsNum((int)($row['deliveries'] ?? 0)); ?></td>
                            <td><?php echo itemshopAnalyticsNum((int)($row['buyers'] ?? 0)); ?></td>
                            <td><?php echo itemshopAnalyticsNum($rowRevenue); ?></td>
                            <td><?php echo itemshopAnalyticsNum($share,1); ?>%</td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Rendimiento por categoría</strong><span>Usa la categoría congelada dentro del snapshot de cada entrega.</span></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-bordered itemshop-analytics-table">
                    <thead><tr><th>Categoría</th><th>Entregas</th><th>Compradores</th><th><?php echo itemshopAnalyticsEsc($currency); ?></th></tr></thead>
                    <tbody>
                    <?php if(empty($data['categories'])) { ?><tr><td colspan="4">Sin datos en el período.</td></tr><?php } ?>
                    <?php foreach((array)($data['categories'] ?? array()) as $row) { ?>
                        <tr><td><strong><?php echo itemshopAnalyticsEsc($row['category'] ?? ''); ?></strong></td><td><?php echo itemshopAnalyticsNum((int)($row['deliveries'] ?? 0)); ?></td><td><?php echo itemshopAnalyticsNum((int)($row['buyers'] ?? 0)); ?></td><td><?php echo itemshopAnalyticsNum((int)($row['revenue'] ?? 0)); ?></td></tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="itemshop-analytics-columns">
        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Compradores principales</strong><span>Herramienta de lectura económica; no modifica cuentas.</span></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-bordered itemshop-analytics-table">
                    <thead><tr><th>Cuenta</th><th>Entregas</th><th>Productos</th><th><?php echo itemshopAnalyticsEsc($currency); ?></th><th>Última</th></tr></thead>
                    <tbody>
                    <?php if(empty($data['top_buyers'])) { ?><tr><td colspan="5">Sin compradores en el período.</td></tr><?php } ?>
                    <?php foreach((array)($data['top_buyers'] ?? array()) as $row) { ?>
                        <tr><td><strong><?php echo itemshopAnalyticsEsc($row['account_username'] ?? ''); ?></strong></td><td><?php echo itemshopAnalyticsNum((int)($row['deliveries'] ?? 0)); ?></td><td><?php echo itemshopAnalyticsNum((int)($row['products'] ?? 0)); ?></td><td><?php echo itemshopAnalyticsNum((int)($row['revenue'] ?? 0)); ?></td><td><?php echo itemshopAnalyticsEsc(itemshopAnalyticsDate($row['last_purchase'] ?? null,'d/m H:i')); ?></td></tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Salud comercial del catálogo</strong><span>Prioriza qué revisar sin alterar automáticamente precios o stock.</span></div>
            <div class="panel-body">
                <div class="itemshop-analytics-health-grid">
                    <div><span>Publicados</span><strong><?php echo itemshopAnalyticsNum((int)($catalog['active_items'] ?? 0)); ?></strong></div>
                    <div><span>Sin ventas</span><strong><?php echo itemshopAnalyticsNum((int)($catalog['unsold_active'] ?? 0)); ?></strong></div>
                    <div><span>Agotados</span><strong><?php echo itemshopAnalyticsNum((int)($catalog['sold_out'] ?? 0)); ?></strong></div>
                    <div><span>Stock ≤ 5</span><strong><?php echo itemshopAnalyticsNum((int)($catalog['low_stock'] ?? 0)); ?></strong></div>
                </div>
                <p class="help-block" style="margin-bottom:0">“Sin ventas” significa que un producto publicado no registró ninguna orden delivered en los últimos <?php echo (int)$range; ?> días. No implica que deba eliminarse o bajar de precio automáticamente.</p>
            </div>
        </div>
    </div>

    <div class="itemshop-analytics-columns">
        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Publicados sin rotación</strong><span>Hasta 20 configuraciones sin ventas en el período.</span></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-bordered itemshop-analytics-table">
                    <thead><tr><th>Ítem</th><th>Código</th><th>Precio</th><th>Stock</th><th></th></tr></thead>
                    <tbody>
                    <?php if(empty($data['unsold'])) { ?><tr><td colspan="5">Todos los productos publicados registraron al menos una venta.</td></tr><?php } ?>
                    <?php foreach((array)($data['unsold'] ?? array()) as $row) { ?>
                        <tr>
                            <td><strong><?php echo itemshopAnalyticsEsc($row['name'] ?? ''); ?></strong><br><small><?php echo itemshopAnalyticsEsc($row['category'] ?? ''); ?><?php if(!empty($row['featured'])) echo ' · Destacado'; ?></small></td>
                            <td><code><?php echo (int)($row['item_section'] ?? 0); ?>:<?php echo (int)($row['item_index'] ?? 0); ?></code></td>
                            <td><?php echo itemshopAnalyticsNum((int)($row['price_wc'] ?? 0)); ?></td>
                            <td><?php echo (int)($row['stock'] ?? -1) < 0 ? 'Ilimitado' : itemshopAnalyticsNum((int)$row['stock']); ?></td>
                            <td><a class="btn btn-default btn-xs" href="index.php?module=itemshop&amp;page=form&amp;id=<?php echo (int)($row['id'] ?? 0); ?>">Editar</a></td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="panel panel-default itemshop-admin-panel">
            <div class="panel-heading"><strong>Alertas de stock</strong><span>Publicados con stock entre 0 y 5; ilimitados quedan fuera.</span></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-bordered itemshop-analytics-table">
                    <thead><tr><th>Ítem</th><th>Código</th><th>Stock</th><th>Precio</th><th></th></tr></thead>
                    <tbody>
                    <?php if(empty($data['low_stock'])) { ?><tr><td colspan="5">Sin alertas de stock.</td></tr><?php } ?>
                    <?php foreach((array)($data['low_stock'] ?? array()) as $row) { ?>
                        <tr>
                            <td><strong><?php echo itemshopAnalyticsEsc($row['name'] ?? ''); ?></strong><br><small><?php echo itemshopAnalyticsEsc($row['category'] ?? ''); ?></small></td>
                            <td><code><?php echo (int)($row['item_section'] ?? 0); ?>:<?php echo (int)($row['item_index'] ?? 0); ?></code></td>
                            <td><?php if((int)($row['stock'] ?? 0) === 0) { ?><span class="label label-danger">Agotado</span><?php } else { ?><span class="label label-warning"><?php echo itemshopAnalyticsNum((int)$row['stock']); ?></span><?php } ?></td>
                            <td><?php echo itemshopAnalyticsNum((int)($row['price_wc'] ?? 0)); ?></td>
                            <td><a class="btn btn-default btn-xs" href="index.php?module=itemshop&amp;page=form&amp;id=<?php echo (int)($row['id'] ?? 0); ?>">Editar</a></td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
