<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../services/analytics/DashboardAccessService.php';
require_once '../../services/analytics/KpiDashboardService.php';

require_login();

$user = current_user();
$access = new DashboardAccessService();
$allowed = $access->allowedDashboards($user);
$catalog = $access->catalog();

$view = isset($_GET['view']) ? trim((string)$_GET['view']) : $access->defaultDashboard($user);
if (!isset($catalog[$view]) || !in_array($view, $allowed, true)) {
    $view = $access->defaultDashboard($user);
}
$access->requireView($view, $user);
$canConfigure = $access->canConfigure($view, $user);

$defaultFrom = date('Y-m-01');
$defaultTo = date('Y-m-t');
$from = isset($_GET['from']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['from']) ? $_GET['from'] : $defaultFrom;
$to = isset($_GET['to']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['to']) ? $_GET['to'] : $defaultTo;
if ($from > $to) {
    $tmp = $from;
    $from = $to;
    $to = $tmp;
}

$service = new KpiDashboardService($from, $to, $user);
$dashboard = $service->getDashboard($view);
$meta = $service->meta();

$page_title = $catalog[$view]['label'] . ' | Dashboards';

function dashboard_value($value, $unit)
{
    if ($value === null || $value === '') return 'N/D';
    switch ($unit) {
        case 'clp': return clp($value);
        case 'pct': return number_format((float)$value, 1, ',', '.') . '%';
        case 'x': return number_format((float)$value, 2, ',', '.') . 'x';
        case 'months': return number_format((float)$value, 1, ',', '.') . ' meses';
        case 'int': return number_format((int)$value, 0, ',', '.');
        default: return safe_text((string)$value);
    }
}

function dashboard_target($target, $unit)
{
    if ($target === null || $target === '') return 'Sin meta configurada';
    return 'Meta: ' . dashboard_value($target, $unit);
}

function dashboard_status_label($status)
{
    $labels = array('green' => 'En objetivo', 'amber' => 'Atención', 'red' => 'Crítico', 'neutral' => 'Informativo', 'na' => 'Sin dato', 'covered' => 'Meta cubierta');
    return isset($labels[$status]) ? $labels[$status] : 'Informativo';
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main dashboard-suite-main" id="dashboard-suite-main" data-spa-module="dashboard:suite">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content dashboard-suite-content">
        <header class="dashboard-commandbar">
            <div class="dashboard-commandbar-title">
                <span class="label">Inteligencia de negocio</span>
                <div class="dashboard-title-line">
                    <h1><?php echo safe_text($dashboard['title']); ?></h1>
                    <span class="dashboard-id-chip"><?php echo safe_text($catalog[$view]['id']); ?></span>
                </div>
                <p><?php echo safe_text($dashboard['subtitle']); ?></p>
            </div>

            <form class="dashboard-period-form" method="get" action="/modules/dashboard/">
                <input type="hidden" name="view" value="<?php echo safe_text($view); ?>">
                <label>
                    <span>Desde</span>
                    <input class="input" type="date" name="from" value="<?php echo safe_text($from); ?>">
                </label>
                <label>
                    <span>Hasta</span>
                    <input class="input" type="date" name="to" value="<?php echo safe_text($to); ?>">
                </label>
                <button class="btn btn-outline" type="submit"><i data-lucide="filter"></i><span>Aplicar</span></button>
            </form>
        </header>

        <nav class="dashboard-tabs" aria-label="Dashboards disponibles">
            <?php foreach ($allowed as $key): ?>
                <?php if (!isset($catalog[$key])) continue; ?>
                <a class="dashboard-tab <?php echo $key === $view ? 'is-active' : ''; ?>" href="/modules/dashboard/?view=<?php echo urlencode($key); ?>&from=<?php echo urlencode($from); ?>&to=<?php echo urlencode($to); ?>">
                    <i data-lucide="<?php echo safe_text($catalog[$key]['icon']); ?>"></i>
                    <span><?php echo safe_text($catalog[$key]['label']); ?></span>
                </a>
            <?php endforeach; ?>
        </nav>

        <div class="dashboard-data-strip">
            <span><i data-lucide="calendar-range"></i><?php echo safe_text(date('d-m-Y', strtotime($from))); ?> a <?php echo safe_text(date('d-m-Y', strtotime($to))); ?></span>
            <span><i data-lucide="refresh-cw"></i>Fuente más reciente: <?php echo safe_text($meta['freshness']); ?></span>
            <span><i data-lucide="shield-check"></i><?php echo $canConfigure ? 'Metas editables con trazabilidad' : 'Permisos aplicados en servidor'; ?></span>
        </div>

        <section class="dashboard-kpi-grid">
            <?php foreach ($dashboard['kpis'] as $kpi): ?>
                <?php
                    $tooltip = $kpi['note'];
                    if (!empty($kpi['formula'])) $tooltip .= ' Fórmula: ' . $kpi['formula'] . '.';
                    if (!empty($kpi['definition_version'])) $tooltip .= ' Versión: ' . $kpi['definition_version'] . '.';
                ?>
                <article class="dashboard-kpi dashboard-kpi-<?php echo safe_text($kpi['status']); ?>" tabindex="0" title="<?php echo safe_text($tooltip); ?>">
                    <div class="dashboard-kpi-head">
                        <div>
                            <span class="dashboard-kpi-id"><?php echo safe_text($kpi['id']); ?></span>
                            <h2><?php echo safe_text($kpi['name']); ?></h2>
                        </div>
                        <div class="dashboard-kpi-head-actions">
                            <?php if ($canConfigure): ?>
                                <button
                                    class="dashboard-kpi-target-btn"
                                    type="button"
                                    data-kpi-id="<?php echo safe_text($kpi['id']); ?>"
                                    aria-label="Configurar meta de <?php echo safe_text($kpi['name']); ?>"
                                    title="Ingresar o actualizar meta"
                                ><i data-lucide="pencil-line"></i></button>
                            <?php endif; ?>
                            <span class="dashboard-status-dot" aria-hidden="true"></span>
                            <span class="dashboard-kpi-info" tabindex="0" title="<?php echo safe_text($tooltip); ?>" aria-label="Definición de <?php echo safe_text($kpi['name']); ?>"><i data-lucide="info"></i></span>
                        </div>
                    </div>
                    <div class="dashboard-kpi-value"><?php echo dashboard_value($kpi['value'], $kpi['unit']); ?></div>
                    <div class="dashboard-kpi-meta">
                        <span><?php echo safe_text(dashboard_status_label($kpi['status'])); ?></span>
                        <span><?php echo safe_text(dashboard_target($kpi['target'], $kpi['unit'])); ?></span>
                    </div>
                    <p><?php echo safe_text($kpi['note']); ?></p>
                    <footer>
                        <span class="dashboard-quality dashboard-quality-<?php echo safe_text($kpi['quality']); ?>"><?php echo safe_text($kpi['quality'] === 'validated' ? 'Validado' : ($kpi['quality'] === 'provisional' ? 'Provisional' : ($kpi['quality'] === 'failed' ? 'Error de cálculo' : 'Fuente pendiente'))); ?></span>
                        <span><?php echo safe_text($kpi['freshness']); ?></span>
                    </footer>
                </article>
            <?php endforeach; ?>
        </section>

        <?php if (!empty($dashboard['insight'])): ?>
            <aside class="dashboard-insight">
                <div class="dashboard-insight-icon"><i data-lucide="scan-search"></i></div>
                <div>
                    <span class="label">Lectura prioritaria</span>
                    <p><?php echo safe_text($dashboard['insight']); ?></p>
                </div>
            </aside>
        <?php endif; ?>

        <section class="dashboard-visual-grid">
            <?php if (!empty($dashboard['charts']['sales_trend'])): ?>
                <article class="card dashboard-panel dashboard-panel-wide">
                    <div class="card-header"><div><span class="label">Tendencia</span><h3>Ventas netas mensuales</h3></div></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartSalesTrend"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['pipeline_stage'])): ?>
                <article class="card dashboard-panel">
                    <div class="card-header"><div><span class="label">Pipeline</span><h3>Valor por etapa</h3></div><a class="btn btn-sm btn-outline" href="/modules/crm/embudo.php"><i data-lucide="kanban-square"></i><span>Embudo</span></a></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartPipelineStage"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['concentration'])): ?>
                <article class="card dashboard-panel">
                    <div class="card-header"><div><span class="label">Cartera</span><h3>Concentración por cliente</h3></div></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartConcentration"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['sources'])): ?>
                <article class="card dashboard-panel">
                    <div class="card-header"><div><span class="label">Atribución</span><h3>Pipeline por fuente</h3></div></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartSources"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['created_sources'])): ?>
                <article class="card dashboard-panel">
                    <div class="card-header"><div><span class="label">Demanda</span><h3>Oportunidades creadas por fuente</h3></div></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartCreatedSources"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['aging'])): ?>
                <article class="card dashboard-panel">
                    <div class="card-header"><div><span class="label">Cobranza</span><h3>Aging neto de cuentas por cobrar</h3></div></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartAging"></canvas></div>
                </article>
            <?php endif; ?>

            <?php if (!empty($dashboard['charts']['stock_categories'])): ?>
                <article class="card dashboard-panel dashboard-panel-wide">
                    <div class="card-header"><div><span class="label">Inventario</span><h3>SKU activos por categoría</h3></div><a class="btn btn-sm btn-outline" href="/modules/stock/"><i data-lucide="boxes"></i><span>Stock</span></a></div>
                    <div class="card-body dashboard-chart-body"><canvas id="chartStockCategories"></canvas></div>
                </article>
            <?php endif; ?>
        </section>

        <?php if (!empty($dashboard['tables']['alerts']) || !empty($dashboard['tables']['priorities'])): ?>
            <?php $alerts = !empty($dashboard['tables']['alerts']) ? $dashboard['tables']['alerts'] : $dashboard['tables']['priorities']; ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Decisión</span><h3>Alertas priorizadas</h3></div></div>
                <div class="card-body dashboard-alert-list">
                    <?php foreach ($alerts as $alert): ?>
                        <article class="dashboard-alert dashboard-alert-<?php echo safe_text($alert['severity']); ?>">
                            <span class="dashboard-alert-marker"></span>
                            <div><strong><?php echo safe_text($alert['title']); ?></strong><p><?php echo safe_text($alert['detail']); ?></p></div>
                            <div class="dashboard-alert-owner"><span><?php echo safe_text($alert['owner']); ?></span><strong><?php echo safe_text($alert['action']); ?></strong></div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['stale'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Acción requerida</span><h3>Oportunidades vencidas o incompletas</h3></div><a class="btn btn-sm btn-outline" href="/modules/crm/embudo.php"><i data-lucide="external-link"></i><span>Abrir embudo</span></a></div>
                <div class="table-wrap dashboard-table-scroll">
                    <table class="table">
                        <thead><tr><th>Cliente</th><th>Oportunidad</th><th>Etapa</th><th>Próxima acción</th><th>Fecha</th><th>Valor</th></tr></thead>
                        <tbody>
                        <?php foreach ($dashboard['tables']['stale'] as $row): ?>
                            <tr>
                                <td><?php echo safe_text($row['customer_name']); ?></td>
                                <td><a href="/modules/crm/opportunity.php?id=<?php echo (int)$row['id']; ?>"><?php echo safe_text($row['title']); ?></a></td>
                                <td><span class="badge"><?php echo safe_text($row['stage']); ?></span></td>
                                <td><?php echo safe_text($row['next_action'] ?: 'Sin acción'); ?></td>
                                <td><?php echo safe_text($row['next_action_date'] ?: 'Sin fecha'); ?></td>
                                <td><?php echo clp($row['expected_value']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['upcoming'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Próximos 14 días</span><h3>Acciones de cartera</h3></div></div>
                <div class="table-wrap dashboard-table-scroll">
                    <table class="table"><thead><tr><th>Fecha</th><th>Cliente</th><th>Oportunidad</th><th>Acción</th><th>Valor</th><th>Prob.</th></tr></thead><tbody>
                    <?php foreach ($dashboard['tables']['upcoming'] as $row): ?>
                        <tr><td><?php echo safe_text($row['next_action_date']); ?></td><td><?php echo safe_text($row['customer_name']); ?></td><td><a href="/modules/crm/opportunity.php?id=<?php echo (int)$row['id']; ?>"><?php echo safe_text($row['title']); ?></a></td><td><?php echo safe_text($row['next_action']); ?></td><td><?php echo clp($row['expected_value']); ?></td><td><?php echo (int)$row['probability']; ?>%</td></tr>
                    <?php endforeach; ?>
                    </tbody></table>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['receivables'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Cobranza</span><h3>Principales cuentas por cobrar netas</h3></div><a class="btn btn-sm btn-outline" href="/modules/billing/receivables.php"><i data-lucide="hand-coins"></i><span>Gestionar</span></a></div>
                <div class="table-wrap dashboard-table-scroll">
                    <table class="table"><thead><tr><th>Cliente</th><th>Documento</th><th>Emisión</th><th>Vencimiento</th><th>Estado</th><th>Saldo neto</th></tr></thead><tbody>
                    <?php foreach ($dashboard['tables']['receivables'] as $row): ?>
                        <tr><td><?php echo safe_text($row['customer_name']); ?></td><td><?php echo safe_text($row['document_number']); ?></td><td><?php echo safe_text($row['issue_date']); ?></td><td><?php echo safe_text($row['due_date'] ?: 'Sin fecha'); ?></td><td><span class="badge"><?php echo safe_text($row['collection_status']); ?></span></td><td><?php echo clp($row['balance_amount']); ?></td></tr>
                    <?php endforeach; ?>
                    </tbody></table>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['losses'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Aprendizaje</span><h3>Razones de cierre perdido</h3></div></div>
                <div class="table-wrap dashboard-table-scroll"><table class="table"><thead><tr><th>Motivo</th><th>Oportunidades</th><th>Valor asociado</th></tr></thead><tbody>
                    <?php foreach ($dashboard['tables']['losses'] as $row): ?><tr><td><?php echo safe_text($row['reason']); ?></td><td><?php echo (int)$row['count']; ?></td><td><?php echo clp($row['value']); ?></td></tr><?php endforeach; ?>
                </tbody></table></div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['unattributed'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Calidad de datos</span><h3>Oportunidades sin atribución</h3></div></div>
                <div class="table-wrap dashboard-table-scroll"><table class="table"><thead><tr><th>Fecha</th><th>Cliente</th><th>Oportunidad</th><th>Responsable</th><th>Valor</th></tr></thead><tbody>
                    <?php foreach ($dashboard['tables']['unattributed'] as $row): ?><tr><td><?php echo safe_text(substr($row['created_at'], 0, 10)); ?></td><td><?php echo safe_text($row['customer_name']); ?></td><td><a href="/modules/crm/opportunity.php?id=<?php echo (int)$row['id']; ?>"><?php echo safe_text($row['title']); ?></a></td><td><?php echo safe_text($row['owner_name'] ?: 'Sin responsable'); ?></td><td><?php echo clp($row['expected_value']); ?></td></tr><?php endforeach; ?>
                </tbody></table></div>
            </section>
        <?php endif; ?>

        <?php if (!empty($dashboard['tables']['low_stock'])): ?>
            <section class="card dashboard-table-card">
                <div class="card-header"><div><span class="label">Inventario</span><h3>SKU sin stock</h3></div><a class="btn btn-sm btn-outline" href="/modules/products/"><i data-lucide="package"></i><span>Productos</span></a></div>
                <div class="table-wrap dashboard-table-scroll"><table class="table"><thead><tr><th>SKU</th><th>Producto</th><th>Categoría</th><th>Stock</th></tr></thead><tbody>
                    <?php foreach ($dashboard['tables']['low_stock'] as $row): ?><tr><td><?php echo safe_text($row['sku'] ?: 'S/S'); ?></td><td><?php echo safe_text($row['name']); ?></td><td><?php echo safe_text($row['category_name']); ?></td><td><?php echo number_format((float)$row['stock'], 2, ',', '.'); ?> <?php echo safe_text($row['unit']); ?></td></tr><?php endforeach; ?>
                </tbody></table></div>
            </section>
        <?php endif; ?>

        <?php if ($canConfigure): ?>
            <div id="kpiTargetModal" class="product-modal-backdrop dashboard-target-modal" style="display:none;" aria-hidden="true">
                <div class="product-modal-box dashboard-target-modal-box" role="dialog" aria-modal="true" aria-labelledby="kpiTargetModalTitle">
                    <header class="dashboard-target-modal-header">
                        <div>
                            <span class="label" id="kpiTargetModalId">Meta KPI</span>
                            <h2 id="kpiTargetModalTitle">Configurar meta</h2>
                            <p id="kpiTargetModalHint">La meta aprobada se aplicará al período seleccionado.</p>
                        </div>
                        <button class="dashboard-target-close" type="button" data-kpi-target-close aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </header>

                    <form id="kpiTargetForm" class="dashboard-target-form" novalidate>
                        <input type="hidden" name="target_id" value="">
                        <input type="hidden" name="kpi_id" value="">
                        <input type="hidden" name="view" value="<?php echo safe_text($view); ?>">
                        <input type="hidden" name="from" value="<?php echo safe_text($from); ?>">
                        <input type="hidden" name="to" value="<?php echo safe_text($to); ?>">

                        <div class="dashboard-target-grid">
                            <label class="dashboard-target-field dashboard-target-value-field">
                                <span>Valor de la meta <small id="kpiTargetUnit"></small></span>
                                <input class="input" type="number" name="target_value" step="0.01" required inputmode="decimal">
                            </label>
                            <label class="dashboard-target-field">
                                <span>Estado</span>
                                <select class="input" name="status" required>
                                    <option value="draft">Borrador — no aplica todavía</option>
                                    <option value="approved">Aprobada — aplicar al dashboard</option>
                                    <option value="inactive">Inactiva</option>
                                </select>
                            </label>
                            <label class="dashboard-target-field">
                                <span>Vigente desde</span>
                                <input class="input" type="date" name="period_from" required>
                            </label>
                            <label class="dashboard-target-field">
                                <span>Vigente hasta</span>
                                <input class="input" type="date" name="period_to" required>
                            </label>
                        </div>

                        <details class="dashboard-target-advanced">
                            <summary>Umbral de atención opcional</summary>
                            <div class="dashboard-target-grid">
                                <label class="dashboard-target-field">
                                    <span>Umbral amarillo</span>
                                    <input class="input" type="number" name="amber_threshold" step="0.01" inputmode="decimal">
                                </label>
                                <label class="dashboard-target-field">
                                    <span>Umbral crítico de referencia</span>
                                    <input class="input" type="number" name="red_threshold" step="0.01" inputmode="decimal">
                                </label>
                            </div>
                        </details>

                        <label class="dashboard-target-field">
                            <span>Nota o criterio de la meta</span>
                            <textarea class="input dashboard-target-notes" name="notes" rows="3" maxlength="1000" placeholder="Ej.: meta aprobada para el trimestre, responsable y supuesto principal."></textarea>
                        </label>

                        <div id="kpiTargetFeedback" class="dashboard-target-feedback" role="status" aria-live="polite"></div>
                        <footer class="dashboard-target-actions">
                            <button class="btn btn-outline" type="button" data-kpi-target-close>Cancelar</button>
                            <button class="btn btn-primary" id="kpiTargetSubmit" type="submit"><i data-lucide="save"></i><span>Guardar meta</span></button>
                        </footer>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </section>

<script>
(function () {
    var charts = [];
    var chartRetryTimer = null;
    var disposed = false;
    var dashboardMain = document.getElementById('dashboard-suite-main');
    var targetModal = document.getElementById('kpiTargetModal');
    var targetForm = document.getElementById('kpiTargetForm');
    var targetSubmit = document.getElementById('kpiTargetSubmit');
    var targetFeedback = document.getElementById('kpiTargetFeedback');
    var targetView = <?php echo json_encode($view, JSON_UNESCAPED_SLASHES); ?>;
    var targetFrom = <?php echo json_encode($from, JSON_UNESCAPED_SLASHES); ?>;
    var targetTo = <?php echo json_encode($to, JSON_UNESCAPED_SLASHES); ?>;

    function targetUnitLabel(unit) {
        var labels = { clp: 'CLP', pct: '%', x: 'veces', months: 'meses', int: 'cantidad' };
        return labels[unit] || unit || '';
    }

    function targetDirectionLabel(direction) {
        if (direction === 'higher') return 'Un valor mayor o igual a la meta se considera favorable.';
        if (direction === 'lower') return 'Un valor menor o igual a la meta se considera favorable.';
        if (direction === 'range') return 'El KPI se evalúa dentro de un rango objetivo.';
        return 'La meta se mostrará como referencia informativa.';
    }

    function setTargetFeedback(message, state) {
        if (!targetFeedback) return;
        targetFeedback.textContent = message || '';
        targetFeedback.className = 'dashboard-target-feedback' + (state ? ' is-' + state : '');
    }

    function showTargetModal() {
        if (!targetModal) return;
        targetModal.style.display = 'flex';
        targetModal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('is-modal-open');
        window.requestAnimationFrame(function () { targetModal.classList.add('show'); });
        if (window.lucide) window.lucide.createIcons();
    }

    function closeTargetModal() {
        if (!targetModal) return;
        targetModal.classList.remove('show');
        targetModal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('is-modal-open');
        window.setTimeout(function () {
            if (targetModal && targetModal.getAttribute('aria-hidden') === 'true') targetModal.style.display = 'none';
        }, 180);
    }

    function requestTargetJson(url, options) {
        return fetch(url, options || {}).then(function (response) {
            return response.text().then(function (text) {
                var payload = null;
                try { payload = text ? JSON.parse(text) : null; } catch (error) {}
                if (!response.ok || !payload || payload.success === false) {
                    throw new Error(payload && payload.message ? payload.message : 'No fue posible procesar la meta.');
                }
                return payload;
            });
        });
    }

    function openTargetModal(kpiId) {
        if (!targetModal || !targetForm) return;
        targetForm.reset();
        targetForm.elements.kpi_id.value = kpiId;
        targetForm.elements.view.value = targetView;
        targetForm.elements.from.value = targetFrom;
        targetForm.elements.to.value = targetTo;
        targetForm.elements.period_from.value = targetFrom;
        targetForm.elements.period_to.value = targetTo;
        if (targetSubmit) targetSubmit.disabled = false;
        document.getElementById('kpiTargetModalId').textContent = kpiId;
        document.getElementById('kpiTargetModalTitle').textContent = 'Configurar meta';
        document.getElementById('kpiTargetUnit').textContent = '';
        document.getElementById('kpiTargetModalHint').textContent = 'Cargando configuración vigente…';
        setTargetFeedback('Consultando la meta del período…', 'loading');
        showTargetModal();

        var query = new URLSearchParams({ view: targetView, kpi_id: kpiId, from: targetFrom, to: targetTo });
        requestTargetJson('/modules/dashboard/kpi_target_ajax.php?' + query.toString(), { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
            .then(function (payload) {
                var kpi = payload.kpi || {};
                var target = payload.target || null;
                var defaults = payload.defaults || {};
                document.getElementById('kpiTargetModalId').textContent = kpi.id || kpiId;
                document.getElementById('kpiTargetModalTitle').textContent = kpi.name || 'Configurar meta';
                document.getElementById('kpiTargetUnit').textContent = targetUnitLabel(kpi.unit);
                document.getElementById('kpiTargetModalHint').textContent = targetDirectionLabel(kpi.direction);
                targetForm.elements.target_id.value = target ? target.id : '';
                targetForm.elements.target_value.value = target && target.target_value !== null ? target.target_value : (kpi.suggested_target !== null && kpi.suggested_target !== undefined ? kpi.suggested_target : '');
                targetForm.elements.period_from.value = target ? target.period_from : defaults.period_from;
                targetForm.elements.period_to.value = target ? target.period_to : defaults.period_to;
                targetForm.elements.status.value = target ? target.status : defaults.status;
                targetForm.elements.amber_threshold.value = target && target.amber_threshold !== null ? target.amber_threshold : '';
                targetForm.elements.red_threshold.value = target && target.red_threshold !== null ? target.red_threshold : '';
                targetForm.elements.notes.value = target && target.notes ? target.notes : '';
                var step = kpi.unit === 'int' || kpi.unit === 'clp' ? '1' : '0.01';
                targetForm.elements.target_value.step = step;
                targetForm.elements.amber_threshold.step = step;
                targetForm.elements.red_threshold.step = step;
                setTargetFeedback(target ? 'Se cargó la meta vigente o el último borrador del período.' : 'Aún no existe una meta guardada para este período.', 'info');
                targetForm.elements.target_value.focus();
            })
            .catch(function (error) {
                setTargetFeedback(error.message || 'No fue posible cargar la meta.', 'error');
            });
    }

    function submitTargetForm(event) {
        event.preventDefault();
        if (!targetForm || !targetSubmit) return;
        if (!targetForm.reportValidity()) return;
        if (targetForm.elements.period_from.value > targetForm.elements.period_to.value) {
            setTargetFeedback('La fecha de inicio no puede ser posterior a la fecha de término.', 'error');
            return;
        }

        targetSubmit.disabled = true;
        setTargetFeedback('Guardando meta y registrando trazabilidad…', 'loading');
        requestTargetJson('/modules/dashboard/kpi_target_ajax.php', {
            method: 'POST',
            body: new FormData(targetForm),
            headers: { Accept: 'application/json' },
            credentials: 'same-origin'
        }).then(function (payload) {
            setTargetFeedback(payload.message || 'Meta guardada correctamente.', 'success');
            window.setTimeout(function () { window.location.reload(); }, 650);
        }).catch(function (error) {
            setTargetFeedback(error.message || 'No fue posible guardar la meta.', 'error');
            targetSubmit.disabled = false;
        });
    }

    function handleTargetClick(event) {
        var editButton = event.target.closest ? event.target.closest('.dashboard-kpi-target-btn') : null;
        if (editButton && dashboardMain && dashboardMain.contains(editButton)) {
            event.preventDefault();
            event.stopPropagation();
            openTargetModal(editButton.getAttribute('data-kpi-id'));
            return;
        }
        var closeButton = event.target.closest ? event.target.closest('[data-kpi-target-close]') : null;
        if (closeButton && targetModal && targetModal.contains(closeButton)) {
            event.preventDefault();
            closeTargetModal();
            return;
        }
        if (targetModal && event.target === targetModal) closeTargetModal();
    }

    function handleTargetEscape(event) {
        if (event.key === 'Escape' && targetModal && targetModal.getAttribute('aria-hidden') === 'false') closeTargetModal();
    }

    function formatChartValue(value, format) {
        var numeric = Number(value || 0);
        if (format === 'number') return new Intl.NumberFormat('es-CL', { maximumFractionDigits: 2 }).format(numeric);
        if (format === 'percent') return new Intl.NumberFormat('es-CL', { maximumFractionDigits: 1 }).format(numeric) + '%';
        return new Intl.NumberFormat('es-CL', { style: 'currency', currency: 'CLP', maximumFractionDigits: 0 }).format(numeric);
    }

    function makeChart(id, type, labels, values, label, horizontal, format) {
        var canvas = document.getElementById(id);
        if (!canvas || !window.Chart || !labels || !labels.length) return;
        var scales = horizontal
            ? { x: { beginAtZero: true, grid: { color: 'rgba(128,128,128,.12)' } }, y: { grid: { display: false } } }
            : { x: { grid: { display: false } }, y: { beginAtZero: true, grid: { color: 'rgba(128,128,128,.12)' } } };
        charts.push(new window.Chart(canvas, {
            type: type,
            data: { labels: labels, datasets: [{ label: label, data: values, borderWidth: 2, tension: 0.28, fill: type === 'line' }] },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: horizontal ? 'y' : 'x',
                interaction: { intersect: false, mode: 'index' },
                plugins: {
                    legend: { display: false },
                    tooltip: { callbacks: { label: function (ctx) { return label + ': ' + formatChartValue(ctx.raw, format || 'currency'); } } }
                },
                scales: scales
            }
        }));
    }

    var data = <?php echo json_encode($dashboard['charts'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    function renderCharts() {
        if (disposed || !window.Chart) return false;

        charts.forEach(function (chart) {
            try { chart.destroy(); } catch (error) { console.warn('No fue posible limpiar un gr\u00e1fico anterior.', error); }
        });
        charts = [];

        if (data.sales_trend) makeChart('chartSalesTrend', 'line', data.sales_trend.map(function (r) { return r.period; }), data.sales_trend.map(function (r) { return Number(r.net_sales || 0); }), 'Ventas netas', false, 'currency');
        if (data.pipeline_stage) makeChart('chartPipelineStage', 'bar', data.pipeline_stage.map(function (r) { return r.label; }), data.pipeline_stage.map(function (r) { return Number(r.value || 0); }), 'Pipeline', false, 'currency');
        if (data.concentration) makeChart('chartConcentration', 'bar', data.concentration.map(function (r) { return r.label; }), data.concentration.map(function (r) { return Number(r.value || 0); }), 'Ventas', true, 'currency');
        if (data.sources) makeChart('chartSources', 'bar', data.sources.map(function (r) { return r.label; }), data.sources.map(function (r) { return Number(r.value || 0); }), 'Pipeline', true, 'currency');
        if (data.created_sources) makeChart('chartCreatedSources', 'bar', data.created_sources.map(function (r) { return r.label; }), data.created_sources.map(function (r) { return Number(r.count || 0); }), 'Oportunidades', true, 'number');
        if (data.aging) makeChart('chartAging', 'bar', data.aging.map(function (r) { return r.label; }), data.aging.map(function (r) { return Number(r.value || 0); }), 'Saldo', false, 'currency');
        if (data.stock_categories) makeChart('chartStockCategories', 'bar', data.stock_categories.map(function (r) { return r.label; }), data.stock_categories.map(function (r) { return Number(r.value || 0); }), 'SKU activos', true, 'number');

        return true;
    }

    function initializeCharts(attempt) {
        if (disposed || renderCharts()) return;

        if (attempt >= 40) {
            console.error('ICYLAB Dashboard: Chart.js no estuvo disponible despu\u00e9s de esperar su carga.');
            return;
        }

        chartRetryTimer = window.setTimeout(function () {
            initializeCharts(attempt + 1);
        }, 125);
    }

    function cleanupCharts() {
        disposed = true;
        if (chartRetryTimer) window.clearTimeout(chartRetryTimer);
        charts.forEach(function (chart) {
            try { chart.destroy(); } catch (error) { console.warn('No fue posible destruir un gr\u00e1fico del dashboard.', error); }
        });
        charts = [];
        if (dashboardMain) dashboardMain.removeEventListener('click', handleTargetClick);
        if (targetForm) targetForm.removeEventListener('submit', submitTargetForm);
        document.removeEventListener('keydown', handleTargetEscape);
        closeTargetModal();
    }

    if (dashboardMain) dashboardMain.addEventListener('click', handleTargetClick);
    if (targetForm) targetForm.addEventListener('submit', submitTargetForm);
    document.addEventListener('keydown', handleTargetEscape);

    if (window.ICY_SPA_REGISTER_CLEANUP) {
        window.ICY_SPA_REGISTER_CLEANUP(cleanupCharts);
    } else {
        document.addEventListener('icy:spa-before-cleanup', cleanupCharts, { once: true });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { initializeCharts(0); }, { once: true });
    } else {
        initializeCharts(0);
    }

    if (window.lucide) window.lucide.createIcons();
})();
</script>
</main>

<?php require_once '../../layouts/footer.php'; ?>
