<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../core/format.php';

require_login();
require_permission('module.crm');

$page_title = 'Reposiciones predictivas';
$pdo = db();
$user = current_user() ?: array();
$isPortfolioRestricted = (string)($user['role'] ?? '') === 'comercial';
$status = trim((string)($_GET['status'] ?? 'active'));
$search = trim((string)($_GET['q'] ?? ''));
$allowed = array('active','pending','ready','converted','expired','cancelled','superseded','all');
if (!in_array($status, $allowed, true)) $status = 'active';

$where = array('c.deleted_at IS NULL');
$params = array();
if ($status === 'active') {
    $where[] = "f.status IN ('pending','ready')";
} elseif ($status !== 'all') {
    $where[] = 'f.status = ?';
    $params[] = $status;
}
if ($search !== '') {
    $where[] = '(c.customer_name LIKE ? OR c.customer_tax_id LIKE ? OR f.source_facto_document_id LIKE ?)';
    $needle = '%' . $search . '%';
    array_push($params, $needle, $needle, $needle);
}
if ($isPortfolioRestricted) {
    $where[] = 'f.owner_user_id = ?';
    $params[] = (int)($user['id'] ?? 0);
}
$whereSql = implode(' AND ', $where);

$summary = array('pending'=>0,'ready'=>0,'converted'=>0,'expired'=>0,'total'=>0);
try {
    if ($isPortfolioRestricted) {
        $summaryStmt = $pdo->prepare("SELECT status,COUNT(*) total FROM crm_restock_forecasts WHERE owner_user_id=? GROUP BY status");
        $summaryStmt->execute(array((int)($user['id'] ?? 0)));
        $summaryRows = $summaryStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $summaryRows = $pdo->query("SELECT status,COUNT(*) total FROM crm_restock_forecasts GROUP BY status")->fetchAll(PDO::FETCH_ASSOC);
    }
    foreach ($summaryRows as $row) {
        $summary[$row['status']] = (int)$row['total'];
        $summary['total'] += (int)$row['total'];
    }
    $stmt = $pdo->prepare("\n        SELECT f.*, c.customer_name, c.customer_tax_id, c.customer_lifecycle_status,\n               o.stage AS opportunity_stage, o.archived_at AS opportunity_archived_at\n        FROM crm_restock_forecasts f\n        JOIN crm_customers c ON c.id=f.customer_id\n        LEFT JOIN crm_opportunities o ON o.id=f.opportunity_id\n        WHERE $whereSql\n        ORDER BY CASE f.status WHEN 'ready' THEN 0 WHEN 'pending' THEN 1 ELSE 2 END, f.activation_date ASC, f.id DESC\n        LIMIT 300\n    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $rows = array();
    $loadError = $e->getMessage();
}

function restock_status_label(string $status): string {
    return array(
        'pending'=>'Pendiente','ready'=>'Lista para activar','converted'=>'Convertida',
        'expired'=>'Vencida','cancelled'=>'Cancelada','superseded'=>'Sustituida'
    )[$status] ?? $status;
}
function restock_status_class(string $status): string {
    return array('ready'=>'success','pending'=>'warning','converted'=>'info','expired'=>'error','cancelled'=>'neutral','superseded'=>'neutral')[$status] ?? 'neutral';
}
function restock_lifecycle_label(string $status): string {
    return array('active'=>'Activo','at_risk'=>'En riesgo','lost'=>'Perdido','unknown'=>'Sin clasificar')[$status] ?? $status;
}
function restock_date($value): string {
    if (!$value) return '—';
    $ts = strtotime((string)$value);
    return $ts ? date('d-m-Y',$ts) : '—';
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>
<main class="app-main" id="restock-forecast-main">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section class="content">
        <div class="page-header">
            <div class="page-header-content">
                <span class="label">CRM · Inteligencia comercial</span>
                <h1>Reposiciones predictivas</h1>
                <p class="text-secondary">Pronósticos separados del embudo. El motor evalúa compras recientes, actualiza pronósticos y solo los convierte dentro de la ventana comercial.</p>
            </div>
            <div class="cluster actions-cluster">
                <a href="/modules/crm/" class="btn btn-outline"><i data-lucide="arrow-left"></i><span>Volver al CRM</span></a>
                <?php if (in_array((string)($user['role'] ?? ''), array('admin','administracion'), true)): ?>
                    <form method="post" action="/modules/crm/restock_forecasts_run.php" style="display:inline-flex;">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <button class="btn btn-primary" type="submit"><i data-lucide="refresh-cw"></i><span>Actualizar y procesar</span></button>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!empty($_SESSION['restock_flash'])): $flash=$_SESSION['restock_flash']; unset($_SESSION['restock_flash']); ?>
            <div class="alert <?php echo !empty($flash['ok']) ? 'alert-success' : 'alert-error'; ?> mb-4"><?php echo safe_text($flash['message'] ?? ''); ?></div>
        <?php endif; ?>
        <?php if (!empty($loadError)): ?>
            <div class="alert alert-error mb-4">Falta ejecutar la migración v8.5 o no fue posible leer los pronósticos: <?php echo safe_text($loadError); ?></div>
        <?php endif; ?>

        <section class="grid grid-4 mb-4">
            <article class="kpi-card"><div class="kpi-label">Pendientes</div><div class="kpi-main"><div class="kpi-value"><?php echo (int)$summary['pending']; ?></div></div><p class="kpi-context">Fuera de ventana</p></article>
            <article class="kpi-card"><div class="kpi-label">Listas</div><div class="kpi-main"><div class="kpi-value"><?php echo (int)$summary['ready']; ?></div></div><p class="kpi-context">Activables por el job diario</p></article>
            <article class="kpi-card"><div class="kpi-label">Convertidas</div><div class="kpi-main"><div class="kpi-value"><?php echo (int)$summary['converted']; ?></div></div><p class="kpi-context">Con oportunidad asociada</p></article>
            <article class="kpi-card"><div class="kpi-label">Vencidas</div><div class="kpi-main"><div class="kpi-value"><?php echo (int)$summary['expired']; ?></div></div><p class="kpi-context">Sin acción o compra</p></article>
        </section>

        <article class="card">
            <div class="card-header">
                <div><span class="label">Control BI</span><h3>Pronósticos de recompra</h3></div>
            </div>
            <div class="card-body">
                <form method="get" class="toolbar" style="display:grid;grid-template-columns:minmax(220px,1fr) minmax(180px,240px) auto;gap:12px;margin-bottom:16px;">
                    <input class="input" name="q" value="<?php echo safe_text($search); ?>" placeholder="Buscar cliente, RUT o DTE">
                    <select class="select" name="status">
                        <?php foreach (array('active'=>'Pendientes + listas','pending'=>'Pendientes','ready'=>'Listas','converted'=>'Convertidas','expired'=>'Vencidas','cancelled'=>'Canceladas','superseded'=>'Sustituidas','all'=>'Todas') as $key=>$label): ?>
                            <option value="<?php echo $key; ?>" <?php echo $status===$key?'selected':''; ?>><?php echo safe_text($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button class="btn btn-outline" type="submit"><i data-lucide="search"></i><span>Filtrar</span></button>
                </form>

                <div class="table-wrap" style="overflow:auto;">
                    <table class="table">
                        <thead><tr><th>Cliente</th><th>Compra base</th><th>Ciclo</th><th>Activación</th><th>Reposición</th><th>Valor</th><th>Confianza</th><th>Estado</th><th>Acción</th></tr></thead>
                        <tbody>
                        <?php if (!$rows): ?>
                            <tr><td colspan="9" class="text-muted" style="text-align:center;padding:28px;">No hay pronósticos para los filtros seleccionados. Usa “Actualizar y procesar” para evaluar las compras recientes.</td></tr>
                        <?php else: foreach ($rows as $row): ?>
                            <tr>
                                <td><strong><?php echo safe_text($row['customer_name']); ?></strong><br><span class="text-muted text-sm"><?php echo safe_text($row['customer_tax_id'] ?: 'Sin RUT'); ?> · <?php echo safe_text(restock_lifecycle_label((string)$row['customer_lifecycle_status'])); ?></span></td>
                                <td><?php echo restock_date($row['last_purchase_date']); ?><br><span class="text-muted text-sm">DTE <?php echo safe_text($row['source_facto_document_id']); ?></span></td>
                                <td><?php echo (int)$row['restock_days']; ?> días<br><span class="text-muted text-sm"><?php echo (int)$row['purchase_observations']; ?> observaciones</span></td>
                                <td><?php echo restock_date($row['activation_date']); ?></td>
                                <td><strong><?php echo restock_date($row['projected_restock_date']); ?></strong></td>
                                <td><?php echo clp((float)$row['expected_value']); ?></td>
                                <td><?php echo number_format(((float)$row['confidence_score'])*100,0,',','.'); ?>%</td>
                                <td><span class="badge badge-<?php echo restock_status_class((string)$row['status']); ?>"><?php echo safe_text(restock_status_label((string)$row['status'])); ?></span></td>
                                <td>
                                    <?php if (!empty($row['opportunity_id'])): ?>
                                        <a class="icon-btn" href="/modules/crm/opportunity.php?id=<?php echo (int)$row['opportunity_id']; ?>" title="Abrir oportunidad"><i data-lucide="external-link"></i></a>
                                    <?php else: ?>—<?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </article>
    </section>
</main>
<style>
@media(max-width:760px){#restock-forecast-main .toolbar{grid-template-columns:1fr!important}#restock-forecast-main .grid-4{grid-template-columns:repeat(2,minmax(0,1fr))!important}}
</style>
<?php require_once '../../layouts/footer.php'; ?>
