<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../services/facto/FactoDashboardService.php';
require_once '../../core/format.php';

$factoDashboard = new FactoDashboardService();

$kpis = $factoDashboard->getKpis();
$kpis30 = $factoDashboard->getRollingKpis(30);
$kpis60 = $factoDashboard->getRollingKpis(60);
$kpis90 = $factoDashboard->getRollingKpis(90);
$topCustomers = $factoDashboard->getTopCustomers(5);
$latestDocuments = $factoDashboard->getLatestDocuments(8);
$monthlySales = $factoDashboard->getMonthlySales(12);
$range = isset($_GET['range']) ? (int) $_GET['range'] : 30;

if (!in_array($range, array(30, 60, 90))) {
    $range = 30;
}

$recentSales = $factoDashboard->getRecentSales($range);

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';

require_login();

$page_title = 'Dashboard Ejecutivo';

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

?>

<main class="app-main dashboard-main" id="dashboard-main">

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

    <section class="content">

        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Empresa</span>
                <h2>Dashboard Ejecutivo</h2>
                <p class="text-secondary">
                    Centro de control estratégico de ICYLAB.
                </p>
            </div>

            <div class="cluster">
                <span class="badge badge-success">Sistema activo</span>
                <span class="badge">MVP v1.0</span>
            </div>
        </div>

        <section class="grid grid-4">

            <article class="kpi-card">
                <div class="kpi-label">Facturación mes</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($kpis['sales_month']); ?></div>
                </div>
                <p class="kpi-context">
                    Meta: <?php echo clp($kpis['monthly_target']); ?> · <?php echo pct($kpis['progress']); ?>
                </p>
                <div class="progress">
                    <div class="progress-bar" style="--progress:<?php echo min((int) $kpis['progress'], 100); ?>%;"></div>
                </div>
            </article>
        
            <article class="kpi-card">
                <div class="kpi-label">Documentos mes</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo (int) $kpis['documents_month']; ?></div>
                </div>
                <p class="kpi-context">Ventas emitidas este mes</p>
            </article>
        
            <article class="kpi-card">
                <div class="kpi-label">Clientes mes</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo (int) $kpis['customers_month']; ?></div>
                </div>
                <p class="kpi-context">Clientes con compra mensual</p>
            </article>
        
            <article class="kpi-card">
                <div class="kpi-label">Ticket promedio</div>
                <div class="kpi-main">
                    <div class="kpi-value"><?php echo clp($kpis['average_ticket']); ?></div>
                </div>
                <p class="kpi-context">Promedio por documento</p>
            </article>
        
        </section>
        
        <div class="mt-8"></div>

    <section class="card">
        <div class="card-header">
            <div>
                <span class="label">FACTO</span>
                <h3>Ventas vs Cotizaciones</h3>
            </div>
    
            <div class="cluster">
                <select class="select chart-date" id="chartGroup">
                    <option value="day">Diario</option>
                    <option value="week">Semanal</option>
                    <option value="month">Mensual</option>
                </select>
                <input class="input chart-date" type="date" id="chartFrom">
                <input class="input chart-date" type="date" id="chartTo">
    
            </div>
        </div>
    
        <div class="card-body">
            <div class="chart-wrap">
                <canvas id="salesQuotesChart"></canvas>
            </div>
        </div>
    </section>
            
            <div class="mt-8"></div>
    
    <section class="card">
    
        <div class="card-header">
            <div>
                <span class="label">FACTO</span>
                <h3>Indicadores móviles</h3>
            </div>
        </div>
    
        <div class="card-body">
    
            <div class="table-wrap">
    
                <table class="table">
                    <thead>
                        <tr>
                            <th>Periodo</th>
                            <th>Facturación neta</th>
                            <th>Documentos</th>
                            <th>Clientes</th>
                            <th>Ticket promedio</th>
                        </tr>
                    </thead>
    
                    <tbody>
                        <tr>
                            <td>Últimos 30 días</td>
                            <td><?php echo clp($kpis30['sales']); ?></td>
                            <td><?php echo (int) $kpis30['documents']; ?></td>
                            <td><?php echo (int) $kpis30['customers']; ?></td>
                            <td><?php echo clp($kpis30['average_ticket']); ?></td>
                        </tr>
    
                        <tr>
                            <td>Últimos 60 días</td>
                            <td><?php echo clp($kpis60['sales']); ?></td>
                            <td><?php echo (int) $kpis60['documents']; ?></td>
                            <td><?php echo (int) $kpis60['customers']; ?></td>
                            <td><?php echo clp($kpis60['average_ticket']); ?></td>
                        </tr>
    
                        <tr>
                            <td>Últimos 90 días</td>
                            <td><?php echo clp($kpis90['sales']); ?></td>
                            <td><?php echo (int) $kpis90['documents']; ?></td>
                            <td><?php echo (int) $kpis90['customers']; ?></td>
                            <td><?php echo clp($kpis90['average_ticket']); ?></td>
                        </tr>
                    </tbody>
                </table>
    
            </div>
    
        </div>
    
    </section>
    
            <div class="mt-8"></div>
    
    <section class="grid grid-2">
    
                <article class="card">
                    <div class="card-header">
                        <div>
                            <span class="label">Scoreboard</span>
                            <h3>KPIs Estratégicos</h3>
                        </div>
                    </div>
    
                    <div class="card-body">
                        <div class="metric-row">
                            <span>Ventas del mes</span>
                            <strong class="metric-value">0</strong>
                        </div>
    
                        <div class="metric-row">
                            <span>Cotizaciones abiertas</span>
                            <strong class="metric-value">0</strong>
                        </div>
    
                        <div class="metric-row">
                            <span>Producciones activas</span>
                            <strong class="metric-value">0</strong>
                        </div>
    
                        <div class="metric-row">
                            <span>QA pendientes</span>
                            <strong class="metric-value">0</strong>
                        </div>
                    </div>
                </article>
                
                <article class="card">
                    <div class="card-header">
                        <div>
                            <span class="label">FACTO</span>                        <h3>Top clientes</h3>
                        </div>
                    </div>
                
                    <div class="card-body">
                        <div class="table-wrap">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Cliente</th>
                                        <th>Ventas netas</th>
                                        <th>Docs</th>
                                        <th>Última compra</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topCustomers as $customer): ?>
                                        <tr>
                                            <td><?php echo safe_text($customer['receiver_legal_name']); ?></td>
                                            <td><?php echo clp($customer['total_sales']); ?></td>
                                            <td><?php echo (int) $customer['document_count']; ?></td>
                                            <td><?php echo safe_text($customer['last_purchase']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                
                                    <?php if (empty($topCustomers)): ?>
                                        <tr>
                                            <td colspan="4">Sin datos sincronizados desde FACTO.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </article>
    </section>
                
     <div class="mt-8"></div>
    
    <section class="card">
                
            
                <article class="card">
                    <div class="card-header">
                        <div>
                            <span class="label">FACTO</span>
                            <h3>Últimos documentos</h3>
                        </div>
                    </div>
                
                    <div class="card-body">
                        <div class="table-wrap">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Fecha</th>
                                        <th>Folio</th>
                                        <th>Tipo</th>
                                        <th>Cliente</th>
                                        <th>Efecto neto</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($latestDocuments as $doc): ?>
                                        <tr>
                                            <td><?php echo safe_text($doc['issue_date']); ?></td>
                                            <td><?php echo safe_text($doc['document_number']); ?></td>
                                            <td><?php echo safe_text($doc['document_label']); ?></td>
                                            <td><?php echo safe_text($doc['receiver_legal_name']); ?></td>
                                            <td><?php echo clp($doc['net_sales_effect']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                
                                    <?php if (empty($latestDocuments)): ?>
                                        <tr>
                                            <td colspan="4">Sin documentos emitidos sincronizados.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </article>
                
    </section>

</main>


<script>
(function () {
    var chartEl = document.getElementById('salesQuotesChart');

    if (!chartEl) {
        return;
    }

    var fromInput = document.getElementById('chartFrom');
    var toInput = document.getElementById('chartTo');
    var groupInput = document.getElementById('chartGroup');
    var rangeButtons = document.querySelectorAll('[data-range]');
    var chart = null;

    function formatDate(date) {
        return date.toISOString().slice(0, 10);
    }

    function setRange(months) {
        var to = new Date();
        var from = new Date();

        from.setMonth(from.getMonth() - months);

        fromInput.value = formatDate(from);
        toInput.value = formatDate(to);

        if (months <= 2) {
            groupInput.value = 'day';
        } else if (months <= 6) {
            groupInput.value = 'week';
        } else {
            groupInput.value = 'month';
        }

        loadChart();
    }

    function loadChart() {
        var from = fromInput.value;
        var to = toInput.value;
        var group = groupInput.value;

        fetch('/api/dashboard/sales_quotes_chart.php?from=' + from + '&to=' + to + '&group=' + group)
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                renderChart(data);
            });
    }

    function renderChart(data) {
        if (chart) {
            chart.destroy();
        }

        chart = new Chart(chartEl, {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [
                    {
                        label: 'Ventas netas CLP',
                        data: data.sales,
                        yAxisID: 'y',
                        tension: 0.35,
                        borderWidth: 2,
                        pointRadius: 2
                    },
                    {
                        label: 'Cotizaciones emitidas',
                        data: data.quotes,
                        yAxisID: 'y1',
                        tension: 0.35,
                        borderWidth: 2,
                        pointRadius: 2
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: data.group === 'day'
                                ? 'Días'
                                : data.group === 'week'
                                    ? 'Semanas'
                                    : 'Meses'
                        }
                    },
                    y: {
                        position: 'left',
                        ticks: {
                            callback: function (value) {
                                return '$' + new Intl.NumberFormat('es-CL').format(value);
                            }
                        },
                        title: {
                            display: true,
                            text: 'Ventas'
                        }
                    },
                    y1: {
                        position: 'right',
                        grid: {
                            drawOnChartArea: false
                        },
                        title: {
                            display: true,
                            text: 'Cotizaciones'
                        }
                    }
                }
            }
        });
    }

    rangeButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            setRange(parseInt(button.getAttribute('data-range'), 10));
        });
    });

    fromInput.addEventListener('change', loadChart);
    toInput.addEventListener('change', loadChart);
    groupInput.addEventListener('change', loadChart);

    setRange(12);
})();
</script>

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