<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

$servicios_data_from_db = [];
$monthly_sold_services_count = 0;

try {
    $stmt = $pdo->query("
        SELECT 
            s.id, 
            s.name, 
            s.price, 
            s.category, 
            s.description,
            COUNT(cs.client_id) as active_clients
        FROM 
            services s
        LEFT JOIN 
            client_services cs ON s.id = cs.service_id
        GROUP BY 
            s.id
        ORDER BY 
            s.name ASC
    ");
    $db_services_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_services_rows as $row) {
        $servicios_data_from_db['service-' . $row['id']] = [
            'id' => 'service-' . $row['id'],
            'db_id' => $row['id'],
            'nombre' => $row['name'],
            'precio' => $row['price'],
            'categoria' => $row['category'],
            'descripcion' => $row['description'],
            'active_clients' => $row['active_clients']
        ];
    }
} catch (PDOException $e) {
    error_log("Error PDO al cargar servicios en services.php: " . $e->getMessage());
}

try {
    $current_month = date('m');
    $current_year = date('Y');

    $stmt_sold_services = $pdo->prepare("
        SELECT SUM(ii.quantity) as total_sold_items
        FROM invoice_items ii
        JOIN invoices i ON ii.invoice_id = i.id
        WHERE i.status = 'pagada' AND MONTH(i.invoice_date) = :month AND YEAR(i.invoice_date) = :year
    ");
    $stmt_sold_services->bindParam(':month', $current_month);
    $stmt_sold_services->bindParam(':year', $current_year);
    $stmt_sold_services->execute();
    $result = $stmt_sold_services->fetch(PDO::FETCH_ASSOC);

    $monthly_sold_services_count = (int)($result['total_sold_items'] ?? 0);

} catch (PDOException $e) {
    error_log("Error PDO al contar servicios vendidos este mes: " . $e->getMessage());
    $monthly_sold_services_count = 0;
}

$servicios_json = json_encode($servicios_data_from_db);
$monthly_sold_services_json = json_encode($monthly_sold_services_count);

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>Panel De Servicios FlowCRM™  De OrozDesign Powered By OrozCO</title>
  <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'; ?>

    <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>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>

<style>
@media (max-width: 768px) {
  .page-header-container, #page-title, #page-subtitle { display: none !important; }
}
:is(h1,h2,h3,h4,h5,h6){ text-transform:none !important; letter-spacing:normal !important; }
#service-grid-view h3.uppercase,
#service-list-view [data-label="NOMBRE"] .uppercase {
  text-transform: none !important;
  letter-spacing: normal !important;
}
.client-card .chip, .client-card .badge, .client-card .tag, .client-card .label, .client-card .service-badge,
#service-grid-view .chip, #service-grid-view .badge, #service-grid-view .tag, #service-grid-view .label {
  text-transform: uppercase !important; letter-spacing: .02em !important;
}
@media (max-width: 768px) {
  #service-grid-view .bg-gray-100.p-3.flex.justify-end {
    flex-direction: column !important;
    align-items: stretch !important;
    gap: 10px !important;
  }
  #service-grid-view .bg-gray-100.p-3.flex.justify-end > :not([hidden]) ~ :not([hidden]) {
    margin-left: 0 !important;
  }
  #service-grid-view .bg-gray-100.p-3.flex.justify-end > button,
  #service-grid-view .bg-gray-100.p-3.flex.justify-end > a {
    width: 100% !important;
    display: block !important;
    text-align: center !important;
  }
}
@media (max-width: 640px) {
  #service-list-view table.responsive-invoices-table {
    width: 100% !important; border-collapse: collapse; display: block;
  }
  #service-list-view table.responsive-invoices-table thead { display: none !important; }
  #service-list-view table.responsive-invoices-table tbody { display: block; width: 100%; }
  #service-list-view table.responsive-invoices-table tbody tr {
    display: block;
    background:#fff; border-radius:12px; margin:10px 0;
    box-shadow:0 8px 18px rgba(0,0,0,.06); overflow:hidden;
  }
  #service-list-view table.responsive-invoices-table tbody td {
    display:grid; grid-template-columns:42% 1fr; gap:8px;
    padding:10px 12px; border-bottom:1px solid rgba(0,0,0,.06);
    align-items:start; white-space:normal;
  }
  #service-list-view table.responsive-invoices-table tbody td:last-child { border-bottom:none; }
  #service-list-view table.responsive-invoices-table tbody td::before {
    content: attr(data-label);
    font-weight:800; font-size:.72rem; letter-spacing:.02em; text-transform:uppercase; color:#6B7280;
  }
  #service-list-view td [class*="justify-center"] {
    display: flex !important; flex-direction: column !important;
    gap: 10px !important; align-items: stretch !important;
  }
  #service-list-view td [class*="justify-center"] > a,
  #service-list-view td [class*="justify-center"] > button {
    width: 100% !important; display: block !important; text-align: center !important;
  }
}
@media (max-width: 768px) {
  #confirmDeleteModal .flex.justify-center.space-x-4 {
    display:flex !important; flex-direction:column !important; align-items:stretch !important; gap:12px !important;
  }
  #confirmDeleteModal .flex.justify-center.space-x-4 > :not([hidden]) ~ :not([hidden]) { margin-left:0 !important; }
  #confirmDeleteModal .flex.justify-center.space-x-4 > button,
  #confirmDeleteModal .flex.justify-center.space-x-4 > a {
    width:100% !important; display:block !important; text-align:center !important;
  }
  #confirmDeleteModal .bg-white { max-width:92vw !important; margin:16px !important; }
}
</style>

</head>
<body data-page-title="Catálogo De Servicios Ofrecidos"
      data-page-subtitle="Gestión De Propuestas Comerciales Para El Mercado"
      data-page-icon="briefcase-business">

    <div id="toast-container" class="toast-container"></div>
        
<?php include 'files/gtm-body.php'; ?>

<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>
    <div id="task-panel-overlay" class="off-canvas-overlay"></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">
                <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="servicios" 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="package" class="w-7 h-7 text-[var(--color-primary)]"></i> INVENTARIO DE SERVICIOS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">VISUALIZA Y EDITA TUS PRODUCTOS Y SERVICIOS.</p>
                        </div>
                        <div class="flex flex-col sm:flex-row 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 sm:w-auto justify-center uppercase" onclick="openPanel('addServicioPanel')">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> AGREGAR SERVICIO
                            </button>
                            <button class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center w-full sm:w-auto justify-center uppercase text-sm" onclick="openPanel('manageCategoriesPanel')">
                                <i data-lucide="tag" class="w-4 h-4 mr-2"></i> ADMINISTRAR CATEGORÍAS
                            </button>
                            </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 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-[var(--color-primary)]">
                            <i data-lucide="package" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">TOTAL DE SERVICIOS</h3>
                                <p id="total-services-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                                <p class="text-sm text-gray-400 mt-1">EN EL CATÁLOGO</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-highlight)]">
                            <i data-lucide="wallet" class="w-12 h-12 text-gray-700"></i>
                            <div>
                                <h3 class="text-lg font-extrabold text-gray-500 mb-1">SERVICIOS VENDIDOS ESTE MES</h3>
                                <p id="monthly-sold-services-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                                <p class="text-sm text-gray-400 mt-1 uppercase">Basado en facturas pagadas</p>
                            </div>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row gap-4 mb-6">
                        <div class="relative flex-grow">
                            <input type="text" id="service-search" placeholder="Buscar Por Nombre 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>
                        <select id="service-filter-category" 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">TODAS LAS CATEGORÍAS</option>
                        </select>
                        <div class="view-toggle inline-flex bg-gray-200 rounded-lg p-1">
                            <button id="grid-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 active uppercase" title="Vista de Cuadrícula">
                                <i data-lucide="layout-grid" class="w-5 h-5"></i>
                            </button>
                            <button id="list-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 uppercase" title="Vista de Lista">
                                <i data-lucide="list" class="w-5 h-5"></i>
                            </button>
                        </div>
                    </div>

                    <div id="service-grid-view" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    </div>

                    <div id="service-list-view" class="overflow-x-auto hidden">
                        <table class="min-w-full bg-white responsive-invoices-table">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-semibold">NOMBRE</th>
                                    <th class="py-3 px-6 font-semibold hidden md:table-cell">CATEGORÍA</th>
                                    <th class="py-3 px-6 font-semibold">PRECIO</th>
                                    <th class="py-3 px-6 font-semibold">CLIENTES ACTIVOS</th>
                                    <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="servicesTableBody">
                            </tbody>
                        </table>
                    </div>

                </div>
            </section>
        </div>
    </main>
</div>

<div id="addServicioPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="plus-circle" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">AGREGAR NUEVO SERVICIO</h3>
            </div>
            <button onclick="closePanel('addServicioPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <form id="add-servicio-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 class="md:col-span-2">
                        <label for="servicio-nombre" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL SERVICIO</label>
                        <input type="text" id="servicio-nombre" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Limpieza Semanal" required>
                    </div>
                    <div>
                        <label for="servicio-precio" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PRECIO</label>
                        <input type="number" step="0.01" id="servicio-precio" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 50.00" required>
                    </div>
                    <div>
                        <label for="servicio-categoria" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CATEGORÍA</label>
                        <select id="servicio-categoria" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="">Selecciona Una Categoría</option>
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label for="servicio-descripcion" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DESCRIPCIÓN</label>
                        <textarea id="servicio-descripcion" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Descripción Del Servicio"></textarea>
                    </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('addServicioPanel')">CANCELAR</button>
                <button type="submit" form="add-servicio-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR SERVICIO</button>
            </div>
        </div>
    </div>
</div>

<div id="viewServicioPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="clipboard-list" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">DETALLE DEL SERVICIO</h3>
            </div>
            <button onclick="closePanel('viewServicioPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <form id="view-servicio-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
                <input type="hidden" id="view-servicio-id">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                    <div class="md:col-span-2">
                        <label for="view-servicio-nombre" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DEL SERVICIO</label>
                        <input type="text" id="view-servicio-nombre" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Nombre Del servicio">
                    </div>
                    <div>
                        <label for="view-servicio-precio" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PRECIO</label>
                        <input type="number" step="0.01" id="view-servicio-precio" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 50.00">
                    </div>
                    <div>
                        <label for="view-servicio-categoria" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CATEGORÍA</label>
                        <select id="view-servicio-categoria" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="">Selecciona Una Categoría</option>
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label for="view-servicio-descripcion" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DESCRIPCIÓN</label>
                        <textarea id="view-servicio-descripcion" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Descripción Del Servicio"></textarea>
                    </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('viewServicioPanel')">CANCELAR</button>
                <button type="submit" form="view-servicio-form" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR CAMBIOS</button>
            </div>
        </div>
    </div>
</div>

<div id="viewClientsPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="users" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 id="clients-panel-title" class="text-xl font-bold uppercase">CLIENTES CON EL SERVICIO</h3>
            </div>
            <button onclick="closePanel('viewClientsPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div id="clients-list-container" class="p-8 flex-grow overflow-y-auto">
            </div>
    </div>
</div>

<div id="manageCategoriesPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="folder-cog" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">ADMINISTRAR CATEGORÍAS</h3>
            </div>
            <button onclick="closePanel('manageCategoriesPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <h4 class="text-xl font-bold text-gray-700 mb-4 uppercase">Agregar Nueva Categoría</h4>
            <form id="add-category-form" class="mb-8">
                <div class="mb-4">
                    <label for="new-category-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE DE LA CATEGORÍA</label>
                    <input type="text" id="new-category-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. Contabilidad" required>
                </div>
                <button type="submit" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">AÑADIR CATEGORÍA</button>
            </form>

            <h4 class="text-xl font-bold text-gray-700 mb-4 uppercase">Categorías Existentes</h4>
            <div id="category-list-container" class="space-y-2">
                <p class="text-gray-500 text-sm italic">Cargando Categorías...</p>
            </div>
        </div>
        <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('manageCategoriesPanel')">CERRAR</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-[var(--color-secondary)]"></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>

<script>
let serviciosActuales = <?php echo $servicios_json; ?>;
let allCategories = []; 
let monthlySoldServicesCount = <?php echo json_encode($monthly_sold_services_count); ?>;

// --- INICIO: FUNCIÓN DE TOAST (NECESARIA) ---
// Esta función faltaba en tu archivo, la agrego para que los mensajes de error/éxito funcionen.
function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container');
    if (!toastContainer) return;

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    
    let icon = 'info';
    if (type === 'success') icon = 'check-circle';
    if (type === 'error') icon = 'alert-circle';
    if (type === 'warning') icon = 'alert-triangle';

    toast.innerHTML = `<i data-lucide="${icon}" class="w-5 h-5"></i><span>${message}</span>`;
    
    toastContainer.appendChild(toast);
    lucide.createIcons({ container: toast });

    setTimeout(() => {
        toast.classList.add('show');
    }, 100);

    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toast.parentNode === toastContainer) {
                toastContainer.removeChild(toast);
            }
        }, 500);
    }, 4000);
}
// --- FIN: FUNCIÓN DE TOAST ---

document.addEventListener('DOMContentLoaded', function() {
    // --- Selectores de DOM ---
    const monthlySoldServicesCountElement = document.getElementById('monthly-sold-services-count');
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const serviceSearch = document.getElementById('service-search');
    const serviceFilterCategory = document.getElementById('service-filter-category');
    const serviceGridView = document.getElementById('service-grid-view');
    const serviceListView = document.getElementById('service-list-view');
    const servicesTableBody = document.getElementById('servicesTableBody');
    const gridViewBtn = document.getElementById('grid-view-btn');
    const listViewBtn = document.getElementById('list-view-btn');
    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    const confirmItemTypeSpan = document.getElementById('confirm-item-type');
    const addServicioForm = document.getElementById('add-servicio-form');
    const viewServicioForm = document.getElementById('view-servicio-form');
    const totalServicesCountElement = document.getElementById('total-services-count');
    const addServiceCategorySelect = document.getElementById('servicio-categoria');
    const viewServiceCategorySelect = document.getElementById('view-servicio-categoria');
    const newCategoryNameInput = document.getElementById('new-category-name');
    const addCategoryForm = document.getElementById('add-category-form');
    const categoryListContainer = document.getElementById('category-list-container');
    
    let currentServiceView = 'grid';
    
    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 de Panel y Modal ---
    window.openPanel = function(panelId) {
        const panel = document.getElementById(panelId);
        if (!panel) return;
        panel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        if (panelId === 'addServicioPanel') {
            addServicioForm.reset();
            populateCategoryDropdowns();
        } else if (panelId === 'manageCategoriesPanel') {
            newCategoryNameInput.value = '';
            renderCategoryList();
        }
        lucide.createIcons();
    };

    window.closePanel = function(panelId) {
        const panel = document.getElementById(panelId);
        if (!panel) return;
        panel.classList.add('translate-x-full');
        panelOverlay.classList.add('hidden');
    };

    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { showToast(`Error: Modal con ID "${modalId}" no encontrado.`, 'error'); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modal.classList.remove('hidden');
        setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
        panelOverlay.classList.remove('hidden');
        lucide.createIcons();
    };

    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) { showToast(`Error: Modal con ID "${modalId}" no encontrado para cerrar.`, 'error'); return; }
        const modalBox = modal.querySelector('div:first-of-type');
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => { modal.classList.add('hidden'); }, 300);
    };
    
    window.openConfirmDeleteModal = function(itemId, itemType) {
        if (!confirmDeleteButton || !confirmItemTypeSpan) { showToast("Error: Elementos del modal de confirmación no encontrados.", 'error'); return; }
        confirmDeleteButton.dataset.itemId = itemId; 
        confirmDeleteButton.dataset.itemType = itemType;
        confirmItemTypeSpan.textContent = itemType.toUpperCase();
        openModal('confirmDeleteModal');
    };

    window.openViewServicioModal = function(servicioId) {
        const servicio = serviciosActuales[servicioId];
        if (!servicio) { showToast('Servicio no encontrado.', 'error'); return; }
        document.getElementById('view-servicio-id').value = servicio.db_id;
        document.getElementById('view-servicio-nombre').value = servicio.nombre;
        document.getElementById('view-servicio-precio').value = servicio.precio;
        populateCategoryDropdowns(servicio.categoria);
        document.getElementById('view-servicio-descripcion').value = servicio.descripcion || '';
        openPanel('viewServicioPanel');
    };

    async function openClientsPanel(serviceId, serviceName) {
        openPanel('viewClientsPanel');
        const container = document.getElementById('clients-list-container');
        const titleElement = document.getElementById('clients-panel-title');
        titleElement.textContent = `Clientes Con "${serviceName}"`;
        container.innerHTML = '<p class="text-gray-500">Cargando clientes...</p>';

        try {
            // Este archivo db/service-clients-read.php no me lo has dado, pero asumo que existe
            const response = await fetch(`db/service-clients-read.php?service_id=${serviceId}`);
            const data = await response.json();

            if (data.success) {
                container.innerHTML = ''; 
                const totalClients = data.clients.length;
                const summaryCard = document.createElement('div');
                summaryCard.className = 'stat-card bg-white p-4 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)] mb-6';
                summaryCard.innerHTML = `
                    <i data-lucide="users" class="w-10 h-10 text-gray-700"></i>
                    <div>
                        <h3 class="text-md font-extrabold text-gray-500 mb-1 uppercase">Total de Clientes</h3>
                        <p class="text-4xl font-bold text-[var(--color-secondary)]">${totalClients}</p>
                    </div>
                `;
                container.appendChild(summaryCard);

                if (totalClients > 0) {
                    const ul = document.createElement('ul');
                    ul.className = 'space-y-2';
                    data.clients.forEach(client => {
                        const li = document.createElement('li');
                        li.className = 'p-3 bg-gray-100 rounded-lg';
                        li.innerHTML = `<span class="font-semibold text-gray-800">${client.first_name} ${client.last_name}</span>`;
                        ul.appendChild(li);
                    });
                    container.appendChild(ul);
                } else {
                    container.innerHTML += '<p class="text-gray-500 text-center mt-4">No hay clientes asignados a este servicio.</p>';
                }
                lucide.createIcons();
            } else {
                container.innerHTML = `<p class="text-[var(--color-secondary)]">Error: ${data.message}</p>`;
            }
        } catch (error) {
            container.innerHTML = '<p class="text-[var(--color-secondary)]">Error de conexión al cargar los clientes.</p>';
        }
    }

    // --- Funciones de Listeners ---
    function setupDeleteListeners() {
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.removeEventListener('click', handleDeleteButtonClick);
            button.addEventListener('click', handleDeleteButtonClick);
        });
    }
    function handleDeleteButtonClick(e) { e.stopPropagation(); const itemId = e.currentTarget.dataset.itemId; const itemType = e.currentTarget.dataset.itemType; openConfirmDeleteModal(itemId, itemType); }

    function setupEditListeners() {
        document.querySelectorAll('.edit-servicio-btn').forEach(button => {
            button.removeEventListener('click', handleEditServicioButtonClick);
            button.addEventListener('click', handleEditServicioButtonClick);
        });
    }
    function handleEditServicioButtonClick(e) { e.stopPropagation(); const servicioId = e.currentTarget.dataset.servicioId; openViewServicioModal(servicioId); }

    function setupViewClientsListeners() {
        document.querySelectorAll('.view-clients-btn').forEach(button => {
            button.removeEventListener('click', handleViewClientsClick);
            button.addEventListener('click', handleViewClientsClick);
        });
    }
    function handleViewClientsClick(e) {
        e.stopPropagation();
        const serviceDbId = e.currentTarget.dataset.serviceDbId;
        const serviceName = e.currentTarget.dataset.serviceName;
        openClientsPanel(serviceDbId, serviceName);
    }
    
    // --- Funciones de UI ---
    function toggleSidebar() { if (sidebar) sidebar.classList.toggle('-translate-x-full'); if (sidebarOverlay) sidebarOverlay.classList.toggle('hidden'); }
    function updateTotalServicesDisplay() { if (totalServicesCountElement) { totalServicesCountElement.textContent = Object.keys(serviciosActuales).length.toString(); } }
    function updateMonthlySoldServicesDisplay() { if (monthlySoldServicesCountElement) { monthlySoldServicesCountElement.textContent = monthlySoldServicesCount.toString(); } }
    
    // =================================================================
    // --- INICIO DE LÓGICA CORREGIDA (CATEGORÍAS) ---
    // =================================================================

    async function fetchCategories() {
        try {
            const response = await fetch('db/services-categories-read.php'); 
            const data = await response.json();
            if (data.success) {
                allCategories = data.categories; 
                populateCategoryFilter();
                populateCategoryDropdowns();
            } else {
                showToast('No se pudieron cargar las categorías.', 'error');
                console.error(data.message);
                allCategories = []; 
                populateCategoryFilter();
                populateCategoryDropdowns();
            }
        } catch (error) {
            showToast('Error de red al cargar categorías.', 'error');
            console.error('Error en fetchCategories:', error);
            allCategories = [];
            populateCategoryFilter();
            populateCategoryDropdowns();
        }
    }

    function populateCategoryFilter() {
        if (!serviceFilterCategory) return;
        serviceFilterCategory.innerHTML = '<option value="all">TODAS LAS CATEGORÍAS</option>';
        allCategories.forEach(category => {
            const option = new Option(category.name.toUpperCase(), category.name);
            serviceFilterCategory.appendChild(option);
        });
    }

    function populateCategoryDropdowns(selectedCategoryName = '') {
        const selects = [addServiceCategorySelect, viewServiceCategorySelect];
        selects.forEach(select => {
            if (!select) return;
            select.innerHTML = '<option value="">Selecciona Una Categoría</option>';
            allCategories.forEach(category => {
                const option = new Option(category.name, category.name);
                if (category.name === selectedCategoryName) {
                    option.selected = true;
                }
                select.appendChild(option);
            });
        });
    }

    function renderCategoryList() {
        if (!categoryListContainer) return;
        categoryListContainer.innerHTML = '';
        if (allCategories.length === 0) {
            categoryListContainer.innerHTML = '<p class="text-gray-500 text-sm italic">No hay categorías definidas.</p>';
            return;
        }
        allCategories.forEach(category => {
            const categoryEl = document.createElement('div');
            categoryEl.className = 'flex justify-between items-center p-2 bg-gray-100 rounded-lg';
            categoryEl.innerHTML = `
                <span class="font-medium">${category.name}</span>
                <button class="text-[var(--color-secondary)] hover:text-[var(--color-secondary)] delete-category-btn" data-item-type="categoria" data-item-id="${category.id}" title="ELIMINAR CATEGORÍA">
                    <i data-lucide="trash-2" class="w-5 h-5"></i>
                </button>
            `;
            categoryListContainer.appendChild(categoryEl);
        });

        categoryListContainer.querySelectorAll('.delete-category-btn').forEach(button => {
            button.addEventListener('click', handleDeleteButtonClick);
        });
        lucide.createIcons();
    }

    function renderServiceCard(service) {
        const card = document.createElement('div');
        card.className = 'bg-white rounded-xl shadow-md overflow-hidden flex flex-col border border-gray-200';
        card.dataset.servicioId = service.id;
        card.innerHTML = `
            <div class="bg-[var(--color-primary)] text-white p-4 flex items-center justify-between">
                <div class="flex items-center gap-2 flex-grow min-w-0">
                    <i data-lucide="clipboard-check" class="w-5 h-5 flex-shrink-0"></i>
                    <h3 class="font-bold text-lg uppercase truncate">${service.nombre}</h3>
                </div>
            </div>
            <div class="p-6 flex-grow flex flex-col">
                <p class="text-gray-600 uppercase text-sm mb-2 font-semibold">PRECIO:</p>
                <p class="text-[var(--color-secondary)] font-extrabold text-3xl mb-4">$${parseFloat(service.precio).toFixed(2)}</p>
                <p class="text-gray-700 text-sm flex-grow mb-4 line-clamp-3">${service.descripcion || 'Sin descripción.'}</p>
                <div class="flex justify-between items-center text-xs uppercase mt-auto">
                    <span class="text-gray-500">Categoría: <span class="font-semibold">${service.categoria || 'N/A'}</span></span>
                    <span class="flex items-center gap-1 font-bold text-gray-600">
                        <i data-lucide="users" class="w-4 h-4"></i>
                        ${service.active_clients} Clientes
                    </span>
                </div>
            </div>
            <div class="bg-gray-100 p-3 flex justify-end space-x-3 border-t border-gray-200">
                <button class="bg-green-100 hover:bg-green-200 text-green-800 font-semibold p-2 rounded-lg text-sm uppercase view-clients-btn" data-service-db-id="${service.db_id}" data-service-name="${service.nombre}" title="Ver Clientes">
                    <i data-lucide="eye" class="w-5 h-5"></i>
                </button>
                <button class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg text-sm uppercase edit-servicio-btn" data-servicio-id="${service.id}">EDITAR</button>
                <button class="p-2 bg-[var(--color-secondary)] hover:bg-[var(--color-secondary)] text-white rounded-lg delete-btn" data-item-type="servicio" data-item-id="${service.id}" title="ELIMINAR"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
            </div>
        `;
        return card;
    }

    function renderServiceTableRow(service) {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50';
        row.dataset.servicioId = service.id;
        row.innerHTML = `
            <td class="py-4 px-6" data-label="NOMBRE"><span class="font-semibold uppercase">${service.nombre}</span></td>
            <td class="py-4 px-6 hidden md:table-cell" data-label="CATEGORÍA">${service.categoria || 'N/A'}</td>
            <td class="py-4 px-6 uppercase" data-label="PRECIO">$${parseFloat(service.precio).toFixed(2)}</td>
            <td class="py-4 px-6 text-center" data-label="CLIENTES ACTIVOS"><span class="font-bold text-gray-700">${service.active_clients}</span></td>
            <td class="py-4 px-6 text-center" data-label="ACCIONES">
                <div class="flex justify-center space-x-2">
                    <button class="text-green-600 hover:text-green-800 view-clients-btn" title="Ver Clientes" data-service-db-id="${service.db_id}" data-service-name="${service.nombre}">
                        <i data-lucide="eye" class="w-5 h-5"></i>
                    </button>
                    <button class="text-blue-600 hover:text-blue-800 edit-servicio-btn" title="EDITAR" data-servicio-id="${service.id}"><i data-lucide="edit-2" class="w-5 h-5"></i></button>
                    <button class="text-[var(--color-secondary)] hover:text-[var(--color-secondary)] delete-btn" data-item-type="servicio" data-item-id="${service.id}" title="ELIMINAR"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
                </div>
            </td>
        `;
        return row;
    }

    function renderServices(viewType = currentServiceView) {
        const searchTerm = serviceSearch.value.toLowerCase();
        const selectedCategory = serviceFilterCategory.value;
        const filteredServices = Object.values(serviciosActuales).filter(s => {
            const matchesSearch = s.nombre.toLowerCase().includes(searchTerm) || (s.descripcion && s.descripcion.toLowerCase().includes(searchTerm));
            const matchesCategory = selectedCategory === 'all' || (s.categoria && s.categoria === selectedCategory);
            return matchesSearch && matchesCategory;
        });

        serviceGridView.innerHTML = '';
        servicesTableBody.innerHTML = '';

        if (filteredServices.length === 0) {
            const message = `<p class="text-gray-500 md:col-span-3 text-center">NO SE ENCONTRARON SERVICIOS.</p>`;
            serviceGridView.innerHTML = message;
            servicesTableBody.innerHTML = `<tr><td colspan="5" class="py-4 text-center">NO SE ENCONTRARON SERVICIOS.</td></tr>`;
        } else {
            filteredServices.forEach(service => {
                if (viewType === 'grid') {
                    serviceGridView.appendChild(renderServiceCard(service));
                } else {
                    servicesTableBody.appendChild(renderServiceTableRow(service));
                }
            });
        }
        
        if (viewType === 'grid') {
            serviceGridView.classList.remove('hidden');
            serviceListView.classList.add('hidden');
            gridViewBtn.classList.add('active');
            listViewBtn.classList.remove('active');
        } else {
            serviceGridView.classList.add('hidden');
            serviceListView.classList.remove('hidden');
            gridViewBtn.classList.remove('active');
            listViewBtn.classList.add('active');
        }

        setupDeleteListeners();
        setupEditListeners();
        setupViewClientsListeners();
        lucide.createIcons();
    }
    
    // =================================================================
    // --- INICIO DE LÓGICA CORREGIDA (FORMULARIOS) ---
    // =================================================================

    if (addServicioForm) {
        addServicioForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            showToast('Guardando servicio...', 'info');
            
            const formData = {
                name: document.getElementById('servicio-nombre').value,
                price: parseFloat(document.getElementById('servicio-precio').value),
                category: document.getElementById('servicio-categoria').value,
                description: document.getElementById('servicio-descripcion').value,
                show_on_web: false // Asumimos false ya que no está en el formulario
            };

            try {
                const response = await fetch('db/services-create.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast(result.message, 'success');
                    location.reload();
                } else {
                    showToast(result.message || 'Error desconocido al crear.', 'error');
                }
            } catch (error) {
                console.error('Error en addServicioForm:', error);
                showToast('Error de conexión al guardar.', 'error');
            }
        });
    }

    if (viewServicioForm) {
        viewServicioForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = {
                id: document.getElementById('view-servicio-id').value,
                name: document.getElementById('view-servicio-nombre').value,
                price: parseFloat(document.getElementById('view-servicio-precio').value),
                category: document.getElementById('view-servicio-categoria').value,
                description: document.getElementById('view-servicio-descripcion').value,
                show_on_web: false 
            };

            try {
                const response = await fetch('db/services-update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });
                const result = await response.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    location.reload(); 
                } else {
                    showToast(result.message || 'Error desconocido al actualizar.', 'error');
                }
            } catch (error) {
                console.error('Error en viewServicioForm:', error);
                showToast('Error de conexión al actualizar.', 'error');
            }
        });
    }

    if (confirmDeleteButton) {
        confirmDeleteButton.addEventListener('click', async function() {
            const itemId = this.dataset.itemId;
            const itemType = this.dataset.itemType;

            let url = '';
            let body = {};

            if (itemType === 'servicio') {
                const service = serviciosActuales[itemId];
                if (!service) {
                    showToast('Error: Servicio no encontrado.', 'error');
                    return;
                }
                url = 'db/services-delete.php';
                body = { id: service.db_id }; 
            
            } else if (itemType === 'categoria') {
                url = 'db/services-categories-delete.php'; 
                body = { id: parseInt(itemId) }; 
            } else {
                showToast('Tipo de ítem desconocido.', 'error');
                return;
            }

            closeModal('confirmDeleteModal');

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(body)
                });
                const result = await response.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    location.reload();
                } else {
                    showToast(result.message || 'Error desconocido al eliminar.', 'error');
                }
            } catch (error) {
                console.error('Error en confirmDeleteButton click:', error);
                showToast('Error de conexión al eliminar.', 'error');
            }
        });
    }

    if (addCategoryForm) {
        addCategoryForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const categoryName = newCategoryNameInput.value.trim();
            if (!categoryName) {
                showToast('El nombre de la categoría no puede estar vacío.', 'warning');
                return;
            }

            try {
                const response = await fetch('db/services-categories-create.php', { 
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: categoryName })
                });
                const result = await response.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    newCategoryNameInput.value = '';
                    await fetchCategories();
                    renderCategoryList(); 
                } else {
                    showToast(result.message || 'Error al crear la categoría.', 'error');
                }
            } catch (error) {
                console.error('Error en addCategoryForm:', error);
                showToast('Error de conexión al guardar categoría.', 'error');
            }
        });
    }
    
    if (mobileMenuButton) mobileMenuButton.addEventListener('click', toggleSidebar);
    if (sidebarOverlay) sidebarOverlay.addEventListener('click', () => { toggleSidebar(); closePanel('addServicioPanel'); closePanel('viewServicioPanel'); closePanel('manageCategoriesPanel'); closePanel('viewClientsPanel'); });
    panelOverlay.addEventListener('click', () => { closePanel('addServicioPanel'); closePanel('viewServicioPanel'); closePanel('manageCategoriesPanel'); closePanel('viewClientsPanel'); });

    fetchCategories();
    updateTotalServicesDisplay();
    updateMonthlySoldServicesDisplay();
    renderServices(currentServiceView);
    if (serviceSearch) serviceSearch.addEventListener('input', () => renderServices(currentServiceView));
    if (serviceFilterCategory) serviceFilterCategory.addEventListener('change', () => renderServices(currentServiceView));
    if (gridViewBtn) gridViewBtn.addEventListener('click', () => { currentServiceView = 'grid'; renderServices('grid'); });
    if (listViewBtn) listViewBtn.addEventListener('click', () => { currentServiceView = 'list'; renderServices('list'); });
});
</script>

<script>
(function () {
  const table = document.querySelector('#service-list-view table.responsive-invoices-table');
  if (!table) return;
  function getHeaders(t) { return Array.from(t.querySelectorAll('thead th')).map(th => (th.innerText || '').trim()); }
  function applyLabels(t) {
    const labels = getHeaders(t);
    t.querySelectorAll('tbody tr').forEach(tr => {
      tr.querySelectorAll('td').forEach((td, i) => { td.setAttribute('data-label', labels[i] || ''); });
    });
  }
  applyLabels(table);
  new MutationObserver(() => applyLabels(table)).observe(table.tBodies[0], { childList: true });
})();
</script>
</body>
</html>