<?php
ob_start(); // Iniciar el búfer de salida al inicio del script
session_start();

// ***** IMPORTANTE: ESTAS LÍNEAS ESTÁN AQUÍ PARA DEPURAR. *****
// UNA VEZ QUE FUNCIONE, CÁMBIALAS A: error_reporting(0); ini_set('display_errors', 0);
error_reporting(E_ALL); // Reporta todos los errores
ini_set('display_errors', 1); // Muestra los errores en la pantalla
// *************************************************************

// --- DATOS DE ADMINISTRADOR DE EJEMPLO ---
$admin_data = [
    'nombre' => 'María Admin',
    'email' => 'maria.admin@orozdesign.com',
    'foto_perfil' => 'https://placehold.co/100x100/4c7c59/ffffff?text=MA' // Ejemplo de imagen
];

// --- DATOS DUMMY DE PRÉSTAMOS ---
$loans_data_dummy = [
    1 => [
        'id' => 1,
        'name' => 'Préstamo Coche',
        'total_amount_original' => 15000.00,
        'monthly_payment' => 250.00,
        'total_installments' => 60,
        'start_date' => '2023-01-01',
    ],
    2 => [ // Préstamo diseñado para tener 10 cuotas pendientes
        'id' => 2,
        'name' => 'Préstamo Personal (10 pendientes)',
        'total_amount_original' => 1000.00,
        'monthly_payment' => 100.00,
        'total_installments' => 10, // Total 10 cuotas
        'start_date' => date('Y-m-d', strtotime('-9 months')), // Empezó hace 9 meses, 10 cuotas = la primera cuota venció hace 8 meses
    ],
    3 => [
        'id' => 3,
        'name' => 'Préstamo Estudios',
        'total_amount_original' => 8000.00,
        'monthly_payment' => 100.00,
        'total_installments' => 80,
        'start_date' => '2024-03-01',
    ],
];

// --- Generar Cuotas DUMMY a partir de préstamos ---
$installments_data_dummy = [];
$installment_counter = 1;
foreach ($loans_data_dummy as $loan) {
    $current_date_for_installments = new DateTime($loan['start_date']);
    // Ajustar para que la primera cuota venza al mes siguiente del start_date
    $current_date_for_installments->modify('+1 month'); 

    for ($i = 1; $i <= $loan['total_installments']; $i++) {
        $due_date = clone $current_date_for_installments;
        // Ajustar la fecha de vencimiento de cada cuota si el ciclo no es el primer mes
        if ($i > 1) {
             $due_date->modify("+" . ($i - 1) . " months");
        }
        
        $is_paid = false;
        // Simular que cuotas anteriores al mes actual están pagadas
        if ($due_date < new DateTime(date('Y-m-01'))) { 
            $is_paid = true;
        }

        // Si es el préstamo "Préstamo Personal (10 pendientes)", aseguramos que las últimas 10 estén pendientes
        if ($loan['id'] == 2) {
            // Este préstamo tiene 10 cuotas en total, y lo configuramos para que estén todas pendientes
            // simplemente por el 'start_date' y 'total_installments'
            // Opcional: Forzar que las 10 cuotas estén pendientes sin importar la fecha
            // if ($i <= $loan['total_installments']) { // Todas las cuotas de este préstamo están pendientes
            //     $is_paid = false;
            // }
        }
        
        $installments_data_dummy["installment-{$installment_counter}"] = [
            'id' => $installment_counter,
            'loan_id' => $loan['id'],
            'loan_name' => $loan['name'],
            'due_date' => $due_date->format('Y-m-d'),
            'amount' => $loan['monthly_payment'],
            'is_paid' => $is_paid,
        ];
        $installment_counter++;
    }
}

// --- Calcular Métricas para Tarjetas ---
$total_debt_remaining = 0;
$total_monthly_payment_due = 0;
$total_remaining_installments = 0;
$current_month_start = new DateTime(date('Y-m-01'));
$current_month_end = new DateTime(date('Y-m-t')); // Último día del mes actual

foreach ($installments_data_dummy as $installment) {
    if (!$installment['is_paid']) {
        $total_debt_remaining += $installment['amount'];
        $total_remaining_installments++;

        $installment_due_date = new DateTime($installment['due_date']);
        // Si la cuota está pendiente y vence en el mes actual
        if ($installment_due_date >= $current_month_start && $installment_due_date <= $current_month_end) {
            $total_monthly_payment_due += $installment['amount'];
        }
    }
}


// Conversión a JSON para JavaScript
$loans_json = json_encode(array_values($loans_data_dummy));
$installments_json = json_encode(array_values($installments_data_dummy));

$loan_metrics_json = json_encode([
    'total_debt_remaining' => $total_debt_remaining,
    'total_monthly_payment_due' => $total_monthly_payment_due,
    'total_remaining_installments' => $total_remaining_installments,
]);


// Conversión a JSON para JavaScript
$loans_json = json_encode(array_values($loans_data_dummy));
$installments_json = json_encode(array_values($installments_data_dummy));

$loan_metrics_json = json_encode([
    'total_debt_remaining' => $total_debt_remaining,
    'total_monthly_payment_due' => $total_monthly_payment_due,
    'total_remaining_installments' => $total_remaining_installments,
]);


// Manejo de notificaciones de sesión
$notification_message = '';
$notification_type = '';
if (isset($_SESSION['notification'])) {
    $notification_message = $_SESSION['notification']['message'];
    $notification_type = $_SESSION['notification']['type'];
    unset($_SESSION['notification']);
}
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Dashboard | Finanzas Personales</title>
    <meta name="description" content="Gestiona tus préstamos personales, registra pagos y monitorea tu deuda en LocalCRM.">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="../img/favicon.png">
    <link rel="apple-touch-icon" href="../img/apple-touch-icon.png">

    <?php // include '../files/gtm-head.php'; // Ajustar ruta si es necesario ?> 

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <link rel="stylesheet" href="../style.css"> <script src="../files/header-manager.js"></script> </head>
<body data-page-title="PANEL DE ADMINISTRADOR - FINANZAS PERSONALES"
      data-page-subtitle="GESTIÓN DE PRÉSTAMOS Y GASTOS"
      data-page-icon="wallet">

<?php // include '../files/gtm-body.php'; // Ajustar ruta si es necesario ?> 

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>

    <aside id="sidebar" class="fixed inset-y-0 left-0 w-64 bg-primary text-white p-6
                                         transform -translate-x-full transition-transform duration-300 ease-in-out z-50
                                         lg:relative lg:translate-x-0 lg:flex lg:flex-col lg:w-72">
        <button id="sidebarCloseBtn" class="absolute top-4 right-4 text-white text-2xl lg:hidden">
            <i class="fas fa-times"></i>
        </button>

        <div class="flex items-center justify-center mb-6">
            <img src="../img/LogoPlataformaBlanco.png" alt="ASI SE COBRA OROZDESIGN" class="h-16">
        </div>
        <div class="flex items-center gap-4 border-b border-gray-700 pb-6">
            <img src="<?php echo htmlspecialchars($admin_data['foto_perfil']); ?>" alt="Foto de Perfil" class="w-16 h-16 rounded-full object-cover" onerror="this.onerror=null; this.src='https://placehold.co/100x100/ffffff/1f2937?text=AD';">
            <div>
                <h2 class="font-bold text-lg"><?php echo htmlspecialchars($admin_data['nombre']); ?></h2>
                <p class="text-sm text-gray-400">Administrador</p>
            </div>
        </div>

        <nav class="mt-8 space-y-2">
            <a href="dashboard.php" data-section="dashboard" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="layout-dashboard" class="w-5 h-5 mr-3"></i> DASHBOARD
            </a>
            <a href="clientes.php" data-section="clientes" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="users" class="w-5 h-5 mr-3"></i> CLIENTES
            </a>
            <a href="servicios.php" data-section="servicios" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="briefcase" class="w-5 h-5 mr-3"></i> SERVICIOS
            </a>
            <a href="leads.php" data-section="leads" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="funnel-dollar" class="w-5 h-5 mr-3"></i> LEADS
            </a>
            <a href="agenda.php" data-section="calendario" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="calendar" class="w-5 h-5 mr-3"></i> CALENDARIO
            </a>
            <a href="finances.php" data-section="finanzas" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="trending-up" class="w-5 h-5 mr-3"></i> FINANZAS (Negocio)
            </a>
            <a href="invoices.php" data-section="facturas" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="receipt" class="w-5 h-5 mr-3"></i> FACTURAS
            </a>
            <a href="quotes.php" data-section="cotizaciones" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="file-text" class="w-5 h-5 mr-3"></i> COTIZACIONES
            </a>
            <a href="performance.php" data-section="rendimiento" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="bar-chart-2" class="w-5 h-5 mr-3"></i> RENDIMIENTO
            </a>
            <a href="website.php" data-section="pagina-web" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="globe" class="w-5 h-5 mr-3"></i> PAGINA WEB
            </a>
            <a href="ia-marketing.php" data-section="herramientas-ia" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="cpu" class="w-5 h-5 mr-3"></i> IA MARKETING
            </a>
            <a href="academy.php" data-section="academia" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="graduation-cap" class="w-5 h-5 mr-3"></i> ACADEMIA PUBLICITARIA
            </a>
            <a href="promote.php" data-section="promociona" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="rocket" class="w-5 h-5 mr-3"></i> PROMOCIONATE
            </a>
            <a href="comunicaciones.php" data-section="comunicaciones" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="message-square" class="w-5 h-5 mr-3"></i> COMUNICACIONES
            </a>
            <a href="videos.php" data-section="videos" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="film" class="w-5 h-5 mr-3"></i> VIDEOS
            </a>
            <a href="personal-finances.php" data-section="finanzas-personales" class="nav-link sidebar-link active w-full text-left">
                <i data-lucide="wallet" class="w-5 h-5 mr-3"></i> FINANZAS PERSONALES
            </a>
            <a href="account.php" data-section="cuenta" class="nav-link sidebar-link w-full text-left">
                <i data-lucide="user-cog" class="w-5 h-5 mr-3"></i> TU CUENTA
            </a>
        </nav>

        <div class="mt-auto pt-8">
            <div class="flex flex-col gap-2">
                <button id="addLoanBtnSidebar" class="btn-cta w-full text-white font-bold py-3 px-4 rounded-lg inline-flex items-center justify-center">
                    <i class="fas fa-plus mr-2"></i>AÑADIR PRÉSTAMO
                </button>
                <a href="?logout=true" class="btn-logout w-full text-white font-bold py-3 px-4 rounded-lg inline-flex items-center justify-center" title="Cerrar Sesión">
                    <i class="fas fa-sign-out-alt mr-2"></i>SALIR
                </a>
            </div>
        </div>
    </aside>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container" id="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            <section id="loan-overview-section" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="wallet" class="w-7 h-7 text-[var(--color-primary)]"></i> RESUMEN DE PRÉSTAMOS PERSONALES
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">VISIÓN GENERAL DE DEUDAS Y PAGOS.</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-red-500">
                            <i data-lucide="banknote" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">DEUDA TOTAL RESTANTE</h3>
                                <p id="total-debt-remaining" class="text-5xl font-bold text-red-700">$0.00</p>
                            </div>
                        </div>
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-blue-500">
                            <i data-lucide="credit-card" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">PAGO TOTAL DEL MES</h3>
                                <p id="total-monthly-payment-due" class="text-5xl font-bold text-blue-700">$0.00</p>
                            </div>
                        </div>
                        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-green-500">
                            <i data-lucide="trending-down" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">PAGOS RESTANTES</h3>
                                <p id="total-remaining-installments" class="text-5xl font-bold text-green-700">0</p>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section id="installments-list-section" class="dashboard-section mt-8">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="list-checks" class="w-7 h-7 text-[var(--color-primary)]"></i> CUOTAS DE PRÉSTAMOS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">MARCA LAS CUOTAS PAGADAS Y GESTIONA TUS COMPROMISOS.</p>
                        </div>
                        <div class="flex items-center gap-4 w-full md:w-auto">
                            <button id="addLoanBtnTop" class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> AÑADIR PRÉSTAMO
                            </button>
                            <select id="installments-filter-loan" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                                <option value="all">TODOS LOS PRÉSTAMOS</option>
                                </select>
                            <select id="installments-filter-status" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                                <option value="all">TODOS LOS ESTADOS</option>
                                <option value="pending">PENDIENTES</option>
                                <option value="paid">PAGADAS</option>
                            </select>
                            <button id="downloadInstallmentsBtn" class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase text-sm">
                                <i data-lucide="download" class="w-4 h-4 mr-2"></i> DESCARGAR
                            </button>
                        </div>
                    </div>

                    <div id="installments-list-view" class="overflow-x-auto">
                        <table class="min-w-full bg-white">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-semibold">PRÉSTAMO</th>
                                    <th class="py-3 px-6 font-semibold">CUOTA #</th>
                                    <th class="py-3 px-6 font-semibold">FECHA VENCIMIENTO</th>
                                    <th class="py-3 px-6 font-semibold">MONTO</th>
                                    <th class="py-3 px-6 font-semibold text-center">ESTADO</th>
                                    <th class="py-3 px-6 font-semibold text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="installmentsTableBody">
                                <?php if (empty($installments_data_dummy)): ?>
                                    <tr>
                                        <td colspan="6" class="py-3 px-6 text-center">No hay cuotas registradas.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addLoanPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">AÑADIR NUEVO PRÉSTAMO</h3>
            <button onclick="closePanel('addLoanPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="add-loan-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                <div>
                    <label for="loan-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL PRÉSTAMO</label>
                    <input type="text" id="loan-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Préstamo Hipotecario" required>
                </div>
                <div>
                    <label for="loan-total-amount" class="block text-gray-700 text-sm font-bold mb-2 uppercase">MONTO TOTAL ORIGINAL</label>
                    <input type="number" step="0.01" id="loan-total-amount" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 15000.00" required>
                </div>
                <div>
                    <label for="loan-monthly-payment" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PAGO MENSUAL</label>
                    <input type="number" step="0.01" id="loan-monthly-payment" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 250.00" required>
                </div>
                <div>
                    <label for="loan-total-installments" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NÚMERO DE CUOTAS TOTAL</label>
                    <input type="number" step="1" id="loan-total-installments" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 60" required>
                </div>
                <div class="md:col-span-2">
                    <label for="loan-start-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FECHA DE INICIO</label>
                    <input type="date" id="loan-start-date" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
            </div>
            <div class="h-4"></div></form>
        <div class="flex justify-end space-x-4 pt-6 flex-shrink-0">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('addLoanPanel')">CANCELAR</button>
            <button type="submit" form="add-loan-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR PRÉSTAMO</button>
        </div>
    </div>
</div>

<div id="viewLoanPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">DETALLE DEL PRÉSTAMO</h3>
            <button onclick="closePanel('viewLoanPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="view-loan-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="view-loan-id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                <div>
                    <label for="view-loan-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL PRÉSTAMO</label>
                    <input type="text" id="view-loan-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
                <div>
                    <label for="view-loan-total-amount" class="block text-gray-700 text-sm font-bold mb-2 uppercase">MONTO TOTAL ORIGINAL</label>
                    <input type="number" step="0.01" id="view-loan-total-amount" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
                 <div>
                    <label for="view-loan-monthly-payment" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PAGO MENSUAL</label>
                    <input type="number" step="0.01" id="view-loan-monthly-payment" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
                <div>
                    <label for="view-loan-total-installments" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NÚMERO DE CUOTAS TOTAL</label>
                    <input type="number" step="1" id="view-loan-total-installments" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
                <div class="md:col-span-2">
                    <label for="view-loan-start-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FECHA DE INICIO</label>
                    <input type="date" id="view-loan-start-date" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                </div>
            </div>
            <div class="h-4"></div></form>
        <div class="flex justify-end space-x-4 pt-4 border-t border-gray-200 mt-6 flex-shrink-0">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('viewLoanPanel')">CANCELAR</button>
            <button type="submit" form="view-loan-form" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR CAMBIOS</button>
        </div>
    </div>
</div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i data-lucide="alert-triangle" class="w-16 h-16 text-red-500"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ACCIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS REALIZAR ESTA ACCIÓN?</p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmDeleteModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>


<script>
// Variables globales para los datos (dummy)
let loansActuales = <?php echo $loans_json; ?>;
let installmentsActuales = <?php echo $installments_json; ?>;
let loanMetrics = <?php echo $loan_metrics_json; ?>;

document.addEventListener('DOMContentLoaded', function() {
    // --- CONSOLE.LOGS PARA DEPURACIÓN ---
    console.log("--- Depuración de personal-finances.php ---");
    console.log("loansActuales (préstamos):", loansActuales);
    console.log("installmentsActuales (cuotas):", installmentsActuales);
    console.log("loanMetrics (métricas iniciales):", loanMetrics);
    // --- FIN CONSOLE.LOGS PARA DEPURACIÓN ---


    // --- VARIABLES DOM LOCALES ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    
    // Métricas de Préstamos
    const totalDebtRemainingElement = document.getElementById('total-debt-remaining');
    const totalMonthlyPaymentDueElement = document.getElementById('total-monthly-payment-due');
    const totalRemainingInstallmentsElement = document.getElementById('total-remaining-installments');

    // Añadir Préstamo
    const addLoanBtnSidebar = document.getElementById('addLoanBtnSidebar'); // Sidebar button
    const addLoanBtnTop = document.getElementById('addLoanBtnTop'); // Top button
    const addLoanForm = document.getElementById('add-loan-form');
    const addLoanPanel = document.getElementById('addLoanPanel'); // Panel para añadir préstamo
    
    // Ver/Editar Préstamo
    const viewLoanPanel = document.getElementById('viewLoanPanel');
    const viewLoanForm = document.getElementById('view-loan-form');
    const viewLoanIdInput = document.getElementById('view-loan-id');
    const viewLoanNameInput = document.getElementById('view-loan-name');
    const viewLoanTotalAmountInput = document.getElementById('view-loan-total-amount');
    const viewLoanMonthlyPaymentInput = document.getElementById('view-loan-monthly-payment');
    const viewLoanTotalInstallmentsInput = document.getElementById('view-loan-total-installments');
    const viewLoanStartDateInput = document.getElementById('view-loan-start-date');

    // Lista de Cuotas
    const installmentsTableBody = document.getElementById('installmentsTableBody');
    const installmentsFilterLoan = document.getElementById('installments-filter-loan');
    const installmentsFilterStatus = document.getElementById('installments-filter-status');
    const downloadInstallmentsBtn = document.getElementById('downloadInstallmentsBtn');

    // Modales de confirmación (compartidos)
    const confirmDeleteModal = document.getElementById('confirmDeleteModal');
    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    const confirmItemTypeSpan = document.getElementById('confirm-item-type');


    // Elemento de overlay para los paneles laterales (creado dinámicamente)
    const panelOverlay = document.createElement('div');
    panelOverlay.id = 'panel-overlay';
    panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
    document.body.appendChild(panelOverlay);


    // --- FUNCIONES HELPER GLOBALES (reutilizadas) ---

    // Muestra una notificación personalizada (simulada)
    window.showCustomNotification = function(message, type = 'info', duration = 3000) {
        const toast = document.getElementById('toastNotification');
        const toastMessage = document.getElementById('toastMessage');
        const toastIcon = document.getElementById('toastIcon');
        const toastCloseBtn = document.getElementById('toastCloseBtn');
        let toastTimeout;

        if (!toast || !toastMessage || !toastIcon || !toastCloseBtn) {
            console.warn(`[NOTIFICACION - FALLBACK] Elementos de toast no encontrados. Mensaje: ${type.toUpperCase()}: ${message}`);
            return;
        }

        clearTimeout(toastTimeout);
        toast.className = 'toast-notification'; // Resetear clases
        toastIcon.className = 'fas'; // Resetear icono base

        toastMessage.textContent = message;
        toast.classList.add(type === 'success' ? 'success' : (type === 'error' ? 'error' : 'info'));
        
        if (type === 'success') {
            toastIcon.classList.add('fa-check-circle');
        } else if (type === 'error') {
            toastIcon.classList.add('fa-exclamation-circle');
        } else {
            toastIcon.classList.add('fa-info-circle');
        }

        toast.classList.add('show');
        toastTimeout = setTimeout(() => {
            toast.classList.remove('show');
        }, duration);

        toastCloseBtn.onclick = () => {
            clearTimeout(toastTimeout);
            toast.classList.remove('show');
        };

        console.log(`[NOTIFICACION - ${type.toUpperCase()}] ${message}`);
    };

    // Abre un panel lateral (MODIFICADO para incluir lógica de inicialización)
    window.openPanel = function(panelId) {
        const panel = document.getElementById(panelId);
        if (!panel) { console.error(`Error: Panel con ID "${panelId}" no encontrado.`); return; }
        panel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden'); // Muestra el overlay
        console.log(`[personal-finances.php] Panel ${panelId} abierto.`);
        
        // Lógica específica para paneles
        if (panelId === 'addLoanPanel') { // Panel de añadir préstamo
            addLoanForm.reset();
            document.getElementById('loan-start-date').valueAsDate = new Date(); // Fecha de inicio por defecto
        } else if (panelId === 'viewLoanPanel') { // Panel de ver/editar préstamo
            // La inicialización se hace en openViewLoanModal
        }
    };

    // Cierra un panel lateral (MODIFICADO para incluir todos los paneles)
    window.closePanel = function(panelId) {
        const panel = document.getElementById(panelId);
        if (!panel) { console.error(`Error: Panel con ID "${panelId}" no encontrado para cerrar.`); return; }
        panel.classList.add('translate-x-full');
        panelOverlay.classList.add('hidden'); // Oculta el overlay
        console.log(`[personal-finances.php] Panel ${panelId} cerrado.`);
    };

    // Abre un modal (solo para confirmDeleteModal)
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { console.error(`Error: Modal con ID "${modalId}" no encontrado.`); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modal.classList.remove('hidden');
        setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
        console.log(`[personal-finances.php] Modal ${modalId} abierto.`);
    };

    // Cierra un modal (solo para confirmDeleteModal)
    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { console.error(`Error: Modal con ID "${modalId}" no encontrado para cerrar.`); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => { modal.classList.add('hidden'); }, 300);
        console.log(`[personal-finances.php] Modal ${modalId} cerrado.`);
    };
    
    // Abre el modal de confirmación general
    window.openConfirmActionModal = function(actionCallback, message = '¿ESTÁS SEGURO DE QUE DESEAS REALIZAR ESTA ACCIÓN?') {
        if (!confirmDeleteButton) { showCustomNotification("Error: Botón de confirmación no encontrado.", 'error'); return; }
        document.getElementById('confirmDeleteModal').querySelector('h3').textContent = 'CONFIRMAR ACCIÓN';
        document.getElementById('confirmDeleteModal').querySelector('p').textContent = message;
        confirmDeleteButton.onclick = () => {
            actionCallback();
            closeModal('confirmDeleteModal');
        };
        openModal('confirmDeleteModal');
    };

    // Descarga datos como CSV (adaptada para cuotas de préstamos)
    function descargarComoCSV(dataArray, filename) {
        if (dataArray.length === 0) { showCustomNotification('No hay datos para descargar.', 'info'); return; }
        const escapeCSV = (value) => {
            if (value === null || value === undefined) { return ''; }
            value = String(value);
            if (value.search(/("|,|\n)/g) >= 0) { return `"${value.replace(/"/g, '""')}"`; }
            return value;
        };
        let headers = ['id', 'loan_id', 'loan_name', 'due_date', 'amount', 'is_paid']; // Headers para cuotas
        
        const csvRows = [headers.map(h => escapeCSV(h.replace(/_/g, ' ').toUpperCase())).join(',')];
        dataArray.forEach(item => {
            const values = headers.map(header => escapeCSV(item[header]));
            csvRows.push(values.join(','));
        });
        const csvContent = csvRows.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url); link.setAttribute('download', filename);
            link.style.visibility = 'hidden'; document.body.appendChild(link);
            link.click(); document.body.removeChild(link);
        }
    }


    // --- FUNCIONES ESPECÍFICAS DE FINANZAS PERSONALES ---

    function updateLoanMetricsDisplay() {
        if (totalDebtRemainingElement) totalDebtRemainingElement.textContent = `$${loanMetrics.total_debt_remaining.toFixed(2)}`;
        if (totalMonthlyPaymentDueElement) totalMonthlyPaymentDueElement.textContent = `$${loanMetrics.total_monthly_payment_due.toFixed(2)}`;
        if (totalRemainingInstallmentsElement) totalRemainingInstallmentsElement.textContent = loanMetrics.total_remaining_installments.toString();
    }

    // RENDERIZAR TABLA DE CUOTAS
    function renderInstallmentsTable() {
        if (!installmentsTableBody) return;
        installmentsTableBody.innerHTML = ''; // Limpiar tabla

        const selectedLoanId = installmentsFilterLoan.value;
        const selectedStatus = installmentsFilterStatus.value;

        const filteredInstallments = installmentsActuales.filter(installment => {
            const matchesLoan = selectedLoanId === 'all' || installment.loan_id.toString() === selectedLoanId;
            const matchesStatus = selectedStatus === 'all' || 
                                  (selectedStatus === 'paid' && installment.is_paid) ||
                                  (selectedStatus === 'pending' && !installment.is_paid);
            return matchesLoan && matchesStatus;
        });

        if (filteredInstallments.length === 0) {
            installmentsTableBody.innerHTML = `<tr><td colspan="6" class="py-3 px-6 text-center">No hay cuotas registradas con los filtros actuales.</td></tr>`;
            return;
        }

        filteredInstallments.forEach(installment => {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-200 hover:bg-gray-50';
            
            const statusText = installment.is_paid ? 'PAGADA' : 'PENDIENTE';
            const statusClass = installment.is_paid ? 'bg-green-200 text-green-800' : 'bg-red-200 text-red-800';
            const actionButton = installment.is_paid ?
                `<button class="text-gray-400 cursor-not-allowed" title="Cuota ya pagada"><i data-lucide="check-circle" class="w-5 h-5"></i></button>` :
                `<button class="text-green-600 hover:text-green-800 mark-as-paid-btn" data-installment-id="${installment.id}" title="Marcar como Pagada"><i data-lucide="dollar-sign" class="w-5 h-5"></i></button>`;
            
            row.innerHTML = `
                <td class="py-3 px-6 text-left whitespace-nowrap">${installment.loan_name}</td>
                <td class="py-3 px-6 text-left"># ${installment.id}</td>
                <td class="py-3 px-6 text-left">${new Date(installment.due_date).toLocaleDateString()}</td>
                <td class="py-3 px-6 text-left">$${installment.amount.toFixed(2)}</td>
                <td class="py-3 px-6 text-center">
                    <span class="px-3 py-1 rounded-full text-xs font-semibold ${statusClass}">${statusText}</span>
                </td>
                <td class="py-3 px-6 text-center">
                    <div class="flex item-center justify-center">
                        <button class="w-6 h-6 mr-2 transform hover:text-[var(--color-highlight)] hover:scale-110" title="Editar Préstamo" onclick="openViewLoanModal(${installment.loan_id})">
                            <i data-lucide="edit" class="w-5 h-5"></i>
                        </button>
                        ${actionButton}
                        <button class="w-6 h-6 ml-2 transform hover:text-red-500 hover:scale-110 delete-installment-btn" data-installment-id="${installment.id}" title="Eliminar Cuota">
                            <i data-lucide="trash-2" class="w-5 h-5"></i>
                        </button>
                    </div>
                </td>
            `;
            installmentsTableBody.appendChild(row);
        });
        lucide.createIcons({ container: installmentsTableBody }); // Renderizar iconos Lucide
        setupInstallmentListeners(); // Adjuntar listeners a los botones
    }

    function populateLoanFilterDropdown() {
        if (!installmentsFilterLoan) return;
        installmentsFilterLoan.innerHTML = '<option value="all">TODOS LOS PRÉSTAMOS</option>';
        loansActuales.forEach(loan => {
            const option = document.createElement('option');
            option.value = loan.id;
            option.textContent = loan.name.toUpperCase();
            installmentsFilterLoan.appendChild(option);
        });
    }

    function setupInstallmentListeners() {
        // Marcar como pagada
        document.querySelectorAll('.mark-as-paid-btn').forEach(button => {
            button.removeEventListener('click', handleMarkAsPaidClick);
            button.addEventListener('click', handleMarkAsPaidClick);
        });
        // Eliminar cuota
        document.querySelectorAll('.delete-installment-btn').forEach(button => {
            button.removeEventListener('click', handleDeleteInstallmentClick);
            button.addEventListener('click', handleDeleteInstallmentClick);
        });
    }

    function handleMarkAsPaidClick(e) {
        const installmentId = parseInt(e.currentTarget.dataset.installmentId);
        openConfirmActionModal(async () => {
            const installment = installmentsActuales.find(inst => inst.id === installmentId);
            if (installment) {
                // SIMULACIÓN: Marcar como pagada localmente
                installment.is_paid = true;
                // SIMULACIÓN: Actualizar métricas
                loanMetrics.total_debt_remaining -= installment.amount;
                loanMetrics.total_remaining_installments--;
                
                // Si la cuota era del mes actual y estaba pendiente
                const today = new Date();
                const installmentDueDate = new Date(installment.due_date);
                if (installmentDueDate.getMonth() === today.getMonth() && installmentDueDate.getFullYear() === today.getFullYear()) {
                     loanMetrics.total_monthly_payment_due -= installment.amount;
                }

                updateLoanMetricsDisplay();
                renderInstallmentsTable(); // Re-renderizar para reflejar el cambio
                showCustomNotification(`Cuota #${installmentId} marcada como pagada (simulado).`, 'success');

                // En un sistema real, harías un fetch a un endpoint:
                // await fetch('../db/installments-mark-paid.php', { ... });
            }
        }, `¿Estás seguro de que deseas marcar la cuota #${installmentId} como pagada?`);
    }

    function handleDeleteInstallmentClick(e) {
        const installmentId = parseInt(e.currentTarget.dataset.installmentId);
        openConfirmActionModal(async () => {
            // SIMULACIÓN: Eliminar cuota localmente
            const deletedInstallment = installmentsActuales.find(inst => inst.id === installmentId);
            installmentsActuales = installmentsActuales.filter(inst => inst.id !== installmentId);

            // SIMULACIÓN: Actualizar métricas si la cuota no estaba pagada
            if (deletedInstallment && !deletedInstallment.is_paid) {
                loanMetrics.total_debt_remaining -= deletedInstallment.amount;
                loanMetrics.total_remaining_installments--;
                const today = new Date();
                const installmentDueDate = new Date(deletedInstallment.due_date);
                if (installmentDueDate.getMonth() === today.getMonth() && installmentDueDate.getFullYear() === today.getFullYear()) {
                    loanMetrics.total_monthly_payment_due -= deletedInstallment.amount;
                }
            }
            updateLoanMetricsDisplay();
            renderInstallmentsTable();
            showCustomNotification(`Cuota #${installmentId} eliminada (simulado).`, 'success');

            // En un sistema real:
            // await fetch('../db/installments-delete.php', { ... });
        }, `¿Estás seguro de que deseas eliminar la cuota #${installmentId}? Esto NO afecta el total del préstamo original.`);
    }

    // Abre el panel para ver/editar un préstamo
    window.openViewLoanModal = function(loanId) {
        const loan = loansActuales.find(l => l.id === loanId);
        if (!loan) { console.error('Préstamo no encontrado:', loanId); return; }

        viewLoanIdInput.value = loan.id;
        viewLoanNameInput.value = loan.name;
        viewLoanTotalAmountInput.value = loan.total_amount_original;
        viewLoanMonthlyPaymentInput.value = loan.monthly_payment;
        viewLoanTotalInstallmentsInput.value = loan.total_installments;
        viewLoanStartDateInput.value = loan.start_date;
        
        openPanel('viewLoanPanel');
    };

    // --- INICIALIZACIÓN DE LA PÁGINA ---

    // Mostrar notificación PHP si existe
    const phpNotificationMessage = "<?php echo addslashes($notification_message); ?>";
    const phpNotificationType = "<?php echo addslashes($notification_type); ?>";
    if (phpNotificationMessage) {
        showCustomNotification(phpNotificationMessage, phpNotificationType);
    }

    // Eventos de la barra lateral (menú móvil)
    const mobileMenuButtonHeader = document.getElementById('mobile-menu-button');
    const sidebarCloseBtnHeader = document.getElementById('sidebarCloseBtn');
    if (mobileMenuButtonHeader) mobileMenuButtonHeader.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });
    if (sidebarOverlay) sidebarOverlay.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });
    if (sidebarCloseBtnHeader) sidebarCloseBtnHeader.addEventListener('click', () => { sidebar.classList.toggle('-translate-x-full'); sidebarOverlay.classList.toggle('hidden'); });

    // Evento de botón "Añadir Préstamo" (sidebar)
    if (addLoanBtnSidebar) addLoanBtnSidebar.addEventListener('click', () => openPanel('addLoanPanel')); // Abre el panel de añadir préstamo
    // Evento de botón "Añadir Préstamo" (arriba de la tabla)
    if (addLoanBtnTop) addLoanBtnTop.addEventListener('click', () => openPanel('addLoanPanel'));

    // Actualizar métricas
    updateLoanMetricsDisplay();

    // Poblar dropdown de préstamos y renderizar tabla
    populateLoanFilterDropdown();
    renderInstallmentsTable();

    // Listeners para filtros de cuotas
    if (installmentsFilterLoan) installmentsFilterLoan.addEventListener('change', renderInstallmentsTable);
    if (installmentsFilterStatus) installmentsFilterStatus.addEventListener('change', renderInstallmentsTable);

    // Listener para descarga de cuotas
    if (downloadInstallmentsBtn) {
        downloadInstallmentsBtn.addEventListener('click', () => {
            descargarComoCSV(installmentsActuales, 'reporte_cuotas_prestamos.csv');
        });
    }

    // Listener para el formulario de añadir préstamo
    if (addLoanForm) {
        addLoanForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const loanName = document.getElementById('loan-name').value;
            const totalAmount = parseFloat(document.getElementById('loan-total-amount').value);
            const monthlyPayment = parseFloat(document.getElementById('loan-monthly-payment').value);
            const totalInstallments = parseInt(document.getElementById('loan-total-installments').value);
            const startDate = document.getElementById('loan-start-date').value;

            // Simulación de creación de préstamo y cuotas
            const newLoanId = loansActuales.length > 0 ? Math.max(...loansActuales.map(l => l.id)) + 1 : 1;
            const newLoan = {
                id: newLoanId,
                name: loanName,
                total_amount_original: totalAmount,
                monthly_payment: monthlyPayment,
                total_installments: totalInstallments,
                start_date: startDate
            };
            loansActuales.push(newLoan); // Añadir a la lista de préstamos

            // Generar cuotas para el nuevo préstamo y añadirlas a installmentsActuales
            let lastInstallmentId = installmentsActuales.length > 0 ? Math.max(...installmentsActuales.map(i => i.id)) : 0;
            
            // Calculamos las cuotas a partir de la fecha de inicio del préstamo
            let installment_due_date_calc = new Date(newLoan.start_date);
            installment_due_date_calc.setDate(1); // Empezar siempre el día 1 del mes para cálculo
            
            for (let i = 1; i <= newLoan.total_installments; i++) {
                let due_date = new Date(installment_due_date_calc.setMonth(installment_due_date_calc.getMonth() + 1));
                
                const newInstallment = {
                    id: ++lastInstallmentId,
                    loan_id: newLoan.id,
                    loan_name: newLoan.name,
                    due_date: due_date.toISOString().split('T')[0], // Formato YYYY-MM-DD
                    amount: newLoan.monthly_payment,
                    is_paid: false
                };
                installmentsActuales.push(newInstallment);
            }
            
            // Recalcular y actualizar métricas
            // Para la demo, simplificamos la adición de la deuda y cuotas nuevas.
            // En un sistema real, la lógica de recalculo de deuda restante sería más compleja.
            loanMetrics.total_debt_remaining += newLoan.total_amount_original;
            loanMetrics.total_remaining_installments += newLoan.total_installments;
            
            // Para el pago mensual, sumamos si la primera cuota de este préstamo es de este mes o anterior.
            const today = new Date();
            const currentMonthStart = new Date(today.getFullYear(), today.getMonth(), 1);
            if (new Date(installmentsActuales[installmentsActuales.length - newLoan.total_installments].due_date) <= currentMonthStart) {
                 loanMetrics.total_monthly_payment_due += newLoan.monthly_payment;
            }

            updateLoanMetricsDisplay();
            populateLoanFilterDropdown(); // Actualizar dropdown de préstamos
            renderInstallmentsTable(); // Volver a renderizar la tabla

            closePanel('addLoanPanel'); // Cerrar el panel de añadir préstamo
            showCustomNotification('Préstamo añadido con éxito (simulado).', 'success');

            // En un caso real, enviarías los datos a un endpoint PHP
            // await fetch('../db/loans-create.php', { ... });
        });
    }

    // Listener para el formulario de editar préstamo (Panel viewLoanPanel)
    if (viewLoanForm) {
        viewLoanForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const loanId = parseInt(viewLoanIdInput.value);
            const loanName = viewLoanNameInput.value;
            const totalAmount = parseFloat(viewLoanTotalAmountInput.value);
            const monthlyPayment = parseFloat(viewLoanMonthlyPaymentInput.value);
            const totalInstallments = parseInt(viewLoanTotalInstallmentsInput.value);
            const startDate = viewLoanStartDateInput.value;

            // Encontrar y actualizar el préstamo en la lista dummy
            const loanToUpdate = loansActuales.find(loan => loan.id === loanId);
            if (loanToUpdate) {
                // Simulación de actualización
                loanToUpdate.name = loanName;
                loanToUpdate.total_amount_original = totalAmount;
                loanToUpdate.monthly_payment = monthlyPayment;
                loanToUpdate.total_installments = totalInstallments;
                loanToUpdate.start_date = startDate;

                // Para una demo, simplemente recargamos para actualizar las métricas de forma "consistente"
                // En un sistema real, la actualización de cuotas sería más compleja.
                location.reload();
                showCustomNotification('Préstamo actualizado con éxito (simulado).', 'success');
            } else {
                showCustomNotification('Error: Préstamo no encontrado para actualizar (simulado).', 'error');
            }
            closePanel('viewLoanPanel');
        });
    }

    // Listener para el botón "Añadir Dato" del sidebar (en esta página es un placeholder)
    const addDashboardEntryBtnElement = document.getElementById('addDashboardEntryBtn');
    if (addDashboardEntryBtnElement) {
        addDashboardEntryBtnElement.addEventListener('click', () => {
            showCustomNotification('Esta sección gestiona tus finanzas personales. Puedes añadir un préstamo o marcar cuotas aquí.', 'info');
        });
    }

    // Se re-renderizan los iconos de Lucide al cargar el DOM
    lucide.createIcons();
    console.log("[personal-finances.php] Página de finanzas personales inicializada.");
});
        </script>
</body>
</html>
});