<?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@example.com',
    'foto_perfil' => 'https://placehold.co/100x100/4c7c59/ffffff?text=MA' // Ejemplo de imagen
];

// --- Lógica PHP para obtener datos de Pagos Automatizados (AHORA SON DATOS DUMMY) ---
$automated_payments_data_from_db = [
    'auto-pay-1' => [
        'id' => 'auto-pay-1',
        'db_id' => 1,
        'client_name' => 'Juan Pérez',
        'product_name' => 'Professional CRM Version',
        'amount' => 99.99,
        'payment_date' => '2024-07-01 08:00:00',
        'status' => 'Completed',
        'next_due_date' => '2024-08-01'
    ],
    'auto-pay-2' => [
        'id' => 'auto-pay-2',
        'db_id' => 2,
        'client_name' => 'Ana García',
        'product_name' => 'Standard CRM Version',
        'amount' => 49.99,
        'payment_date' => '2024-07-05 10:00:00',
        'status' => 'Completed',
        'next_due_date' => '2024-08-05'
    ],
    'auto-pay-3' => [
        'id' => 'auto-pay-3',
        'db_id' => 3,
        'client_name' => 'Carlos López',
        'product_name' => 'Advanced CRM Version',
        'amount' => 199.99,
        'payment_date' => '2024-06-28 15:00:00',
        'status' => 'Pending', // Ejemplo de pago pendiente
        'next_due_date' => '2024-07-28'
    ]
];
$new_automated_payments_this_month = 2; // Datos de ejemplo para este mes

// --- Lógica PHP para obtener datos de Pagos Manuales (AHORA SON DATOS DUMMY) ---
$manual_payments_data_from_db = [
    'manual-pay-1' => [
        'id' => 'manual-pay-1',
        'db_id' => 1,
        'client_name' => 'Pedro Ramírez',
        'description' => 'Pago único por Consultoría Inicial',
        'amount' => 250.00,
        'payment_date' => '2024-07-08 11:00:00'
    ],
    'manual-pay-2' => [
        'id' => 'manual-pay-2',
        'db_id' => 2,
        'client_name' => 'Sofía Díaz',
        'description' => 'Pago por Ebook de Marketing',
        'amount' => 19.99,
        'payment_date' => '2024-07-15 09:30:00'
    ]
];
$new_manual_payments_this_month = 2; // Datos de ejemplo para este mes


// --- Métricas Financieras DUMMY ---
$total_income_month = 0;
foreach($automated_payments_data_from_db as $payment) {
    if ((new DateTime($payment['payment_date']))->format('Y-m') === date('Y-m') && $payment['status'] === 'Completed') {
        $total_income_month += $payment['amount'];
    }
}
foreach($manual_payments_data_from_db as $payment) {
    if ((new DateTime($payment['payment_date']))->format('Y-m') === date('Y-m')) {
        $total_income_month += $payment['amount'];
    }
}

$completed_payments_this_month = 0;
foreach($automated_payments_data_from_db as $payment) {
    if ((new DateTime($payment['payment_date']))->format('Y-m') === date('Y-m') && $payment['status'] === 'Completed') {
        $completed_payments_this_month++;
    }
}
foreach($manual_payments_data_from_db as $payment) {
    if ((new DateTime($payment['payment_date']))->format('Y-m') === date('Y-m')) {
        $completed_payments_this_month++;
    }
}


// $recurring_payments_active_count ya no es necesaria
// $recurring_payments_active_count = 0;
// foreach($automated_payments_data_from_db as $payment) {
//     if ($payment['status'] === 'Completed' || $payment['status'] === 'Pending') { // Consideramos 'Pending' como activo para recurrencia
//         $recurring_payments_active_count++;
//     }
// }

$total_manual_payments_count = count($manual_payments_data_from_db);


$automated_payments_json = json_encode($automated_payments_data_from_db);
$manual_payments_json = json_encode($manual_payments_data_from_db);

$total_income_month_json = json_encode($total_income_month);
$completed_payments_this_month_json = json_encode($completed_payments_this_month);
// $recurring_payments_active_count_json ya no es necesaria
// $recurring_payments_active_count_json = json_encode($recurring_payments_active_count);
$total_manual_payments_count_json = json_encode($total_manual_payments_count);


$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 | Administración de Finanzas</title>
    <meta name="description" content="Gestiona los ingresos de productos digitales en LocalCRM: monitorea pagos automáticos y registra transacciones manuales.">
    <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">

    <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"
      data-page-subtitle="GESTIÓN DE INGRESOS DE PRODUCTOS DIGITALES"
      data-page-icon="trending-up">

<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>

<?php include 'menu.php'; ?>

    <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="finances-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="bar-chart-2" class="w-7 h-7 text-[var(--color-primary)]"></i> RESUMEN FINANCIERO (PRODUCTOS DIGITALES)
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">VISIÓN GENERAL DE INGRESOS 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-green-500">
                            <i data-lucide="dollar-sign" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">INGRESOS TOTALES (MES)</h3>
                                <p id="total-income-month" class="text-5xl font-bold text-green-700">$0.00</p>
                                <p class="text-sm text-gray-400 mt-1">PRODUCTOS DIGITALES</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-[var(--color-primary)]">
                            <i data-lucide="check-circle" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">PAGOS COMPLETADOS (MES)</h3>
                                <p id="completed-payments-this-month" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                                <p class="text-sm text-gray-400 mt-1">AUTOMÁTICOS Y MANUALES</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="notebook-tabs" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">PAGOS MANUALES REGISTRADOS</h3>
                                <p id="total-manual-payments-count" class="text-5xl font-bold text-blue-700">0</p>
                                <p class="text-sm text-gray-400 mt-1">TRANSACCIONES INDIVIDUALES</p>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section id="automated-payments-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="credit-card" class="w-7 h-7 text-[var(--color-primary)]"></i> PAGOS AUTOMATIZADOS (SUSCRIPCIONES CRM)
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">REGISTRO DE COBROS AUTOMÁTICOS POR SUSCRIPCIONES A VERSIONES DE CRM.</p>
                        </div>
                        <div class="flex items-center gap-4 w-full md:w-auto">
                            <button class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase" onclick="openPanel('addAutomatedPaymentPanel')">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> REGISTRAR PAGO AUTOMÁTICO
                            </button>
                            <button id="download-automated-payments-btn" 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 class="flex flex-col md:flex-row gap-4 mb-6">
                        <div class="relative flex-grow">
                            <input type="text" id="automated-payment-search" placeholder="Buscar Por Cliente o Producto..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                            <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                        </div>
                        <select id="automated-payment-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="Completed">COMPLETADO</option>
                            <option value="Pending">PENDIENTE</option>
                            <option value="Failed">FALLIDO</option>
                        </select>
                    </div>

                    <div id="automated-payment-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">CLIENTE</th>
                                    <th class="py-3 px-6 font-semibold">PRODUCTO</th>
                                    <th class="py-3 px-6 font-semibold">MONTO</th>
                                    <th class="py-3 px-6 font-semibold">FECHA PAGO</th>
                                    <th class="py-3 px-6 font-semibold">ESTADO</th>
                                    <th class="py-3 px-6 font-semibold text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="automatedPaymentsTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
            
            <section id="manual-payments-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="notebook-tabs" class="w-7 h-7 text-[var(--color-primary)]"></i> PAGOS MANUALES
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">REGISTRO DE TRANSACCIONES MANUALES Y PUNTUALES.</p>
                        </div>
                        <div class="flex items-center gap-4 w-full md:w-auto">
                            <button class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase" onclick="openPanel('addManualPaymentPanel')">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> REGISTRAR PAGO MANUAL
                            </button>
                            <button id="download-manual-payments-btn" 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 class="flex flex-col md:flex-row gap-4 mb-6">
                        <div class="relative flex-grow">
                            <input type="text" id="manual-payment-search" placeholder="Buscar Por Cliente o Descripción..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                            <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                        </div>
                    </div>

                    <div id="manual-payment-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">CLIENTE</th>
                                    <th class="py-3 px-6 font-semibold">DESCRIPCIÓN</th>
                                    <th class="py-3 px-6 font-semibold">MONTO</th>
                                    <th class="py-3 px-6 font-semibold">FECHA PAGO</th>
                                    <th class="py-3 px-6 font-semibold text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="manualPaymentsTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addAutomatedPaymentPanel" 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)]">REGISTRAR PAGO AUTOMATIZADO</h3>
            <button onclick="closePanel('addAutomatedPaymentPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="add-automated-payment-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="grid grid-cols-1 gap-x-6 gap-y-4">
                <div>
                    <label for="automated-client-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL CLIENTE</label>
                    <input type="text" id="automated-client-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. Juan Pérez" required>
                </div>
                <div>
                    <label for="automated-product-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL PRODUCTO DIGITAL</label>
                    <input type="text" id="automated-product-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. Versión Profesional CRM" required>
                </div>
                <div>
                    <label for="automated-amount" class="block text-gray-700 text-sm font-bold mb-2 uppercase">MONTO DEL PAGO</label>
                    <input type="number" step="0.01" id="automated-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. 99.99" required>
                </div>
                <div>
                    <label for="automated-payment-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FECHA DE PAGO</label>
                    <input type="date" id="automated-payment-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>
                    <label for="automated-status" class="block text-sm font-medium text-gray-700">ESTADO DEL PAGO</label>
                    <select id="automated-status" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white" required>
                        <option value="Completed">Completado</option>
                        <option value="Pending">Pendiente</option>
                        <option value="Failed">Fallido</option>
                    </select>
                </div>
                <div>
                    <label for="automated-next-due-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PRÓXIMA FECHA DE VENCIMIENTO</label>
                    <input type="date" id="automated-next-due-date" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                    <p class="text-xs text-gray-500 mt-1">Para pagos recurrentes.</p>
                </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('addAutomatedPaymentPanel')">CANCELAR</button>
            <button type="submit" form="add-automated-payment-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR PAGO AUTOMATIZADO</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 ELIMINACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR ESTE <span id="confirm-item-type" class="font-semibold">ELEMENTO</span>? ESTA ACCIÓN NO SE PUEDE DESHACER.</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>

<div id="viewAutomatedPaymentPanel" 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 DE PAGO AUTOMATIZADO</h3>
            <button onclick="closePanel('viewAutomatedPaymentPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="view-automated-payment-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="view-automated-payment-id">
            <div class="grid grid-cols-1 gap-x-6 gap-y-4">
                <div>
                    <label for="view-automated-client-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL CLIENTE</label>
                    <input type="text" id="view-automated-client-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. Juan Pérez" required>
                </div>
                <div>
                    <label for="view-automated-product-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL PRODUCTO DIGITAL</label>
                    <input type="text" id="view-automated-product-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. Versión Profesional CRM" required>
                </div>
                <div>
                    <label for="view-automated-amount" class="block text-sm font-medium text-gray-700">MONTO DEL PAGO</label>
                    <input type="number" step="0.01" id="view-automated-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. 99.99" required>
                </div>
                <div>
                    <label for="view-automated-payment-date" class="block text-sm font-medium text-gray-700">FECHA DE PAGO</label>
                    <input type="date" id="view-automated-payment-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>
                    <label for="view-automated-status" class="block text-sm font-medium text-gray-700">ESTADO DEL PAGO</label>
                    <select id="view-automated-status" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white" required>
                        <option value="Completed">Completado</option>
                        <option value="Pending">Pendiente</option>
                        <option value="Failed">Fallido</option>
                    </select>
                </div>
                <div>
                    <label for="view-automated-next-due-date" class="block text-sm font-medium text-gray-700">PRÓXIMA FECHA DE VENCIMIENTO</label>
                    <input type="date" id="view-automated-next-due-date" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                    <p class="text-xs text-gray-500 mt-1">Para pagos recurrentes.</p>
                </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('viewAutomatedPaymentPanel')">CANCELAR</button>
            <button type="submit" form="view-automated-payment-form" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR CAMBIOS</button>
        </div>
    </div>
</div>

<div id="addManualPaymentPanel" 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)]">REGISTRAR PAGO MANUAL</h3>
            <button onclick="closePanel('addManualPaymentPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="add-manual-payment-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="grid grid-cols-1 gap-x-6 gap-y-4">
                <div>
                    <label for="manual-client-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL CLIENTE</label>
                    <input type="text" id="manual-client-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. Cliente de Pago Único" required>
                </div>
                <div>
                    <label for="manual-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DESCRIPCIÓN DEL PAGO</label>
                    <input type="text" id="manual-description" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Servicio de instalación, Ebook específico" required>
                </div>
                <div>
                    <label for="manual-amount" class="block text-gray-700 text-sm font-bold mb-2 uppercase">MONTO DEL PAGO</label>
                    <input type="number" step="0.01" id="manual-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. 250.00" required>
                </div>
                <div>
                    <label for="manual-payment-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FECHA DE PAGO</label>
                    <input type="date" id="manual-payment-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('addManualPaymentPanel')">CANCELAR</button>
            <button type="submit" form="add-manual-payment-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR PAGO MANUAL</button>
        </div>
    </div>
</div>

<div id="viewManualPaymentPanel" 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 DE PAGO MANUAL</h3>
            <button onclick="closePanel('viewManualPaymentPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="view-manual-payment-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="view-manual-payment-id">
            <div class="grid grid-cols-1 gap-x-6 gap-y-4">
                <div>
                    <label for="view-manual-client-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL CLIENTE</label>
                    <input type="text" id="view-manual-client-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. Cliente de Pago Único" required>
                </div>
                <div>
                    <label for="view-manual-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DESCRIPCIÓN DEL PAGO</label>
                    <input type="text" id="view-manual-description" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Servicio de instalación, Ebook específico" required>
                </div>
                <div>
                    <label for="view-manual-amount" class="block text-gray-700 text-sm font-bold mb-2 uppercase">MONTO DEL PAGO</label>
                    <input type="number" step="0.01" id="view-manual-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. 250.00" required>
                </div>
                <div>
                    <label for="view-manual-payment-date" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FECHA DE PAGO</label>
                    <input type="date" id="view-manual-payment-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('viewManualPaymentPanel')">CANCELAR</button>
            <button type="submit" form="view-manual-payment-form" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR CAMBIOS</button>
        </div>
    </div>
</div>

<script>
// Variables globales para los datos (dummy)
let automatedPaymentsActuales = <?php echo $automated_payments_json; ?>;
let manualPaymentsActuales = <?php echo $manual_payments_json; ?>;

// Métricas financieras globales (dummy)
let totalIncomeMonth = <?php echo $total_income_month_json; ?>;
let completedPaymentsThisMonth = <?php echo $completed_payments_this_month_json; ?>;
// let recurringPaymentsActiveCount = <?php // echo $recurring_payments_active_count_json; ?>; // Eliminado
let totalManualPaymentsCount = <?php echo $total_manual_payments_count_json; ?>;


document.addEventListener('DOMContentLoaded', function() {
    // --- CONSOLE.LOGS PARA DEPURACIÓN ---
    console.log("--- Depuración de finances.php ---");
    console.log("automatedPaymentsActuales (pagos automatizados):", automatedPaymentsActuales);
    console.log("manualPaymentsActuales (pagos manuales):", manualPaymentsActuales);
    console.log("Métricas Financieras:", { totalIncomeMonth, completedPaymentsThisMonth, totalManualPaymentsCount }); // recurringPaymentsActiveCount eliminado
    // --- 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');
    const sidebarCloseBtn = document.getElementById('sidebarCloseBtn'); // Asegurarse de que esté aquí

    // Métricas
    const totalIncomeMonthElement = document.getElementById('total-income-month');
    const completedPaymentsThisMonthElement = document.getElementById('completed-payments-this-month');
    // const recurringPaymentsActiveCountElement = document.getElementById('recurring-payments-active-count'); // Eliminado
    const totalManualPaymentsCountElement = document.getElementById('total-manual-payments-count');

    // Pagos Automatizados
    const automatedPaymentSearch = document.getElementById('automated-payment-search');
    const automatedPaymentFilterStatus = document.getElementById('automated-payment-filter-status');
    const automatedPaymentsTableBody = document.getElementById('automatedPaymentsTableBody');
    const downloadAutomatedPaymentsBtn = document.getElementById('download-automated-payments-btn');
    const addAutomatedPaymentPanel = document.getElementById('addAutomatedPaymentPanel');
    const addAutomatedPaymentForm = document.getElementById('add-automated-payment-form');
    const viewAutomatedPaymentPanel = document.getElementById('viewAutomatedPaymentPanel');
    const viewAutomatedPaymentForm = document.getElementById('view-automated-payment-form');
    
    // Pagos Manuales
    const manualPaymentSearch = document.getElementById('manual-payment-search');
    const manualPaymentsTableBody = document.getElementById('manualPaymentsTableBody');
    const downloadManualPaymentsBtn = document.getElementById('download-manual-payments-btn');
    const addManualPaymentPanel = document.getElementById('addManualPaymentPanel');
    const addManualPaymentForm = document.getElementById('add-manual-payment-form');
    const viewManualPaymentPanel = document.getElementById('viewManualPaymentPanel');
    const viewManualPaymentForm = document.getElementById('view-manual-payment-form');

    // Botón general "Añadir Pago" del sidebar
    const addFinanceEntryBtn = document.getElementById('addFinanceEntryBtn');

    // 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 ---

    // 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(`[finances.php] Panel ${panelId} abierto.`);
        
        // Lógica específica para paneles
        if (panelId === 'addAutomatedPaymentPanel') {
            addAutomatedPaymentForm.reset();
            // Establecer la fecha de pago por defecto al día actual
            document.getElementById('automated-payment-date').valueAsDate = new Date();
        } else if (panelId === 'addManualPaymentPanel') {
            addManualPaymentForm.reset();
            // Establecer la fecha de pago por defecto al día actual
            document.getElementById('manual-payment-date').valueAsDate = new Date();
        } 
    };

    // 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(`[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(`[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(`[finances.php] Modal ${modalId} cerrado.`);
    };
    
    // Abre el modal de confirmación de eliminación (sin cambios)
    window.openConfirmDeleteModal = function(itemId, itemType) {
        if (!confirmDeleteButton || !confirmItemTypeSpan) { console.error("Error: Elementos del modal de confirmación de eliminación no encontrados."); return; }
        confirmDeleteButton.dataset.itemId = itemId; confirmDeleteButton.dataset.itemType = itemType;
        confirmItemTypeSpan.textContent = itemType.toUpperCase();
        openModal('confirmDeleteModal');
    };

    // Descarga datos como CSV (adaptada para ambos tipos de pagos)
    function descargarComoCSV(dataObject, filename) {
        const data = Object.values(dataObject);
        if (data.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 = [];
        if (filename.includes('automatizados')) {
            headers = ['db_id', 'client_name', 'product_name', 'amount', 'payment_date', 'status', 'next_due_date'];
        } else if (filename.includes('manuales')) {
            headers = ['db_id', 'client_name', 'description', 'amount', 'payment_date'];
        } else { // Fallback genérico
            headers = Object.keys(data[0]);
        }
        
        const csvRows = [headers.map(h => escapeCSV(h.replace(/_/g, ' ').toUpperCase())).join(',')];
        data.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 PARA PAGOS AUTOMATIZADOS ---
    window.openViewAutomatedPaymentModal = function(paymentId) {
        const payment = automatedPaymentsActuales[paymentId];
        if (!payment) { console.error('Pago automatizado no encontrado:', paymentId); return; }
        
        document.getElementById('view-automated-payment-id').value = payment.db_id;
        document.getElementById('view-automated-client-name').value = payment.client_name;
        document.getElementById('view-automated-product-name').value = payment.product_name;
        document.getElementById('view-automated-amount').value = payment.amount;
        document.getElementById('view-automated-payment-date').value = payment.payment_date.split(' ')[0]; // Solo la fecha
        document.getElementById('view-automated-status').value = payment.status;
        document.getElementById('view-automated-next-due-date').value = payment.next_due_date || '';

        openPanel('viewAutomatedPaymentPanel');
    };

    function setupAutomatedPaymentDeleteListeners() {
        document.querySelectorAll('.delete-automated-payment-btn').forEach(button => {
            button.removeEventListener('click', handleDeleteAutomatedPaymentButtonClick);
            button.addEventListener('click', handleDeleteAutomatedPaymentButtonClick);
        });
    }
    function handleDeleteAutomatedPaymentButtonClick(e) {
        e.stopPropagation();
        const itemId = this.dataset.itemId; const itemType = this.dataset.itemType; // 'pago automatizado'
        openConfirmDeleteModal(itemId, itemType);
    }

    function setupAutomatedPaymentEditListeners() {
        document.querySelectorAll('.edit-automated-payment-btn').forEach(button => {
            button.removeEventListener('click', handleEditAutomatedPaymentButtonClick);
            button.addEventListener('click', handleEditAutomatedPaymentButtonClick);
        });
    }
    function handleEditAutomatedPaymentButtonClick(e) {
        e.stopPropagation();
        const paymentId = this.dataset.paymentId;
        openViewAutomatedPaymentModal(paymentId);
    }
    
    function renderAutomatedPaymentRow(payment) {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50';
        row.dataset.paymentId = payment.id;
        row.dataset.itemId = payment.id;

        const paymentStatusClass = getStatusClass(payment.status);

        row.innerHTML = `
            <td class="py-4 px-6 whitespace-nowrap">
                <span class="text-blue-600 hover:text-blue-800 cursor-pointer font-semibold uppercase" onclick="openViewAutomatedPaymentModal('${payment.id}')">${payment.client_name}</span>
            </td>
            <td class="py-4 px-6 uppercase">${payment.product_name}</td>
            <td class="py-4 px-6 uppercase">$${parseFloat(payment.amount).toFixed(2)}</td>
            <td class="py-4 px-6 uppercase">${new Date(payment.payment_date).toLocaleDateString()}</td>
            <td class="py-4 px-6 text-center">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold uppercase ${paymentStatusClass}">${payment.status}</span>
            </td>
            <td class="py-4 px-6 text-center">
                <button class="text-blue-600 hover:text-blue-800 mr-3 edit-automated-payment-btn" title="EDITAR PAGO AUTOMATIZADO" data-payment-id="${payment.id}"><i data-lucide="edit-2" class="w-5 h-5"></i></button>
                <button class="text-red-600 hover:text-red-800 delete-automated-payment-btn" data-item-type="pago automatizado" data-item-id="${payment.id}" title="ELIMINAR PAGO AUTOMATIZADO"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
            </td>
        `;
        return row;
    }

    function renderAutomatedPayments() {
        if (!automatedPaymentsTableBody || !automatedPaymentSearch || !automatedPaymentFilterStatus) {
               console.error("[finances.php] ERROR: Elementos DOM de Pagos Automatizados no encontrados. Verifique los IDs."); return;
        }
        const searchTerm = automatedPaymentSearch.value.toLowerCase();
        const selectedStatus = automatedPaymentFilterStatus.value;
        const allPaymentsArray = Object.values(automatedPaymentsActuales);

        const filteredPayments = allPaymentsArray.filter(p => {
            const matchesSearch = searchTerm === '' || 
                                    p.client_name.toLowerCase().includes(searchTerm) || 
                                    p.product_name.toLowerCase().includes(searchTerm);
            const matchesStatus = selectedStatus === 'all' || p.status === selectedStatus;
            return matchesSearch && matchesStatus;
        });

        automatedPaymentsTableBody.innerHTML = '';

        if (filteredPayments.length === 0) {
            automatedPaymentsTableBody.innerHTML = `<tr><td colspan="6" class="py-4 px-6 text-center text-gray-500 uppercase">NO SE ENCONTRARON PAGOS AUTOMATIZADOS.</td></tr>`;
        } else {
            filteredPayments.forEach(payment => automatedPaymentsTableBody.appendChild(renderAutomatedPaymentRow(payment)));
        }

        setupAutomatedPaymentDeleteListeners();
        setupAutomatedPaymentEditListeners();
        lucide.createIcons();
    }

    // --- FUNCIONES PARA PAGOS MANUALES ---
    window.openViewManualPaymentModal = function(paymentId) {
        const payment = manualPaymentsActuales[paymentId];
        if (!payment) { console.error('Pago manual no encontrado:', paymentId); return; }
        
        document.getElementById('view-manual-payment-id').value = payment.db_id;
        document.getElementById('view-manual-client-name').value = payment.client_name;
        document.getElementById('view-manual-description').value = payment.description;
        document.getElementById('view-manual-amount').value = payment.amount;
        document.getElementById('view-manual-payment-date').value = payment.payment_date.split(' ')[0]; // Solo la fecha

        openPanel('viewManualPaymentPanel');
    };

    function setupManualPaymentDeleteListeners() {
        document.querySelectorAll('.delete-manual-payment-btn').forEach(button => {
            button.removeEventListener('click', handleDeleteManualPaymentButtonClick);
            button.addEventListener('click', handleDeleteManualPaymentButtonClick);
        });
    }
    function handleDeleteManualPaymentButtonClick(e) {
        e.stopPropagation();
        const itemId = this.dataset.itemId; const itemType = this.dataset.itemType; // 'pago manual'
        openConfirmDeleteModal(itemId, itemType);
    }

    function setupManualPaymentEditListeners() {
        document.querySelectorAll('.edit-manual-payment-btn').forEach(button => {
            button.removeEventListener('click', handleEditManualPaymentButtonClick);
            button.addEventListener('click', handleEditManualPaymentButtonClick);
        });
    }
    function handleEditManualPaymentButtonClick(e) {
        e.stopPropagation();
        const paymentId = this.dataset.paymentId;
        openViewManualPaymentModal(paymentId);
    }
    
    function renderManualPaymentRow(payment) {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50';
        row.dataset.paymentId = payment.id;
        row.dataset.itemId = payment.id;

        row.innerHTML = `
            <td class="py-4 px-6 whitespace-nowrap">
                <span class="text-blue-600 hover:text-blue-800 cursor-pointer font-semibold uppercase" onclick="openViewManualPaymentModal('${payment.id}')">${payment.client_name}</span>
            </td>
            <td class="py-4 px-6 uppercase">${payment.description}</td>
            <td class="py-4 px-6 uppercase">$${parseFloat(payment.amount).toFixed(2)}</td>
            <td class="py-4 px-6 uppercase">${new Date(payment.payment_date).toLocaleDateString()}</td>
            <td class="py-4 px-6 text-center">
                <button class="text-blue-600 hover:text-blue-800 mr-3 edit-manual-payment-btn" title="EDITAR PAGO MANUAL" data-payment-id="${payment.id}"><i data-lucide="edit-2" class="w-5 h-5"></i></button>
                <button class="text-red-600 hover:text-red-800 delete-manual-payment-btn" data-item-type="pago manual" data-item-id="${payment.id}" title="ELIMINAR PAGO MANUAL"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
            </td>
        `;
        return row;
    }

    function renderManualPayments() {
        if (!manualPaymentsTableBody || !manualPaymentSearch) {
               console.error("[finances.php] ERROR: Elementos DOM de Pagos Manuales no encontrados. Verifique los IDs."); return;
        }
        const searchTerm = manualPaymentSearch.value.toLowerCase();
        const allPaymentsArray = Object.values(manualPaymentsActuales);

        const filteredPayments = allPaymentsArray.filter(p => {
            const matchesSearch = searchTerm === '' || 
                                    p.client_name.toLowerCase().includes(searchTerm) || 
                                    p.description.toLowerCase().includes(searchTerm);
            return matchesSearch;
        });

        manualPaymentsTableBody.innerHTML = '';

        if (filteredPayments.length === 0) {
            manualPaymentsTableBody.innerHTML = `<tr><td colspan="5" class="py-4 px-6 text-center text-gray-500 uppercase">NO SE ENCONTRARON PAGOS MANUALES.</td></tr>`;
        } else {
            filteredPayments.forEach(payment => manualPaymentsTableBody.appendChild(renderManualPaymentRow(payment)));
        }

        setupManualPaymentDeleteListeners();
        setupManualPaymentEditListeners();
        lucide.createIcons();
    }


    // Funciones de formato de teléfono (no usadas, pero mantenidas por consistencia si fueran necesarias)
    function formatPhoneNumber(value) {
        if (!value) return '';
        const cleaned = ('' + value).replace(/\D/g, '');    
        const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
        if (match) {
            return `(${match[1]}) ${match[2]}-${match[3]}`;
        }
        return cleaned;    
    }

    function applyInputPhoneFormat(inputElement) {
        if (!inputElement) return;
        inputElement.value = formatPhoneNumber(inputElement.value);
        inputElement.addEventListener('input', (e) => {
            let value = e.target.value.replace(/\D/g, '');    
            e.target.value = formatPhoneNumber(value);
        });
        inputElement.addEventListener('blur', (e) => {
            e.target.value = formatPhoneNumber(e.target.value);
        });
    }

    function applyPhoneFormatToInputs() {
        // No hay campos de teléfono en esta página.
    }

    // Determina la clase CSS para el estado del pago (ej. para pagos automatizados)
    function getStatusClass(status) {
        switch (status.toLowerCase()) {
            case 'completed': return 'bg-green-100 text-green-800';
            case 'pending': return 'bg-yellow-100 text-yellow-800';
            case 'failed': return 'bg-red-100 text-red-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    }

    // Función para recalcular y actualizar todas las métricas financieras en el DOM
    function updateAllFinancialMetrics() {
        let currentTotalIncomeMonth = 0;
        let currentCompletedPaymentsThisMonth = 0;
        // let currentRecurringPaymentsActiveCount = 0; // Eliminado

        const currentMonth = new Date().getMonth(); // 0-indexed
        const currentYear = new Date().getFullYear();

        // Recalcular para Pagos Automatizados
        Object.values(automatedPaymentsActuales).forEach(payment => {
            const paymentDate = new Date(payment.payment_date);
            if (paymentDate.getFullYear() === currentYear && paymentDate.getMonth() === currentMonth) {
                if (payment.status === 'Completed') {
                    currentTotalIncomeMonth += payment.amount;
                    currentCompletedPaymentsThisMonth++;
                }
            }
            // La métrica de pagos recurrentes activos ya no es necesaria
            // if (payment.status === 'Completed' || payment.status === 'Pending') {
            //     currentRecurringPaymentsActiveCount++;
            // }
        });

        // Recalcular para Pagos Manuales
        Object.values(manualPaymentsActuales).forEach(payment => {
            const paymentDate = new Date(payment.payment_date);
            if (paymentDate.getFullYear() === currentYear && paymentDate.getMonth() === currentMonth) {
                currentTotalIncomeMonth += payment.amount;
                currentCompletedPaymentsThisMonth++;
            }
        });

        // Actualizar variables globales
        totalIncomeMonth = currentTotalIncomeMonth;
        completedPaymentsThisMonth = currentCompletedPaymentsThisMonth;
        // recurringPaymentsActiveCount = currentRecurringPaymentsActiveCount; // Eliminado
        totalManualPaymentsCount = Object.keys(manualPaymentsActuales).length; // Actualiza el conteo total de pagos manuales

        // Actualizar el DOM
        if (totalIncomeMonthElement) totalIncomeMonthElement.textContent = `$${totalIncomeMonth.toFixed(2)}`;
        if (completedPaymentsThisMonthElement) completedPaymentsThisMonthElement.textContent = completedPaymentsThisMonth.toString();
        // if (recurringPaymentsActiveCountElement) recurringPaymentsActiveCountElement.textContent = recurringPaymentsActiveCount.toString(); // Eliminado
        if (totalManualPaymentsCountElement) totalManualPaymentsCountElement.textContent = totalManualPaymentsCount.toString();
    }


    // --- INICIALIZACIÓN DE LA PÁGINA ---
    // Esta es la primera y única función que se ejecuta al cargar el DOM.

    // 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)
    if (mobileMenuButton) mobileMenuButton.addEventListener('click', toggleSidebar);
    // Cierra los paneles y el overlay si se hace clic en el overlay de la barra lateral
    if (sidebarOverlay) sidebarOverlay.addEventListener('click', () => {
        toggleSidebar();
        closePanel('addAutomatedPaymentPanel'); 
        closePanel('viewAutomatedPaymentPanel');
        closePanel('addManualPaymentPanel');
        closePanel('viewManualPaymentPanel');
    });
    // Este listener en panelOverlay ahora es crucial para cerrar los paneles laterales
    panelOverlay.addEventListener('click', () => {    
        closePanel('addAutomatedPaymentPanel');
        closePanel('viewAutomatedPaymentPanel');
        closePanel('addManualPaymentPanel');
        closePanel('viewManualPaymentPanel');
    });
    if (sidebarCloseBtn) sidebarCloseBtn.addEventListener('click', toggleSidebar); // Botón de cierre explícito del sidebar

    // --- Actualizar Métricas Financieras ---
    updateAllFinancialMetrics(); // Llama a la nueva función para calcular y actualizar todas las métricas

    // --- Renderizar Pagos Automatizados y Manuales ---
    renderAutomatedPayments();
    renderManualPayments();
    console.log("[finances.php] Pagos renderizados.");

    // LISTENERS PARA PAGOS AUTOMATIZADOS
    if (automatedPaymentSearch) automatedPaymentSearch.addEventListener('input', renderAutomatedPayments);
    if (automatedPaymentFilterStatus) automatedPaymentFilterStatus.addEventListener('change', renderAutomatedPayments);
    if (downloadAutomatedPaymentsBtn) {
        downloadAutomatedPaymentsBtn.addEventListener('click', () => {
            descargarComoCSV(automatedPaymentsActuales, 'pagos_automatizados.csv');
        });
    }
    if (addAutomatedPaymentForm) {
        addAutomatedPaymentForm.addEventListener('submit', async function(e) {    
            e.preventDefault();
            const paymentData = {
                client_name: document.getElementById('automated-client-name').value,
                product_name: document.getElementById('automated-product-name').value,
                amount: parseFloat(document.getElementById('automated-amount').value),
                payment_date: document.getElementById('automated-payment-date').value + ' 00:00:00', // Añadir hora
                status: document.getElementById('automated-status').value,
                next_due_date: document.getElementById('automated-next-due-date').value || null
            };

            try {    
                // SIMULACIÓN DE CREACIÓN
                const newIdNumeric = Object.keys(automatedPaymentsActuales).length > 0 ? Math.max(...Object.keys(automatedPaymentsActuales).map(k => parseInt(k.replace('auto-pay-', '')))) + 1 : 1;
                const newId = 'auto-pay-' + newIdNumeric;

                const data = { success: true, message: "Pago automatizado registrado simuladamente.",
                                 payment: { id: newIdNumeric, ...paymentData } };

                if (data.success) {
                    closePanel('addAutomatedPaymentPanel');
                    addAutomatedPaymentForm.reset();
                    showCustomNotification('Pago automatizado registrado con éxito (simulado).', 'success');
                    automatedPaymentsActuales[newId] = { id: newId, db_id: data.payment.id, ...paymentData };
                    updateAllFinancialMetrics(); // Recalcular y actualizar todas las métricas
                    renderAutomatedPayments();
                } else {
                    showCustomNotification('Error al registrar pago automatizado (simulado): ' + (data.message || 'Error desconocido.'), 'error');
                }
            } catch (error) {
                showCustomNotification('Error de conexión al registrar el pago automatizado (simulado).', 'error');
                console.error('Create automated payment error (simulado):', error);
            }
        });
    }
    if (viewAutomatedPaymentForm) {
        viewAutomatedPaymentForm.addEventListener('submit', async function(e) {    
            e.preventDefault();
            const paymentData = {
                id: document.getElementById('view-automated-payment-id').value, // Esto es el db_id
                client_name: document.getElementById('view-automated-client-name').value,
                product_name: document.getElementById('view-automated-product-name').value,
                amount: parseFloat(document.getElementById('view-automated-amount').value),
                payment_date: document.getElementById('view-automated-payment-date').value + ' 00:00:00',
                status: document.getElementById('view-automated-status').value,
                next_due_date: document.getElementById('view-automated-next-due-date').value || null
            };
            try {    
                // SIMULACIÓN DE ACTUALIZACIÓN
                const internalIdToUpdate = `auto-pay-${paymentData.id}`;
                const data = { success: true, message: "Cambios guardados simuladamente.",
                                 payment: { id: paymentData.id, ...paymentData } };
                if (data.success) {
                    closePanel('viewAutomatedPaymentPanel');
                    showCustomNotification('Cambios guardados con éxito (simulado).', 'success');
                    automatedPaymentsActuales[internalIdToUpdate] = { id: internalIdToUpdate, db_id: data.payment.id, ...paymentData };
                    updateAllFinancialMetrics(); // Recalcular y actualizar todas las métricas
                    renderAutomatedPayments();
                } else {
                    showCustomNotification('Error al guardar cambios (simulado): ' + (data.message || 'Error desconocido.'), 'error');
                }
            } catch (error) {
                showCustomNotification('Error de conexión al guardar los cambios (simulado).', 'error');
                console.error('Update automated payment error (simulado):', error);
            }
        });
    }

    // LISTENERS PARA PAGOS MANUALES
    if (manualPaymentSearch) manualPaymentSearch.addEventListener('input', renderManualPayments);
    if (downloadManualPaymentsBtn) {
        downloadManualPaymentsBtn.addEventListener('click', () => {
            descargarComoCSV(manualPaymentsActuales, 'pagos_manuales.csv');
        });
    }
    if (addManualPaymentForm) {
        addManualPaymentForm.addEventListener('submit', async function(e) {    
            e.preventDefault();
            const paymentData = {
                client_name: document.getElementById('manual-client-name').value,
                description: document.getElementById('manual-description').value,
                amount: parseFloat(document.getElementById('manual-amount').value),
                payment_date: document.getElementById('manual-payment-date').value + ' 00:00:00'
            };
            try {    
                // SIMULACIÓN DE CREACIÓN
                const newIdNumeric = Object.keys(manualPaymentsActuales).length > 0 ? Math.max(...Object.keys(manualPaymentsActuales).map(k => parseInt(k.replace('manual-pay-', '')))) + 1 : 1;
                const newId = 'manual-pay-' + newIdNumeric;
                const data = { success: true, message: "Pago manual registrado simuladamente.",
                                 payment: { id: newIdNumeric, ...paymentData } };
                if (data.success) {
                    closePanel('addManualPaymentPanel');
                    addManualPaymentForm.reset();
                    showCustomNotification('Pago manual registrado con éxito (simulado).', 'success');
                    manualPaymentsActuales[newId] = { id: newId, db_id: data.payment.id, ...paymentData };
                    updateAllFinancialMetrics(); // Recalcular y actualizar todas las métricas
                    renderManualPayments();
                } else {
                    showCustomNotification('Error al registrar pago manual (simulado): ' + (data.message || 'Error desconocido.'), 'error');
                }
            } catch (error) {
                showCustomNotification('Error de conexión al registrar el pago manual (simulado).', 'error');
                console.error('Create manual payment error (simulado):', error);
            }
        });
    }
    if (viewManualPaymentForm) {
        viewManualPaymentForm.addEventListener('submit', async function(e) {    
            e.preventDefault();
            const paymentData = {
                id: document.getElementById('view-manual-payment-id').value,
                client_name: document.getElementById('view-manual-client-name').value,
                description: document.getElementById('view-manual-description').value,
                amount: parseFloat(document.getElementById('view-manual-amount').value),
                payment_date: document.getElementById('view-manual-payment-date').value + ' 00:00:00'
            };
            try {    
                // SIMULACIÓN DE ACTUALIZACIÓN
                const internalIdToUpdate = `manual-pay-${paymentData.id}`;
                const data = { success: true, message: "Cambios guardados simuladamente.",
                                 payment: { id: paymentData.id, ...paymentData } };
                if (data.success) {
                    closePanel('viewManualPaymentPanel');
                    showCustomNotification('Cambios guardados con éxito (simulado).', 'success');
                    manualPaymentsActuales[internalIdToUpdate] = { id: internalIdToUpdate, db_id: data.payment.id, ...paymentData };
                    updateAllFinancialMetrics(); // Recalcular y actualizar todas las métricas
                    renderManualPayments();
                } else {
                    showCustomNotification('Error al guardar cambios (simulado): ' + (data.message || 'Error desconocido.'), 'error');
                }
            } catch (error) {
                showCustomNotification('Error de conexión al guardar los cambios (simulado).', 'error');
                console.error('Update manual payment error (simulado):', error);
            }
        });
    }

    // Listener para el botón general de Añadir Pago del sidebar
    if (addFinanceEntryBtn) {
        // Al hacer clic en "Añadir Pago" preguntamos qué tipo de pago quiere añadir
        addFinanceEntryBtn.addEventListener('click', () => {
            showCustomNotification('¿Qué tipo de pago deseas añadir? Abre el panel de Pagos Automatizados o Pagos Manuales y usa el botón "Registrar Pago".', 'info', 5000); // Mensaje informativo
            // Puedes agregar aquí un modal pequeño con opciones si prefieres una interacción más directa.
        });
    }
});
</script>
</body>
</html>