<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php'; // 1. Agregamos el motor de permisos
require_once '../../core/format.php';
require_once '../../services/commercial/CommercialDashboardService.php';

require_login();
require_permission('module.commercial'); // 2. Bloqueamos a usuarios no autorizados

$page_title = 'Dashboard Comercial';

$dashboard = new CommercialDashboardService();

$kpis = $dashboard->getKpis();
$todayActions = $dashboard->getTodayActions();
$upcomingActions = $dashboard->getUpcomingActions();

// Compatibilidad: P0/P1 usaban nombres tecnicos pipeline; P1+ usa embudo.
$embudoByStage = method_exists($dashboard, 'getEmbudoByStage')
    ? $dashboard->getEmbudoByStage()
    : $dashboard->getPipelineByStage();
$embudoBySource = method_exists($dashboard, 'getEmbudoBySource')
    ? $dashboard->getEmbudoBySource()
    : $dashboard->getPipelineBySource();
$receivables = $dashboard->getReceivables();

$embudoValue = isset($kpis['embudo_value']) ? $kpis['embudo_value'] : ($kpis['pipeline_value'] ?? 0);
$weightedEmbudo = isset($kpis['weighted_embudo']) ? $kpis['weighted_embudo'] : ($kpis['weighted_pipeline'] ?? 0);

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

?>

<main class="app-main" id="commercial-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">

        <div class="page-header page-header-compact">
            <div class="page-header-content">
                <span class="label">Comercial</span>
                <h1>Dashboard Comercial</h1>
                <p class="text-secondary">Embudo, acciones y cobranza comercial.</p>
            </div>

            <div class="cluster">
                <a class="btn btn-primary" href="/modules/crm/">
                    Abrir CRM
                </a>
                
                <a class="btn btn-outline" href="/modules/crm/embudo.php">
                    Ver embudo
                </a>
            </div>
        </div>

        <section class="grid grid-4">

            <article class="kpi-card">
                <div class="kpi-label">Embudo abierto</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($embudoValue); ?></div>
                </div>
                <p class="kpi-context"><?php echo (int) $kpis['open_opportunities']; ?> oportunidades abiertas</p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Embudo ponderado</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($weightedEmbudo); ?></div>
                </div>
                <p class="kpi-context">Valor ajustado por probabilidad</p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Por cobrar</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($kpis['receivables_amount']); ?></div>
                </div>
                <p class="kpi-context">Cobranza comercial pendiente</p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Atrasado</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($kpis['overdue_amount']); ?></div>
                </div>
                <p class="kpi-context"><?php echo (int) $kpis['overdue_actions']; ?> acciones vencidas</p>
            </article>

        </section>

        <div class="mt-8"></div>

        <section class="grid grid-2">

            <article class="card dashboard-card-sm">
                <div class="card-header">
                    <div>
                        <span class="label">Trabajo diario</span>
                        <h3>Acciones vencidas / de hoy</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-sm">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Cliente</th>
                                    <th>Oportunidad</th>
                                    <th>Acción</th>
                                    <th>Fecha</th>
                                    <th>Valor</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($todayActions as $item): ?>
                                    <tr>
                                        <td><?php echo safe_text($item['customer_name']); ?></td>
                                        <td>
                                            <a href="/modules/crm/opportunity.php?id=<?php echo (int) $item['id']; ?>">
                                                <?php echo safe_text($item['title']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo safe_text($item['next_action']); ?></td>
                                        <td><?php echo safe_text($item['next_action_date']); ?></td>
                                        <td><?php echo clp($item['expected_value']); ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($todayActions)): ?>
                                    <tr>
                                        <td colspan="5">Sin acciones vencidas o para hoy.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <article class="card dashboard-card-sm">
                <div class="card-header">
                    <div>
                        <span class="label">Próximos 7 días</span>
                        <h3>Seguimientos próximos</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-sm">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Cliente</th>
                                    <th>Oportunidad</th>
                                    <th>Acción</th>
                                    <th>Fecha</th>
                                    <th>Prob.</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($upcomingActions as $item): ?>
                                    <tr>
                                        <td><?php echo safe_text($item['customer_name']); ?></td>
                                        <td>
                                            <a href="/modules/crm/opportunity.php?id=<?php echo (int) $item['id']; ?>">
                                                <?php echo safe_text($item['title']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo safe_text($item['next_action']); ?></td>
                                        <td><?php echo safe_text($item['next_action_date']); ?></td>
                                        <td><?php echo (int) $item['probability']; ?>%</td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($upcomingActions)): ?>
                                    <tr>
                                        <td colspan="5">Sin seguimientos próximos.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

        </section>

        <div class="mt-8"></div>

        <section class="grid grid-2">

            <article class="card dashboard-card-sm">
                <div class="card-header">
                    <div>
                        <span class="label">Embudo</span>
                        <h3>Embudo por etapa</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="commercial-list commercial-list-scroll-sm">
                        <?php foreach ($embudoByStage as $stage): ?>
                            <a class="commercial-row" href="/modules/crm/embudo.php">
                                <div>
                                    <strong><?php echo safe_text($stage['stage']); ?></strong>
                                    <span><?php echo (int) $stage['opportunities']; ?> oportunidades</span>
                                </div>

                                <div class="commercial-row-values">
                                    <strong><?php echo clp($stage['total_value']); ?></strong>
                                    <span>Pond. <?php echo clp($stage['weighted_value']); ?></span>
                                </div>
                            </a>
                        <?php endforeach; ?>

                        <?php if (empty($embudoByStage)): ?>
                            <p class="text-secondary">Sin oportunidades registradas.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </article>

            <article class="card dashboard-card-sm">
                <div class="card-header">
                    <div>
                        <span class="label">Marketing</span>
                        <h3>Origen de oportunidades</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="commercial-list commercial-list-scroll-sm">
                        <?php foreach ($embudoBySource as $source): ?>
                            <div class="commercial-row">
                                <div>
                                    <strong><?php echo safe_text($source['source']); ?></strong>
                                    <span><?php echo (int) $source['opportunities']; ?> oportunidades</span>
                                </div>

                                <div class="commercial-row-values">
                                    <strong><?php echo clp($source['total_value']); ?></strong>
                                    <span>Pond. <?php echo clp($source['weighted_value']); ?></span>
                                </div>
                            </div>
                        <?php endforeach; ?>

                        <?php if (empty($embudoBySource)): ?>
                            <p class="text-secondary">Sin origen registrado.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </article>

        </section>

        <div class="mt-8"></div>

        <section class="card dashboard-card-md">
            <div class="card-header">
                <div>
                    <span class="label">Cobranza comercial</span>
                    <h3>Por cobrar y atrasos</h3>
                </div>
            </div>

            <div class="card-body">
                <div class="table-wrap table-scroll-md">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Cliente</th>
                                <th>Oportunidad</th>
                                <th>Estado</th>
                                <th>Vencimiento</th>
                                <th>Valor</th>
                                <th>Responsable</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach ($receivables as $item): ?>
                                <tr>
                                    <td><?php echo safe_text($item['customer_name']); ?></td>
                                    <td>
                                        <a href="/modules/crm/opportunity.php?id=<?php echo (int) $item['id']; ?>">
                                            <?php echo safe_text($item['title']); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <?php if ($item['payment_status'] === 'atrasado'): ?>
                                            <span class="badge badge-error">Atrasado</span>
                                        <?php else: ?>
                                            <span class="badge badge-warning">Por cobrar</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo safe_text($item['payment_due_date']); ?></td>
                                    <td><?php echo clp($item['expected_value']); ?></td>
                                    <td><?php echo safe_text($item['owner_name']); ?></td>
                                </tr>
                            <?php endforeach; ?>

                            <?php if (empty($receivables)): ?>
                                <tr>
                                    <td colspan="6">Sin cobranzas comerciales pendientes.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

    </section>
</main>

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