<?php
// 1. SEGURIDAD Y CONTEXTO
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

// Configuración Multiusuario Dinámica
$DB_TARGET = "MS_Datos"; 
$IDUg_SISTEMA = $_SESSION['IDUg'] ?? 1; 

// Tabla dinámica por usuario: ej. "1-FinanzasPresupuesto"
$TABLA_TARGET = $IDUg_SISTEMA."-FinanzasPresupuesto"; 
$SQL_PATH = "`$DB_TARGET`.`$TABLA_TARGET`";
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">


<style>
    :root { 
        --wealth-primary: #1e293b; --wealth-accent: #3b82f6; 
        --wealth-success: #10b981; --wealth-danger: #ef4444; 
    }
    body { background-color: #f8fafc; font-family: 'Inter', sans-serif; color: #334155; }
    
    .glass-card { background: white; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
    .kpi-value { font-size: 1.8rem; font-weight: 800; color: var(--wealth-primary); letter-spacing: -0.04em; }
    
    /* Widget Budget Planner */
    .bucket-card { padding: 15px; border-radius: 16px; background: #f1f5f9; border-left: 5px solid #cbd5e1; }
    .bucket-label { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; color: #64748b; }
    .bucket-amount { font-size: 1.1rem; font-weight: 800; }

    /* Advisor UI */
    .advisor-item { border-left: 4px solid #e2e8f0; background: white; padding: 12px; border-radius: 10px; margin-bottom: 10px; font-size: 0.8rem; }
    .alert-high { border-left-color: var(--wealth-danger); background: #fef2f2; }
    .alert-success { border-left-color: var(--wealth-success); background: #f0fdf4; }

    .nav-tabs-custom .nav-link { border: none; color: #64748b; font-weight: 600; font-size: 0.85rem; }
    .nav-tabs-custom .nav-link.active { color: var(--wealth-accent); background: white; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-radius: 10px; }
</style>

<div class="container-fluid p-4">
    <div class="row mb-4 align-items-center">
        <div class="col-md-6">
            <h3 class="fw-800 text-primary mb-0"><i class="fas fa-project-diagram me-2"></i>Finanzas <span class="text-dark">Presupuesto</span></h3>
            <p class="text-muted small m-0"> | Proyección de Capital</p>
        </div>
        <div class="col-md-6 text-end">
            <div class="btn-group bg-light p-1 rounded-3 shadow-sm border nav-tabs-custom">
                <button class="nav-link px-3 py-1" onclick="setView(1, this)">Diario</button>
                <button class="nav-link px-3 py-1" onclick="setView(7, this)">Semanal</button>
                <button class="nav-link px-3 py-1 active" onclick="setView(30, this)">Mensual</button>
                <button class="nav-link px-3 py-1" onclick="setView(365, this)">Anual</button>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="glass-card p-4">
                <small class="bucket-label">Cash Flow Neto</small>
                <div class="kpi-value" id="kpi_neto">$0.00</div>
                <div id="status_neto" class="small fw-bold"></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="glass-card p-4 border-start border-danger border-4">
                <small class="bucket-label text-danger">Operación (Burn Rate)</small>
                <div class="kpi-value text-danger" id="kpi_burn">$0.00</div>
                <small class="text-muted small">Costo fijo de existencia</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="glass-card p-4 border-start border-info border-4">
                <small class="bucket-label text-info">Financial Runway</small>
                <div class="kpi-value text-info" id="kpi_runway">0.0</div>
                <small class="text-muted small">Meses de autonomía total</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="glass-card p-4 bg-dark text-white">
                <small class="text-info fw-bold d-block mb-1">CAPITAL EFFICIENCY</small>
                <div class="kpi-value text-white" id="kpi_score">--</div>
                <div class="progress mt-2" style="height: 4px; background: rgba(255,255,255,0.1);">
                    <div id="score_bar" class="progress-bar bg-info" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-lg-4">
            <div class="glass-card p-4 mb-4">
                <h6 class="fw-bold mb-3"><i class="fas fa-plus-circle me-2 text-primary"></i>Nueva Transacción</h6>
                <form id="formF">
                    <div class="mb-3">
                        <label class="small fw-bold">Descripción</label>
                        <input type="text" id="in_desc" class="form-control form-control-sm" placeholder="Renta, AWS, Nómina..." required>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="small fw-bold">Monto ($)</label>
                            <input type="number" step="0.01" id="in_monto" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-6">
                            <label class="small fw-bold">Tipo</label>
                            <select id="in_tipo" class="form-select form-select-sm">
                                <option value="Ingreso">Ingreso (+)</option>
                                <option value="Fijo">Gasto Fijo (-)</option>
                                <option value="Variable">Gasto Variable (-)</option>
                                <option value="Inversion">Inversión (★)</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">Periodicidad</label>
                        <select id="in_periodo" class="form-select form-select-sm">
                            <option value="Mensual">Mensual</option>
                            <option value="Semanal">Semanal</option>
                            <option value="Diario">Diario</option>
                            <option value="Anual">Anual</option>
                            <option value="Unico">Único</option>
                        </select>
                    </div>
                    <button type="button" class="btn btn-primary w-100 fw-bold py-2 shadow-sm" onclick="save()">GUARDAR EN MODELO</button>
                </form>
            </div>

            <div class="glass-card p-4">
                <h6 class="fw-bold mb-3 text-primary"><i class="fas fa-crosshairs me-2"></i>Presupuesto de Control (Target)</h6>
                <div class="d-flex flex-column gap-3" id="budget_buckets">
                    </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="glass-card p-4 mb-4">
                <h6 class="fw-bold mb-4 text-center text-muted text-uppercase">Proyección de Patrimonio a 12 Meses</h6>
                <div style="height: 300px;"><canvas id="chartProjection"></canvas></div>
                <p class="x-small text-center text-muted mt-2">Simulación basada en el ahorro neto e inversiones actuales con interés compuesto estimado (10% anual).</p>
            </div>

            <div class="row g-3">
                <div class="col-md-6">
                    <div class="glass-card p-4 h-100">
                        <h6 class="fw-bold mb-3">Estructura Actual</h6>
                        <div style="height: 200px;"><canvas id="chartStructure"></canvas></div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="glass-card p-4 h-100">
                        <h6 class="fw-bold mb-3">Asesoría de Optimización</h6>
                        <div id="advisor_box" class="advisor-box"></div>
                    </div>
                </div>
            </div>

            <div class="glass-card mt-4 overflow-hidden">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light">
                            <tr class="x-small text-muted text-uppercase">
                                <th class="ps-4">Transacción</th>
                                <th>Tipo</th>
                                <th class="text-end">Monto Ajustado</th>
                                <th class="text-center">Acción</th>
                            </tr>
                        </thead>
                        <tbody id="wealthTable"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// --- MOTOR DE INTELIGENCIA ---
const DB = "<?php echo $DB_TARGET; ?>";
const TABLE = "<?php echo $SQL_PATH; ?>";
const IDU = "<?php echo $IDUg_SISTEMA; ?>";

let factor = 30;
let charts = { structure: null, projection: null };

document.addEventListener('DOMContentLoaded', () => { refresh(); });

function setView(val, btn) {
    factor = val;
    document.querySelectorAll('.nav-link').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    refresh();
}

window.refresh = function() {
    const sql = `SELECT * FROM ${TABLE} WHERE IDU=${IDU} ORDER BY IDM DESC`;
    fetch('../librerias/AJAX/Select.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `sql=${encodeURIComponent(sql)}&db=${DB}`
    })
    .then(r => r.json())
    .then(res => {
        const data = res.data || (Array.isArray(res) ? res : []);
        render(data);
    });
};

function render(data) {
    const tbody = document.getElementById('wealthTable');
    const f = factor / 30;
    tbody.innerHTML = '';
    
    let s = { Ingreso: 0, Fijo: 0, Variable: 0, Inversion: 0 };

    data.forEach(row => {
        s[row.Tipo] += parseFloat(row.Monto);
        const isExp = row.Tipo !== 'Ingreso';
        tbody.innerHTML += `
            <tr>
                <td class="ps-4"><b>${row.Descripcion}</b><br><small class="text-muted">${row.Periodicidad}</small></td>
                <td><span class="badge ${row.Tipo === 'Ingreso' ? 'bg-success' : 'bg-light text-dark'}">${row.Tipo}</span></td>
                <td class="text-end fw-bold ${isExp ? 'text-danger' : 'text-primary'}">
                    $${(row.Monto * f).toLocaleString(undefined, {minimumFractionDigits: 2})}
                </td>
                <td class="text-center">
                    <button class="btn btn-sm text-danger" onclick="remove(${row.IDM})"><i class="fas fa-trash"></i></button>
                </td>
            </tr>
        `;
    });

    const neto = s.Ingreso - (s.Fijo + s.Variable + s.Inversion);
    const surplus = s.Ingreso - (s.Fijo + s.Variable);
    const runway = s.Fijo > 0 ? (Math.max(0, surplus * 12) / s.Fijo).toFixed(1) : '∞';
    const savingsRate = s.Ingreso > 0 ? ((s.Inversion + Math.max(0, neto)) / s.Ingreso) * 100 : 0;

    // Update KPIs
    document.getElementById('kpi_neto').innerText = `$${(neto * f).toLocaleString()}`;
    document.getElementById('kpi_burn').innerText = `$${(s.Fijo * f).toLocaleString()}`;
    document.getElementById('kpi_runway').innerText = runway;
    document.getElementById('kpi_score').innerText = Math.round(savingsRate + 20) + '/100';
    document.getElementById('score_bar').style.width = Math.round(savingsRate + 20) + '%';
    
    document.getElementById('status_neto').className = neto >= 0 ? 'small text-success' : 'small text-danger';
    document.getElementById('status_neto').innerText = neto >= 0 ? 'Flujo Positivo' : 'Déficit de Caja';

    updateBuckets(s, f);
    updateCharts(s);
    updateAdvisor(s, runway);
}

function updateBuckets(s, f) {
    const box = document.getElementById('budget_buckets');
    const goals = [
        { t: 'Fijos (Necesidad)', p: 0.5, a: s.Fijo, c: 'danger' },
        { t: 'Variables (Deseos)', p: 0.3, a: s.Variable, c: 'warning' },
        { t: 'Inversión (Futuro)', p: 0.2, a: s.Inversion, c: 'success' }
    ];
    
    box.innerHTML = '';
    goals.forEach(g => {
        const ideal = s.Ingreso * g.p;
        const diff = ideal - g.a;
        box.innerHTML += `
            <div class="bucket-card border-start border-${g.c} border-5">
                <div class="d-flex justify-content-between"><span class="bucket-label">${g.t}</span><span class="small fw-bold">${g.p*100}%</span></div>
                <div class="d-flex justify-content-between align-items-end">
                    <div class="bucket-amount ${diff < 0 ? 'text-danger' : 'text-success'}">$${(diff * f).toLocaleString()}</div>
                    <small class="text-muted">Meta: $${(ideal * f).toLocaleString()}</small>
                </div>
            </div>
        `;
    });
}

function updateCharts(s) {
    // 1. Estructura Actual
    const ctx1 = document.getElementById('chartStructure').getContext('2d');
    if(charts.structure) charts.structure.destroy();
    charts.structure = new Chart(ctx1, {
        type: 'doughnut',
        data: {
            labels: ['Fijos', 'Variables', 'Inversión'],
            datasets: [{ data: [s.Fijo, s.Variable, s.Inversion], backgroundColor: ['#ef4444', '#f59e0b', '#3b82f6'], borderWidth: 0 }]
        },
        options: { maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
    });

    // 2. Proyección en el Tiempo (12 Meses)
    const ctx2 = document.getElementById('chartProjection').getContext('2d');
    if(charts.projection) charts.projection.destroy();
    
    let labels = [];
    let projectionData = [];
    let capital = 0;
    const monthlyNet = s.Ingreso - (s.Fijo + s.Variable); // Lo que queda para ahorrar/invertir
    const r = 0.10 / 12; // 10% anual / 12 meses

    for(let i=0; i<=12; i++) {
        labels.push("Mes " + i);
        projectionData.push(capital);
        capital = (capital + monthlyNet) * (1 + r);
    }

    charts.projection = new Chart(ctx2, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Crecimiento de Patrimonio ($)',
                data: projectionData,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: { maintainAspectRatio: false, scales: { y: { beginAtZero: true } } }
    });
}

function updateAdvisor(s, runway) {
    const box = document.getElementById('advisor_box');
    box.innerHTML = '';
    if(s.Fijo > s.Ingreso * 0.5) box.innerHTML += `<div class="advisor-item alert-high"><b>Vulnerabilidad Operativa:</b> Tus costos fijos superan el 50%. Renegocia gastos antes de que el flujo se detenga.</div>`;
    if(runway < 6) box.innerHTML += `<div class="advisor-item alert-high"><b>Pista Corta:</b> Tienes menos de 6 meses de vida ahorrada. Detén gastos variables de inmediato.</div>`;
    if(s.Inversion > 0) box.innerHTML += `<div class="advisor-item alert-success"><b>Motor de Riqueza:</b> Estás inyectando capital al futuro. Mantén este ritmo para acelerar tu jubilación.</div>`;
}

window.save = function() {
    const d = document.getElementById('in_desc').value;
    const m = document.getElementById('in_monto').value;
    const t = document.getElementById('in_tipo').value;
    const p = document.getElementById('in_periodo').value;
    const token = Math.random().toString(36).substr(2, 11).toUpperCase();
    
    if(!d || !m) return;

    const sql = `INSERT INTO ${TABLE} (IDU, Token, Descripcion, Monto, Tipo, Periodicidad, FechaMovimiento) 
                 VALUES (${IDU}, '${token}', '${d}', ${m}, '${t}', '${p}', NOW())`;

    fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB}` })
    .then(() => { document.getElementById('formF').reset(); refresh(); });
};

window.remove = function(id) {
    const sql = `DELETE FROM ${TABLE} WHERE IDM=${id}`;
    fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB}` }).then(() => refresh());
};
</script>