<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../core/database.php';
require_once '../../services/crm/CrmService.php';

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

$page_title = 'Oportunidades cerradas';
$pdo = db();
$currentUser = current_user() ?: array();
$currentRole = (string)($currentUser['role'] ?? '');
$currentUserId = (int)($currentUser['id'] ?? 0);
$isOwnPortfolioOnly = ($currentRole === 'comercial');
$canFinancialReverse = in_array($currentRole, array('admin','administracion'), true);

$search = trim((string)($_GET['q'] ?? ''));
$outcome = trim((string)($_GET['outcome'] ?? ''));
$ownerId = isset($_GET['owner']) && $_GET['owner'] !== '' ? (int)$_GET['owner'] : null;
$dateFrom = trim((string)($_GET['from'] ?? ''));
$dateTo = trim((string)($_GET['to'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 50;
$offset = ($page - 1) * $perPage;

$outcomeLabels = array(
    'won' => 'Ganada',
    'lost' => 'Perdida',
    'invoiced' => 'Facturada',
    'cancelled' => 'Cancelada',
    'no_decision' => 'Sin decisión',
);
$activeStageLabels = array(
    'nuevo' => 'Nuevo',
    'contactado' => 'Contactado',
    'cotizando' => 'Cotizando',
    'negociacion' => 'Negociación',
);

$where = array('o.deleted_at IS NULL', 'o.archived_at IS NOT NULL');
$params = array();

if ($isOwnPortfolioOnly) {
    $where[] = 'o.owner_user_id = ?';
    $params[] = $currentUserId;
} elseif ($ownerId) {
    $where[] = 'o.owner_user_id = ?';
    $params[] = $ownerId;
}
if ($outcome !== '' && isset($outcomeLabels[$outcome])) {
    $where[] = 'o.closure_outcome = ?';
    $params[] = $outcome;
}
if ($dateFrom !== '') {
    $where[] = 'DATE(o.archived_at) >= ?';
    $params[] = $dateFrom;
}
if ($dateTo !== '') {
    $where[] = 'DATE(o.archived_at) <= ?';
    $params[] = $dateTo;
}
if ($search !== '') {
    $where[] = '(o.title LIKE ? OR o.customer_name LIKE ? OR o.customer_tax_id LIKE ? OR o.closure_reason LIKE ?)';
    $needle = '%' . $search . '%';
    array_push($params, $needle, $needle, $needle, $needle);
}

$whereSql = implode(' AND ', $where);

$summarySql = "\n    SELECT\n        COUNT(*) AS total_closed,\n        SUM(CASE WHEN o.closure_outcome IN ('won','invoiced') THEN 1 ELSE 0 END) AS positive_count,\n        SUM(CASE WHEN o.closure_outcome IN ('lost','cancelled','no_decision') THEN 1 ELSE 0 END) AS negative_count,\n        COALESCE(SUM(CASE WHEN o.closure_outcome IN ('won','invoiced') THEN o.expected_value ELSE 0 END), 0) AS positive_value,\n        COALESCE(AVG(DATEDIFF(COALESCE(o.commercial_closed_at,o.closed_at,o.archived_at), o.created_at)), 0) AS avg_cycle_days\n    FROM crm_opportunities o\n    WHERE $whereSql\n";
$stmt = $pdo->prepare($summarySql);
$stmt->execute($params);
$summary = $stmt->fetch(PDO::FETCH_ASSOC) ?: array();
$totalClosed = (int)($summary['total_closed'] ?? 0);
$positiveCount = (int)($summary['positive_count'] ?? 0);
$negativeCount = (int)($summary['negative_count'] ?? 0);
$conversionRate = $totalClosed > 0 ? ($positiveCount / $totalClosed) * 100 : null;

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM crm_opportunities o WHERE $whereSql");
$countStmt->execute($params);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));

$listSql = "\n    SELECT\n        o.id, o.title, o.customer_name, o.customer_tax_id, o.expected_value, o.probability,\n        o.owner_name, o.owner_user_id, o.stage, o.closure_outcome, o.closure_reason, o.closure_note,\n        o.created_at, o.commercial_closed_at, o.closed_at, o.archived_at, o.archive_source, o.updated_at,\n        DATEDIFF(COALESCE(o.commercial_closed_at,o.closed_at,o.archived_at), o.created_at) AS cycle_days,\n        u.name AS closed_by_name\n    FROM crm_opportunities o\n    LEFT JOIN users u ON u.id = o.closed_by_user_id\n    WHERE $whereSql\n    ORDER BY o.archived_at DESC, o.id DESC\n    LIMIT $perPage OFFSET $offset\n";
$stmt = $pdo->prepare($listSql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$crm = new CrmService();
$assignableUsers = $crm->getAssignableUsers();

$distributionSql = "\n    SELECT COALESCE(o.closure_outcome, 'no_decision') AS outcome, COUNT(*) AS total\n    FROM crm_opportunities o\n    WHERE $whereSql\n    GROUP BY COALESCE(o.closure_outcome, 'no_decision')\n    ORDER BY total DESC\n";
$stmt = $pdo->prepare($distributionSql);
$stmt->execute($params);
$distribution = $stmt->fetchAll(PDO::FETCH_ASSOC);

function archive_date_label($value)
{
    if (!$value) return '—';
    $timestamp = strtotime((string)$value);
    return $timestamp ? date('d-m-Y', $timestamp) : (string)$value;
}

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

<main class="app-main" id="closed-opportunities-main">
    <style>
        #closed-opportunities-main .content { padding-bottom: 28px; }
        #closed-opportunities-main .archive-header { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:18px; }
        #closed-opportunities-main .archive-header h1 { margin:2px 0 4px; }
        #closed-opportunities-main .archive-actions { display:flex; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
        #closed-opportunities-main .archive-kpis { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:12px; margin-bottom:14px; }
        #closed-opportunities-main .archive-kpi { background:var(--surface-1); border:1px solid var(--border-default); border-radius:var(--radius-lg); padding:16px; min-width:0; }
        #closed-opportunities-main .archive-kpi span { display:block; color:var(--text-muted); font-size:.76rem; font-weight:650; text-transform:uppercase; letter-spacing:.04em; }
        #closed-opportunities-main .archive-kpi strong { display:block; margin-top:7px; color:var(--text-primary); font-size:1.35rem; line-height:1.1; }
        #closed-opportunities-main .archive-kpi small { display:block; margin-top:7px; color:var(--text-secondary); }
        #closed-opportunities-main .archive-filter-card { margin-bottom:14px; }
        #closed-opportunities-main .archive-filter-grid { display:grid; grid-template-columns:minmax(220px,2fr) repeat(4,minmax(145px,1fr)) auto; gap:10px; align-items:end; }
        #closed-opportunities-main .archive-filter-grid .form-field { margin:0; }
        #closed-opportunities-main .archive-table-card { overflow:hidden; }
        #closed-opportunities-main .archive-outcome { display:inline-flex; align-items:center; gap:7px; font-size:.78rem; font-weight:650; }
        #closed-opportunities-main .archive-outcome::before { content:''; width:8px; height:8px; border-radius:50%; background:var(--text-muted); }
        #closed-opportunities-main .archive-outcome-won::before,
        #closed-opportunities-main .archive-outcome-invoiced::before { background:var(--color-success); }
        #closed-opportunities-main .archive-outcome-lost::before,
        #closed-opportunities-main .archive-outcome-cancelled::before { background:var(--color-error); }
        #closed-opportunities-main .archive-outcome-no_decision::before { background:var(--color-warning); }
        #closed-opportunities-main .archive-reason { max-width:260px; white-space:normal; line-height:1.35; }
        #closed-opportunities-main .archive-row-actions { display:flex; align-items:center; justify-content:flex-end; gap:6px; }
        #closed-opportunities-main .archive-empty { text-align:center; padding:42px 20px; color:var(--text-secondary); }
        #closed-opportunities-main .archive-empty i { width:34px; height:34px; margin-bottom:10px; color:var(--text-muted); }
        #closed-opportunities-main .archive-pagination { display:flex; justify-content:space-between; align-items:center; gap:12px; padding:14px 16px; border-top:1px solid var(--border-subtle); }
        #closed-opportunities-main .archive-pagination-actions { display:flex; gap:8px; }
        #closed-opportunities-main .archive-chart { height:220px; }
        #closed-opportunities-main .archive-grid-bottom { display:grid; grid-template-columns:minmax(0,1.45fr) minmax(280px,.55fr); gap:14px; }
        @media (max-width: 1080px) {
            #closed-opportunities-main .archive-kpis { grid-template-columns:repeat(2,minmax(0,1fr)); }
            #closed-opportunities-main .archive-filter-grid { grid-template-columns:repeat(3,minmax(0,1fr)); }
            #closed-opportunities-main .archive-filter-grid .archive-search { grid-column:span 2; }
            #closed-opportunities-main .archive-grid-bottom { grid-template-columns:1fr; }
        }
        @media (max-width: 760px) {
            #closed-opportunities-main .archive-header { align-items:stretch; flex-direction:column; }
            #closed-opportunities-main .archive-actions { justify-content:stretch; }
            #closed-opportunities-main .archive-actions .btn { flex:1; }
            #closed-opportunities-main .archive-kpis { grid-template-columns:1fr 1fr; gap:8px; }
            #closed-opportunities-main .archive-kpi { padding:13px; }
            #closed-opportunities-main .archive-filter-grid { grid-template-columns:1fr 1fr; }
            #closed-opportunities-main .archive-filter-grid .archive-search { grid-column:1 / -1; }
            #closed-opportunities-main .archive-filter-actions { grid-column:1 / -1; display:flex; }
            #closed-opportunities-main .archive-filter-actions .btn { flex:1; }
            #closed-opportunities-main .archive-table-card .table-wrap { max-height:none; }
            #closed-opportunities-main .archive-pagination { align-items:stretch; flex-direction:column; }
            #closed-opportunities-main .archive-pagination-actions { width:100%; }
            #closed-opportunities-main .archive-pagination-actions .btn { flex:1; }
        }
    </style>

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

    <section class="content">
        <header class="archive-header">
            <div>
                <span class="label">CRM · HISTÓRICO</span>
                <h1>Oportunidades cerradas</h1>
                <p class="text-secondary">Archivo comercial para análisis de conversión, ciclo y razones de cierre.</p>
            </div>
            <div class="archive-actions">
                <a class="btn btn-outline" href="/modules/crm/embudo.php"><i data-lucide="kanban-square"></i><span>Embudo activo</span></a>
                <a class="btn btn-primary" href="/modules/dashboard/?view=commercial"><i data-lucide="chart-no-axes-combined"></i><span>Analizar cartera</span></a>
            </div>
        </header>

        <section class="archive-kpis" aria-label="Resumen de oportunidades cerradas">
            <article class="archive-kpi"><span>Cierres</span><strong><?php echo number_format($totalClosed, 0, ',', '.'); ?></strong><small>Registros del filtro actual</small></article>
            <article class="archive-kpi"><span>Conversión positiva</span><strong><?php echo $conversionRate === null ? 'N/D' : number_format($conversionRate, 1, ',', '.') . '%'; ?></strong><small><?php echo number_format($positiveCount, 0, ',', '.'); ?> ganadas o facturadas</small></article>
            <article class="archive-kpi"><span>Valor positivo</span><strong><?php echo clp((float)($summary['positive_value'] ?? 0)); ?></strong><small>Valor esperado de cierres positivos</small></article>
            <article class="archive-kpi"><span>Ciclo promedio</span><strong><?php echo $totalClosed > 0 ? number_format((float)($summary['avg_cycle_days'] ?? 0), 1, ',', '.') . ' días' : 'N/D'; ?></strong><small>Desde creación hasta cierre</small></article>
        </section>

        <section class="card archive-filter-card">
            <div class="card-body">
                <form method="GET" class="archive-filter-grid" data-no-spa="true">
                    <div class="form-field archive-search"><label class="label" for="archiveSearch">Buscar</label><div class="input-with-icon"><i data-lucide="search"></i><input class="input" id="archiveSearch" name="q" value="<?php echo safe_text($search); ?>" placeholder="Oportunidad, cliente, RUT o motivo"></div></div>
                    <div class="form-field"><label class="label" for="archiveOutcome">Resultado</label><select class="select" id="archiveOutcome" name="outcome"><option value="">Todos</option><?php foreach ($outcomeLabels as $key => $label): ?><option value="<?php echo safe_text($key); ?>" <?php echo $outcome === $key ? 'selected' : ''; ?>><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                    <?php if (!$isOwnPortfolioOnly): ?><div class="form-field"><label class="label" for="archiveOwner">Responsable</label><select class="select" id="archiveOwner" name="owner"><option value="">Todos</option><?php foreach ($assignableUsers as $user): ?><option value="<?php echo (int)$user['id']; ?>" <?php echo $ownerId === (int)$user['id'] ? 'selected' : ''; ?>><?php echo safe_text($user['name']); ?></option><?php endforeach; ?></select></div><?php endif; ?>
                    <div class="form-field"><label class="label" for="archiveFrom">Desde</label><input class="input" type="date" id="archiveFrom" name="from" value="<?php echo safe_text($dateFrom); ?>"></div>
                    <div class="form-field"><label class="label" for="archiveTo">Hasta</label><input class="input" type="date" id="archiveTo" name="to" value="<?php echo safe_text($dateTo); ?>"></div>
                    <div class="archive-filter-actions"><button class="btn btn-primary" type="submit"><i data-lucide="filter"></i><span>Aplicar</span></button></div>
                </form>
            </div>
        </section>

        <div class="archive-grid-bottom">
            <section class="card archive-table-card">
                <div class="card-header"><div><span class="label">HISTÓRICO</span><h3><?php echo number_format($totalRows, 0, ',', '.'); ?> oportunidades</h3></div></div>
                <?php if (!empty($rows)): ?>
                    <div class="table-wrap">
                        <table class="table">
                            <thead><tr><th>Cierre</th><th>Cliente / oportunidad</th><th>Resultado</th><th>Responsable</th><th>Ciclo</th><th>Valor</th><th style="text-align:right;">Acciones</th></tr></thead>
                            <tbody>
                            <?php foreach ($rows as $row): $rowOutcome = (string)($row['closure_outcome'] ?: 'no_decision'); ?>
                                <tr>
                                    <td data-label="Cierre"><strong><?php echo safe_text(archive_date_label($row['archived_at'])); ?></strong><br><span class="text-muted text-sm"><?php echo safe_text($row['closed_by_name'] ?: 'Sistema'); ?></span></td>
                                    <td data-label="Cliente / oportunidad"><a href="/modules/crm/opportunity.php?id=<?php echo (int)$row['id']; ?>"><strong><?php echo safe_text($row['title']); ?></strong></a><br><span class="text-secondary text-sm"><?php echo safe_text($row['customer_name']); ?><?php if (!empty($row['customer_tax_id'])): ?> · <?php echo safe_text($row['customer_tax_id']); ?><?php endif; ?></span></td>
                                    <td data-label="Resultado"><span class="archive-outcome archive-outcome-<?php echo safe_text($rowOutcome); ?>"><?php echo safe_text($outcomeLabels[$rowOutcome] ?? $rowOutcome); ?></span><?php if (!empty($row['closure_reason'])): ?><div class="archive-reason text-secondary text-sm" title="<?php echo safe_text($row['closure_note'] ?? ''); ?>"><?php echo safe_text($row['closure_reason']); ?></div><?php endif; ?></td>
                                    <td data-label="Responsable"><?php echo safe_text($row['owner_name'] ?: 'Sin responsable'); ?></td>
                                    <td data-label="Ciclo"><?php echo $row['cycle_days'] !== null ? number_format((int)$row['cycle_days'], 0, ',', '.') . ' días' : 'N/D'; ?></td>
                                    <td data-label="Valor"><strong><?php echo clp((float)$row['expected_value']); ?></strong></td>
                                    <td data-label="Acciones">
                                        <div class="archive-row-actions">
                                            <?php if ($rowOutcome !== 'invoiced' || $canFinancialReverse): ?>
                                                <button type="button" class="btn btn-sm btn-outline" onclick="window.reopenArchivedOpportunity(<?php echo (int)$row['id']; ?>, <?php echo htmlspecialchars(json_encode((string)$row['title'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8'); ?>, <?php echo htmlspecialchars(json_encode($rowOutcome), ENT_QUOTES, 'UTF-8'); ?>)"><i data-lucide="rotate-ccw"></i><span><?php echo $rowOutcome === 'invoiced' ? 'Reversión' : 'Reabrir'; ?></span></button>
                                            <?php else: ?>
                                                <span class="text-muted text-sm" title="Las recompras deben registrarse como una nueva oportunidad">Cierre financiero</span>
                                            <?php endif; ?>
                                            <a class="icon-btn" href="/modules/crm/opportunity.php?id=<?php echo (int)$row['id']; ?>" title="Ver detalle"><i data-lucide="arrow-up-right"></i></a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <footer class="archive-pagination">
                        <span class="text-secondary text-sm">Página <?php echo $page; ?> de <?php echo $totalPages; ?></span>
                        <div class="archive-pagination-actions">
                            <?php $queryBase = $_GET; unset($queryBase['page']); ?>
                            <a class="btn btn-sm btn-outline <?php echo $page <= 1 ? 'is-disabled' : ''; ?>" <?php echo $page <= 1 ? 'aria-disabled="true"' : 'href="?' . safe_text(http_build_query(array_merge($queryBase, array('page' => $page - 1)))) . '"'; ?>><i data-lucide="chevron-left"></i><span>Anterior</span></a>
                            <a class="btn btn-sm btn-outline <?php echo $page >= $totalPages ? 'is-disabled' : ''; ?>" <?php echo $page >= $totalPages ? 'aria-disabled="true"' : 'href="?' . safe_text(http_build_query(array_merge($queryBase, array('page' => $page + 1)))) . '"'; ?>><span>Siguiente</span><i data-lucide="chevron-right"></i></a>
                        </div>
                    </footer>
                <?php else: ?>
                    <div class="archive-empty"><i data-lucide="archive"></i><h3>Sin cierres en este filtro</h3><p>Ajusta los filtros o vuelve al embudo activo.</p></div>
                <?php endif; ?>
            </section>

            <section class="card">
                <div class="card-header"><div><span class="label">DISTRIBUCIÓN</span><h3>Resultados de cierre</h3></div></div>
                <div class="card-body archive-chart"><canvas id="closedOutcomeChart"></canvas></div>
            </section>
        </div>
    </section>
</main>

<div id="reopenOpportunityModal" class="product-modal-backdrop" style="display:none;">
    <div class="product-modal-box" style="width:min(480px,calc(100vw - 28px));max-width:480px;" role="dialog" aria-modal="true" aria-labelledby="reopenOpportunityTitle">
        <div class="product-modal-header">
            <div><h2 class="h3" id="reopenOpportunityTitle">Reabrir oportunidad</h2><span class="text-secondary text-sm" id="reopenOpportunitySubtitle">La oportunidad volverá al embudo activo.</span></div>
            <button type="button" class="icon-btn" onclick="window.closeReopenOpportunityModal()" aria-label="Cerrar"><i data-lucide="x"></i></button>
        </div>
        <div class="product-modal-body">
            <form id="reopenOpportunityForm" action="/modules/crm/opportunity_reopen.php" method="POST" data-no-spa="true" style="margin:0;">
                <input type="hidden" name="_csrf_token" value="<?php echo safe_text(csrf_token()); ?>">
                <input type="hidden" name="id" id="reopenOpportunityId" value="">
                <div class="form-field is-required">
                    <label class="label" for="reopenOpportunityStage">Etapa de retorno</label>
                    <select class="select" id="reopenOpportunityStage" name="stage" required>
                        <?php foreach ($activeStageLabels as $key => $label): ?><option value="<?php echo safe_text($key); ?>" <?php echo $key === 'negociacion' ? 'selected' : ''; ?>><?php echo safe_text($label); ?></option><?php endforeach; ?>
                    </select>
                    <span class="text-muted text-sm">Usa la etapa que refleje el próximo paso real, no la etapa histórica de cierre.</span>
                </div>
                <input type="hidden" id="reopenOpportunityOutcome" value="">
                <div class="form-field is-required">
                    <label class="label" for="reopenOpportunityReason">Motivo de reapertura</label>
                    <textarea class="textarea" id="reopenOpportunityReason" name="reason" rows="2" required placeholder="Qué cambió y por qué vuelve al pipeline"></textarea>
                </div>
                <div class="form-grid form-grid-2">
                    <div class="form-field is-required">
                        <label class="label" for="reopenOpportunityNextAction">Próxima acción</label>
                        <select class="select" id="reopenOpportunityNextAction" name="next_action" required>
                            <option value="">Seleccionar</option><option value="Llamar">Llamar</option><option value="Enviar cotización">Enviar cotización</option><option value="Enviar muestra">Enviar muestra</option><option value="Agendar reunión">Agendar reunión</option><option value="Hacer seguimiento">Hacer seguimiento</option><option value="Esperar respuesta">Esperar respuesta</option>
                        </select>
                    </div>
                    <div class="form-field is-required">
                        <label class="label" for="reopenOpportunityNextDate">Fecha próxima acción</label>
                        <input class="input" type="date" id="reopenOpportunityNextDate" name="next_action_date" required min="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                <?php if ($canFinancialReverse): ?>
                <div class="form-field" id="reopenFinancialReversalBlock" style="display:none;padding:12px;border:1px solid var(--color-warning);border-radius:10px;background:var(--surface-2);">
                    <label style="display:flex;gap:10px;align-items:flex-start;cursor:pointer;">
                        <input type="checkbox" name="allow_financial_reversal" value="1" id="reopenFinancialReversal">
                        <span><strong>Reversión administrativa</strong><br><small class="text-secondary">Solo procede si el DTE fue anulado o dejó de estar vigente. Una recompra debe registrarse como nueva oportunidad.</small></span>
                    </label>
                </div>
                <?php endif; ?>
            </form>
        </div>
        <div class="product-modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.closeReopenOpportunityModal()">Cancelar</button>
            <button type="submit" form="reopenOpportunityForm" class="btn btn-primary" id="reopenOpportunitySubmit"><i data-lucide="rotate-ccw"></i><span>Reabrir en el embudo</span></button>
        </div>
    </div>
</div>

<script>
(function () {
    const csrfToken = <?php echo json_encode(csrf_token(), JSON_UNESCAPED_SLASHES); ?>;
    const labels = <?php echo json_encode(array_map(function ($row) use ($outcomeLabels) { $key = $row['outcome']; return $outcomeLabels[$key] ?? $key; }, $distribution), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    const values = <?php echo json_encode(array_map(function ($row) { return (int)$row['total']; }, $distribution), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    window.reopenArchivedOpportunity = function (id, title, outcome) {
        const modal = document.getElementById('reopenOpportunityModal');
        const form = document.getElementById('reopenOpportunityForm');
        if (!modal || !form) return;
        form.reset();
        document.getElementById('reopenOpportunityId').value = id;
        document.getElementById('reopenOpportunityStage').value = 'negociacion';
        document.getElementById('reopenOpportunityOutcome').value = outcome || '';
        const reversalBlock = document.getElementById('reopenFinancialReversalBlock');
        const reversalCheck = document.getElementById('reopenFinancialReversal');
        if (reversalBlock) reversalBlock.style.display = outcome === 'invoiced' ? 'block' : 'none';
        if (reversalCheck) reversalCheck.checked = false;
        document.getElementById('reopenOpportunitySubtitle').textContent = '“' + title + '” volverá al embudo activo.';
        modal.style.display = 'flex';
        setTimeout(function () { modal.classList.add('show'); }, 10);
        if (window.lucide) window.lucide.createIcons();
    };

    window.closeReopenOpportunityModal = function () {
        const modal = document.getElementById('reopenOpportunityModal');
        if (!modal) return;
        modal.classList.remove('show');
        setTimeout(function () { modal.style.display = 'none'; }, 180);
    };

    const reopenForm = document.getElementById('reopenOpportunityForm');
    if (reopenForm) {
        reopenForm.addEventListener('submit', function (event) {
            event.preventDefault();
            if (!this.reportValidity()) return;
            const button = document.getElementById('reopenOpportunitySubmit');
            const originalHtml = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i data-lucide="loader" class="spin-icon"></i><span>Reabriendo...</span>';
            if (window.lucide) window.lucide.createIcons();
            const formData = new FormData(this);
            const id = formData.get('id');
            fetch(this.action, { method: 'POST', body: formData })
                .then(function (response) { return response.json().then(function (data) { return { ok: response.ok, data: data }; }); })
                .then(function (result) {
                    if (!result.ok || !result.data.success) throw new Error(result.data.error || 'No fue posible reabrir la oportunidad.');
                    if (window.ICY_SPA_CLEAR_CACHE) window.ICY_SPA_CLEAR_CACHE();
                    if (window.ICY_SPA_GO) window.ICY_SPA_GO('/modules/crm/embudo.php?open_modal=' + id, { force: true });
                    else window.location.href = '/modules/crm/embudo.php?open_modal=' + id;
                })
                .catch(function (error) {
                    window.alert(error.message);
                    button.disabled = false;
                    button.innerHTML = originalHtml;
                    if (window.lucide) window.lucide.createIcons();
                });
        });
    }

    const reopenModal = document.getElementById('reopenOpportunityModal');
    if (reopenModal) reopenModal.addEventListener('click', function (event) { if (event.target === reopenModal) window.closeReopenOpportunityModal(); });


    let closedOutcomeChartInstance = null;
    function renderChart() {
        const canvas = document.getElementById('closedOutcomeChart');
        if (!canvas || typeof Chart === 'undefined') return;
        if (closedOutcomeChartInstance) closedOutcomeChartInstance.destroy();
        closedOutcomeChartInstance = new Chart(canvas, {
            type: 'doughnut',
            data: { labels: labels.length ? labels : ['Sin datos'], datasets: [{ data: values.length ? values : [1] }] },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '68%',
                plugins: {
                    legend: { position: 'bottom', labels: { usePointStyle: true, boxWidth: 8 } },
                    tooltip: { callbacks: { label: function (context) { return context.label + ': ' + context.raw; } } }
                }
            }
        });
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', renderChart, { once: true });
    else renderChart();
    if (window.ICY_SPA_REGISTER_CLEANUP) {
        window.ICY_SPA_REGISTER_CLEANUP(function() {
            if (closedOutcomeChartInstance) closedOutcomeChartInstance.destroy();
            const modal = document.getElementById('reopenOpportunityModal');
            if (modal) modal.remove();
        });
    }
    if (window.lucide) window.lucide.createIcons();
})();
</script>

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