<?php
// Lógica de sesión y configuración
ob_start();
session_start();
include_once 'db/db_connection.php'; 

// --- LÓGICA DE PROYECTOS ---
$active_projects = [];
$archived_projects = [];
$projects_counts = ['activos' => 0, 'en_proceso' => 0, 'completado' => 0];

try {
    // --- LÓGICA DE CONTEO OPTIMIZADA ---
    $stmt_counts = $pdo->query("
        SELECT
            SUM(CASE WHEN status NOT IN ('Completado', 'Archivado') THEN 1 ELSE 0 END) as activos,
            SUM(CASE WHEN status = 'En Proceso' THEN 1 ELSE 0 END) as en_proceso,
            SUM(CASE WHEN status = 'Completado' THEN 1 ELSE 0 END) as completado
        FROM projects
    ");
    $counts = $stmt_counts->fetch(PDO::FETCH_ASSOC);
    
    // Asigna los valores, con un fallback a 0 si la consulta no devuelve nada
    $projects_counts['activos'] = $counts['activos'] ?? 0;
    $projects_counts['en_proceso'] = $counts['en_proceso'] ?? 0;
    $projects_counts['completado'] = $counts['completado'] ?? 0;


    // --- LÓGICA PARA OBTENER LOS PROYECTOS ---
    $stmt_projects = $pdo->query("
        SELECT p.id, p.name, p.description, p.start_date, p.due_date, p.status, p.updated_at, c.first_name, c.last_name, p.client_id, s.name as service_name, s.id as service_id
        FROM projects p
        JOIN clients c ON p.client_id = c.id
        LEFT JOIN services s ON p.service_id = s.id
        ORDER BY p.created_at DESC
    ");
    $db_projects_rows = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_projects_rows as $row) {
        $project_data = [
            'id' => $row['id'],
            'name' => $row['name'],
            'description' => $row['description'],
            'client_name' => trim($row['first_name'] . ' ' . $row['last_name']),
            'client_id' => $row['client_id'],
            'service_name' => $row['service_name'] ?? 'No asignado',
            'service_id' => $row['service_id'] ?? null,
            'start_date' => $row['start_date'],
            'due_date' => $row['due_date'],
            'status' => $row['status'],
            'updated_at' => $row['updated_at']
        ];
        
        if ($row['status'] === 'Archivado') {
            $archived_projects[] = $project_data;
        } else {
            $active_projects[$row['id']] = $project_data;
        }
        
        // El conteo manual que estaba aquí ha sido eliminado.
    }
    
    usort($archived_projects, fn($a, $b) => strtotime($b['updated_at']) - strtotime($a['updated_at']));

} catch (PDOException $e) {
    error_log("Error al cargar proyectos: " . $e->getMessage());
    // En caso de error, los contadores permanecerán en 0, como se inicializaron.
}

$projects_json = json_encode($active_projects);

$clients_for_selector = [];
try {
    $stmt_clients = $pdo->query("SELECT id, first_name, last_name FROM clients ORDER BY first_name ASC");
    $clients_for_selector = $stmt_clients->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { error_log("Error al cargar clientes: " . $e->getMessage()); }
$clients_json_selector = json_encode($clients_for_selector);

$services_for_selector = [];
try {
    $stmt_services = $pdo->query("SELECT id, name FROM services ORDER BY name ASC");
    $services_for_selector = $stmt_services->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { error_log("Error al cargar servicios: " . $e->getMessage()); }
$services_json_selector = json_encode($services_for_selector);

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 Proyectos 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>
    
</head>
<body data-page-title="Centro De Gestión De Proyectos"
data-page-subtitle="Organiza, Planifica Y Ejecuta Tus Trabajos"
data-page-icon="construction">
    
<?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="proyectos" 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="layout-dashboard" class="w-7 h-7 text-[var(--color-secondary)]"></i> TABLERO DE PROYECTOS ACTIVOS</h3><p class="text-gray-500 text-sm mt-1 uppercase">ARRASTRA LAS TARJETAS PARA CAMBIAR EL ESTADO DE TUS PROYECTOS.</p></div>
                        <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('addProjectPanel')"><i data-lucide="plus" class="w-5 h-5 mr-2"></i> NUEVO PROYECTO</button>
                    </div>
                    <div class="grid grid-cols-1 md: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-[var(--color-secondary)]">
        <i data-lucide="alarm-clock" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">PROYECTOS ACTIVOS</h3>
            <p id="count-activos" class="text-5xl font-bold text-[var(--color-secondary)]"><?php echo $projects_counts['activos']; ?></p>
            <p class="text-sm text-gray-400 mt-1 uppercase">EN CURSO</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-secondary)]">
        <i data-lucide="waypoints" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">EN PROCESO</h3>
            <p id="count-en-proceso" class="text-5xl font-bold text-[var(--color-secondary)]"><?php echo $projects_counts['en_proceso']; ?></p>
            <p class="text-sm text-gray-400 mt-1 uppercase">SIENDO EJECUTADOS</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-2" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">LISTOS PARA ARCHIVAR</h3>
            <p id="count-completado" class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $projects_counts['completado']; ?></p>
            <p class="text-sm text-gray-400 mt-1 uppercase">TRABAJO TERMINADO</p>
        </div>
    </div>
    
</div>
                    <div class="space-y-6">
    <?php $columns = ["top" => ["Aprobado" => "check-square", "En Planificación" => "clipboard-list", "En Proceso" => "tool-case"],"bottom" => ["Listo para Revisión" => "user-star", "Esperando Aprobación" => "hourglass", "Completado" => "folder-check"]];
    foreach ($columns as $row_columns): ?>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <?php foreach ($row_columns as $name => $icon): $slug = str_replace(' ', '-', strtolower($name)); ?>
        <div class="w-full bg-gray-50 rounded-b-lg">
            <h4 class="text-lg font-extrabold text-white p-3 border-b flex items-center gap-2 uppercase bg-slate-800 rounded-t-lg">
                <i data-lucide="<?php echo $icon; ?>" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                <span><?php echo $name; ?></span>
            </h4>
            <div id="column-<?php echo $slug; ?>" class="p-3 space-y-3 min-h-[40vh] project-column" data-status="<?php echo $name; ?>"></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
</div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2 mb-4"><i data-lucide="list-checks" class="w-7 h-7 text-[var(--color-secondary)]"></i> LISTA DE PROYECTOS EN CURSO</h3>
                    <div 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">Proyecto</th><th class="py-3 px-6 font-semibold hidden md:table-cell">Cliente</th><th class="py-3 px-6 font-semibold hidden lg:table-cell">Entrega</th><th class="py-3 px-6 font-semibold text-center">Estado</th></tr></thead>
                            <tbody id="active-projects-table-body" class="text-gray-700 text-sm"></tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2 mb-4"><i data-lucide="archive" class="w-7 h-7 text-[var(--color-secondary)]"></i> HISTORIAL DE PROYECTOS TERMINADOS</h3>
                    <div 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">Proyecto</th><th class="py-3 px-6 font-semibold hidden md:table-cell">Cliente</th><th class="py-3 px-6 font-semibold hidden lg:table-cell">Fecha de Entrega</th><th class="py-3 px-6 font-semibold text-center">Estado</th><th class="py-3 px-6 font-semibold text-center">Acciones</th></tr></thead>
                            <tbody id="archived-projects-table-body" class="text-gray-700 text-sm"></tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addProjectPanel" 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-plus" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">CREAR NUEVO PROYECTO</h3>
            </div>
            <button onclick="closePanel('addProjectPanel')" 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-project-form" class="flex-grow overflow-y-auto pr-2 -mr-2 space-y-4">
                <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Proyecto</label><input type="text" name="name" id="project-name" class="w-full p-3 border rounded-lg" placeholder="Ej: Rediseño Web Corporativo" required></div>
                <div class="relative"><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Buscar Cliente</label><input type="text" id="project-client-search" class="w-full p-3 border rounded-lg" placeholder="Escribe para buscar un cliente..." required><input type="hidden" name="client_id" id="project-client-id">
                    <div id="client-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-48 overflow-y-auto hidden"></div>
                </div>
                <div class="relative"><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Vincular a Servicio</label><input type="text" id="project-service-search" class="w-full p-3 border rounded-lg" placeholder="Escribe para buscar un servicio..." required><input type="hidden" name="service_id" id="project-service-id">
                    <div id="service-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-48 overflow-y-auto hidden"></div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Fecha de Inicio</label><input type="date" name="start_date" id="project-start-date" class="w-full p-3 border rounded-lg" required></div>
                    <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Fecha de Entrega</label><input type="date" name="due_date" id="project-due-date" class="w-full p-3 border rounded-lg"></div>
                </div>
                <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Descripción</label><textarea name="description" id="project-description" rows="3" class="w-full p-3 border rounded-lg"></textarea></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('addProjectPanel')">Cancelar</button>
                <button type="submit" form="add-project-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">Guardar</button>
            </div>
        </div>
    </div>
</div>

<div id="viewProjectPanel" 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-open" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">FICHA DEL PROYECTO</h3>
            </div>
            <button onclick="closePanel('viewProjectPanel')" 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">
            <div id="view-project-content" class="flex-grow overflow-y-auto pr-2 -mr-2">
                <h2 id="view-project-name" class="text-3xl font-extrabold text-gray-900 mb-6 uppercase"></h2>
                <div class="space-y-6">
                    <div class="bg-gray-50 p-4 rounded-lg"><h4 class="text-sm font-bold text-gray-500 mb-2 uppercase">Información Principal</h4><p id="view-project-client" class="flex items-center gap-2 font-semibold text-gray-700"></p><p id="view-project-service" class="flex items-center gap-2 font-semibold text-gray-700 mt-2"></p><p id="view-project-status" class="flex items-center gap-2 font-semibold text-gray-700 mt-2"></p></div>
                    <div class="bg-gray-50 p-4 rounded-lg"><h4 class="text-sm font-bold text-gray-500 mb-2 uppercase">Fechas Clave</h4><p id="view-project-start-date" class="flex items-center gap-2 font-semibold text-gray-700"></p><p id="view-project-due-date" class="flex items-center gap-2 font-semibold text-gray-700 mt-2"></p></div>
                    <div class="bg-gray-50 p-4 rounded-lg"><h4 class="text-sm font-bold text-gray-500 mb-2 uppercase">Descripción</h4><p id="view-project-description" class="text-gray-700 whitespace-pre-wrap"></p></div>
                </div>
            </div>
            <div class="flex justify-end space-x-4 pt-6 flex-shrink-0">
               <button id="delete-project-btn-view" type="button" class="bg-[var(--color-secondary)] text-white font-bold py-2 px-4 rounded-lg uppercase">Eliminar</button>
               <button id="edit-project-btn-view" type="button" class="bg-[var(--color-primary)] text-white font-bold py-2 px-4 rounded-lg uppercase">Editar</button>
               <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('viewProjectPanel')">Cerrar</button>
            </div> 
        </div>
    </div>
</div>

<div id="editProjectPanel" 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">EDITAR PROYECTO</h3>
            </div>
            <button onclick="closePanel('editProjectPanel')" 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="edit-project-form" class="flex-grow overflow-y-auto pr-2 -mr-2 space-y-4">
                <input type="hidden" name="id" id="edit-project-id">
                <input type="hidden" name="action" value="edit_details">
                <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Proyecto</label><input type="text" name="name" id="edit-project-name" class="w-full p-3 border rounded-lg" required></div>
                <div class="relative"><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Buscar Cliente</label><input type="text" id="edit-project-client-search" class="w-full p-3 border rounded-lg" required><input type="hidden" name="client_id" id="edit-project-client-id">
                    <div id="edit-client-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-48 overflow-y-auto hidden"></div>
                </div>
                <div class="relative"><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Vincular a Servicio</label><input type="text" id="edit-project-service-search" class="w-full p-3 border rounded-lg" required><input type="hidden" name="service_id" id="edit-project-service-id">
                    <div id="edit-service-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-48 overflow-y-auto hidden"></div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Fecha de Inicio</label><input type="date" name="start_date" id="edit-project-start-date" class="w-full p-3 border rounded-lg" required></div>
                    <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Fecha de Entrega</label><input type="date" name="due_date" id="edit-project-due-date" class="w-full p-3 border rounded-lg"></div>
                </div>
                <div><label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Descripción</label><textarea name="description" id="edit-project-description" rows="3" class="w-full p-3 border rounded-lg"></textarea></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('editProjectPanel')">Cancelar</button>
                <button type="submit" form="edit-project-form" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase">Guardar Cambios</button>
            </div>
        </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">PROYECTO</span>? ESTA ACCIÓN NO SE PUEDE DESHACER.</p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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 w-full sm:w-auto" id="cancel-delete-button">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>

<script>
    // --- GESTIÓN DE PANELES Y NOTIFICACIONES (GLOBAL) ---
    const panelOverlay = document.createElement('div');
    window.showToast = function(message, type = 'info') {
        const toast = document.createElement('div');
        const icon = type === 'success' ? 'check-circle' : 'alert-triangle';
        const colors = type === 'success' ? 'bg-[var(--color-primary)] text-white' : 'bg-[var(--color-secondary)] text-white';
        toast.className = `fixed top-5 right-5 p-4 rounded-lg shadow-lg flex items-center gap-3 transform translate-x-full transition-transform duration-300 ease-in-out ${colors} z-[100]`;
        toast.innerHTML = `<i data-lucide="${icon}" class="w-6 h-6"></i><p class="font-semibold">${message}</p>`;
        document.body.appendChild(toast);
        lucide.createIcons();
        setTimeout(() => toast.classList.remove('translate-x-full'), 50);
        setTimeout(() => { toast.classList.add('translate-x-full'); setTimeout(() => toast.remove(), 300); }, 3500);
    };
    document.addEventListener('DOMContentLoaded', () => {
        panelOverlay.id = 'panel-overlay';
        panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
        document.body.appendChild(panelOverlay);
        panelOverlay.addEventListener('click', () => {
            document.querySelectorAll('.fixed.inset-y-0.right-0').forEach(p => p.classList.add('translate-x-full'));
            panelOverlay.classList.add('hidden');
        });
        document.getElementById('mobile-menu-button')?.addEventListener('click', () => {
            document.getElementById('sidebar')?.classList.toggle('-translate-x-full');
            document.getElementById('sidebar-overlay')?.classList.toggle('hidden');
        });
        document.getElementById('sidebar-overlay')?.addEventListener('click', () => {
            document.getElementById('sidebar')?.classList.add('-translate-x-full');
            document.getElementById('sidebar-overlay')?.classList.add('hidden');
        });
    });
    window.openPanel = (id) => { document.getElementById(id)?.classList.remove('translate-x-full'); panelOverlay.classList.remove('hidden'); };
    window.closePanel = (id) => { document.getElementById(id)?.classList.add('translate-x-full'); panelOverlay.classList.add('hidden'); };

    // --- LÓGICA DE LA PÁGINA DE PROYECTOS ---
    document.addEventListener('DOMContentLoaded', function() {
        let projectsData = <?php echo $projects_json; ?>;
        let archivedProjects = <?php echo json_encode($archived_projects); ?>;
        const clientsData = <?php echo $clients_json_selector; ?>;
        const servicesData = <?php echo $services_json_selector; ?>;
        let currentViewingProjectId = null;
        let pendingDeletionId = null;

        const API_UPDATE_URL = 'db/projects-update.php';
        const API_CREATE_URL = 'db/projects-create.php';
        const API_DELETE_URL = 'db/projects-delete.php';

        function openProjectDetailsPanel(projectId) {
            currentViewingProjectId = projectId;
            const allProjects = {...projectsData, ...archivedProjects.reduce((acc, p) => ({...acc, [p.id]: p}), {})};
            const project = allProjects[projectId];
            if (!project) return;
            
            document.getElementById('view-project-name').textContent = project.name;
            document.getElementById('view-project-client').innerHTML = `<i data-lucide="user" class="w-4 h-4 text-gray-500"></i> Cliente: <strong>${project.client_name}</strong>`;
            document.getElementById('view-project-service').innerHTML = `<i data-lucide="briefcase" class="w-4 h-4 text-gray-500"></i> Servicio: <strong>${project.service_name}</strong>`;
            document.getElementById('view-project-status').innerHTML = `<i data-lucide="tag" class="w-4 h-4 text-gray-500"></i> Estado: <strong>${project.status}</strong>`;
            const startDate = project.start_date ? new Date(project.start_date+'T00:00:00').toLocaleDateString('es-ES') : 'No definida';
            const dueDate = project.due_date ? new Date(project.due_date+'T00:00:00').toLocaleDateString('es-ES') : 'No definida';
            document.getElementById('view-project-start-date').innerHTML = `<i data-lucide="calendar-plus" class="w-4 h-4 text-gray-500"></i> Inicio: <strong>${startDate}</strong>`;
            document.getElementById('view-project-due-date').innerHTML = `<i data-lucide="calendar-check" class="w-4 h-4 text-gray-500"></i> Entrega: <strong>${dueDate}</strong>`;
            document.getElementById('view-project-description').textContent = project.description || 'No hay descripción para este proyecto.';
            lucide.createIcons();
            openPanel('viewProjectPanel');
        };
        
        function setupSearchableInput(inputId, hiddenId, resultsId, data, nameKey1, nameKey2 = null) {
            const searchInput = document.getElementById(inputId);
            const hiddenInput = document.getElementById(hiddenId);
            const resultsDiv = document.getElementById(resultsId);

            searchInput.addEventListener('input', () => {
                const query = searchInput.value.toLowerCase();
                resultsDiv.innerHTML = '';
                hiddenInput.value = ''; 

                if (query.length < 1) {
                    resultsDiv.classList.add('hidden');
                    return;
                }
                const filtered = data.filter(item => 
                    ((nameKey2 ? `${item[nameKey1]} ${item[nameKey2]}` : item[nameKey1]) || '').toLowerCase().includes(query)
                );
                if (filtered.length > 0) {
                    filtered.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'p-2 cursor-pointer hover:bg-gray-100 search-result-item';
                        div.textContent = nameKey2 ? `${item[nameKey1]} ${item[nameKey2]}` : item[nameKey1];
                        div.dataset.id = item.id;
                        resultsDiv.appendChild(div);
                    });
                    resultsDiv.classList.remove('hidden');
                } else {
                    resultsDiv.classList.add('hidden');
                }
            });

            resultsDiv.addEventListener('mousedown', function(e) {
                if (e.target && e.target.classList.contains('search-result-item')) {
                    const target = e.target;
                    searchInput.value = target.textContent;
                    hiddenInput.value = target.dataset.id;
                    resultsDiv.classList.add('hidden');
                }
            });

            searchInput.addEventListener('blur', () => {
                setTimeout(() => {
                    resultsDiv.classList.add('hidden');
                }, 150);
            });
        }

        setupSearchableInput('project-client-search', 'project-client-id', 'client-search-results', clientsData, 'first_name', 'last_name');
        setupSearchableInput('project-service-search', 'project-service-id', 'service-search-results', servicesData, 'name');
        setupSearchableInput('edit-project-client-search', 'edit-project-client-id', 'edit-client-search-results', clientsData, 'first_name', 'last_name');
        setupSearchableInput('edit-project-service-search', 'edit-project-service-id', 'edit-service-search-results', servicesData, 'name');
        
        const getStatusClass = (status) => {
            const classes = { 'Aprobado': 'bg-[var(--color-secondary)] text-white', 'En Planificación': 'bg-purple-100 text-purple-800', 'En Proceso': 'bg-[var(--color-secondary)] text-white', 'Listo para Revisión': 'bg-[var(--color-highlight)] text-black', 'Esperando Aprobación': 'bg-[var(--color-secondary)] text-white', 'Completado': 'bg-[var(--color-primary)] text-white', 'Archivado': 'bg-gray-100 text-gray-800' };
            return classes[status] || 'bg-gray-100 text-gray-800';
        };

        function renderProjectCard(project) {
            const card = document.createElement('div');
            const statusColors = { 'Aprobado': 'border-[var(--color-secondary)]', 'En Planificación': 'border-purple-500', 'En Proceso': 'border-[var(--color-secondary)]', 'Listo para Revisión': 'border-[var(--color-highlight)]', 'Esperando Aprobación': 'border-[var(--color-secondary)]', 'Completado': 'border-[var(--color-primary)]' };
            card.className = `p-4 bg-white rounded-lg shadow-sm cursor-pointer hover:shadow-lg transition-shadow duration-200 border-l-4 ${statusColors[project.status] || 'border-gray-500'}`;
            card.draggable = true; card.dataset.projectId = project.id;
            const dueDate = project.due_date ? new Date(project.due_date + 'T00:00:00') : null;
            const formattedDate = dueDate ? dueDate.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' }) : 'Sin fecha';
            const dateColor = dueDate && new Date() > dueDate ? 'text-[var(--color-secondary)]' : 'text-gray-500';
            let cardHTML = `<h5 class="font-bold text-gray-900 mb-2">${project.name}</h5><p class="text-xs text-gray-500 mb-4 font-medium flex items-center"><i data-lucide="user" class="w-3 h-3 mr-1.5"></i>${project.client_name}</p><div class="flex justify-between items-center text-xs"><span class="font-semibold ${dateColor} flex items-center"><i data-lucide="calendar" class="w-3 h-3 mr-1.5"></i>${formattedDate}</span>`;
            if (project.status === 'Completado') { cardHTML += `<button class="archive-btn bg-[var(--color-secondary)] text-white font-bold text-xs py-1 px-2 rounded-md flex items-center gap-1 "><i data-lucide="archive" class="w-3 h-3"></i>ARCHIVAR</button>`; }
            cardHTML += `</div>`; card.innerHTML = cardHTML;
            card.addEventListener('click', () => openProjectDetailsPanel(project.id));
            card.querySelector('.archive-btn')?.addEventListener('click', (e) => { e.stopPropagation(); archiveProject(project.id); });
            card.addEventListener('dragstart', e => { if (e.target.tagName !== 'BUTTON') { e.dataTransfer.setData('text/plain', project.id); setTimeout(() => card.classList.add('opacity-50'), 0); } else { e.preventDefault(); } });
            card.addEventListener('dragend', () => card.classList.remove('opacity-50'));
            return card;
        }

        async function archiveProject(projectId) {
            const projectToArchive = projectsData[projectId]; if (!projectToArchive) return;
            const formData = new FormData();
            formData.append('id', projectId);
            formData.append('status', 'Archivado');
            formData.append('action', 'update_status');
            try {
                const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success && result.project) {
                    delete projectsData[projectId];
                    archivedProjects.unshift(result.project);
                    renderAll(); 
                    showToast('Proyecto archivado con éxito', 'success');
                } else { 
                    showToast(result.message || 'Error al archivar', 'error'); 
                }
            } catch(error) { 
                showToast('Error de conexión al archivar.', 'error'); 
            }
        }

        function renderTable(tableBodyId, projects) {
            const tableBody = document.getElementById(tableBodyId);
            tableBody.innerHTML = '';
            const isArchivedTable = tableBodyId === 'archived-projects-table-body';
            const message = isArchivedTable ? 'No hay proyectos archivados.' : 'No hay proyectos activos.';
            if (projects.length === 0) {
                tableBody.innerHTML = `<tr><td colspan="${isArchivedTable ? '5' : '4'}" class="text-center py-6 text-gray-500 italic">${message}</td></tr>`;
                return;
            }
            projects.forEach(p => {
                const statusClass = getStatusClass(p.status);
                let rowHTML = `<tr class="border-b border-gray-200 hover:bg-gray-50"><td class="py-4 px-6 font-medium text-gray-900">${p.name}</td><td class="py-4 px-6 hidden md:table-cell">${p.client_name}</td><td class="py-4 px-6 hidden lg:table-cell">${p.due_date ? new Date(p.due_date+'T00:00:00').toLocaleDateString('es-ES') : 'N/A'}</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-medium ${statusClass}">${p.status}</span></td>`;
                if (isArchivedTable) {
                    rowHTML += `<td class="py-4 px-6 text-center"><button class="delete-project-btn text-[var(--color-secondary)] hover:text-[var(--color-secondary)]" data-project-id="${p.id}" title="Eliminar Permanentemente"><i data-lucide="trash-2" class="w-5 h-5"></i></button></td>`;
                }
                rowHTML += `</tr>`;
                tableBody.innerHTML += rowHTML;
            });
            lucide.createIcons();
        }
        
        function renderAll() {
            renderBoard();
            renderActiveTable();
            renderArchivedTable();
            updateCounts();
        }
        const renderActiveTable = () => renderTable('active-projects-table-body', Object.values(projectsData));
        const renderArchivedTable = () => renderTable('archived-projects-table-body', archivedProjects);

        function updateCounts() {
            let activos = 0, en_proceso = 0, completado = 0;
            Object.values(projectsData).forEach(p => {
                if (p.status !== 'Completado' && p.status !== 'Archivado') activos++;
                if (p.status === 'En Proceso') en_proceso++;
                if (p.status === 'Completado') completado++;
            });
            document.getElementById('count-activos').textContent = activos;
            document.getElementById('count-en-proceso').textContent = en_proceso;
            document.getElementById('count-completado').textContent = completado;
        }

        function renderBoard() {
            document.querySelectorAll('.project-column').forEach(col => col.innerHTML = '');
            Object.values(projectsData).forEach(project => {
                const slug = project.status.replace(/ /g, '-').toLowerCase();
                const column = document.getElementById(`column-${slug}`);
                if (column) {
                    column.appendChild(renderProjectCard(project));
                }
            });
            lucide.createIcons();
        }

        document.querySelectorAll('.project-column').forEach(column => {
            column.addEventListener('dragover', e => e.preventDefault());
            column.addEventListener('drop', async (e) => {
                e.preventDefault();
                const projectId = e.dataTransfer.getData('text/plain');
                const newStatus = column.dataset.status;
                if (projectsData[projectId] && projectsData[projectId].status !== newStatus) {
                    const formData = new FormData();
                    formData.append('id', projectId);
                    formData.append('status', newStatus);
                    formData.append('action', 'update_status');
                    try {
                        const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
                        const result = await response.json();
                        if (result.success && result.project) {
                            projectsData[projectId] = result.project;
                            renderAll();
                            showToast('Estado actualizado', 'success');
                        } else { 
                            showToast(result.message || 'Error al actualizar', 'error'); 
                        }
                    } catch(error) { 
                        showToast('Error de conexión.', 'error'); 
                    }
                }
            });
        });

        document.getElementById('add-project-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);

            if (!formData.get('client_id') || !formData.get('service_id')) {
                showToast('Debes seleccionar un cliente y un servicio de la lista.', 'error');
                return;
            }
            try {
                const response = await fetch(API_CREATE_URL, { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success && result.project) {
                    projectsData[result.project.id] = result.project;
                    renderAll();
                    closePanel('addProjectPanel');
                    form.reset();
                    showToast('Proyecto creado con éxito', 'success');
                } else {
                    showToast(result.message || 'Error al crear proyecto.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al crear el proyecto.', 'error');
            }
        });
        
        document.getElementById('edit-project-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);
            const projectId = formData.get('id');

            if (!formData.get('client_id') || !formData.get('service_id')) {
                showToast('Debes seleccionar un cliente y un servicio de la lista.', 'error');
                return;
            }
            try {
                const response = await fetch(API_UPDATE_URL, { method: 'POST', body: formData });
                const result = await response.json();
                if (result.success && result.project) {
                    projectsData[projectId] = result.project;
                    renderAll();
                    closePanel('editProjectPanel');
                    showToast('Proyecto actualizado con éxito', 'success');
                } else {
                    showToast(result.message || 'Error al actualizar proyecto.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al actualizar.', 'error');
            }
        });

        function openEditPanel() {
            if (!currentViewingProjectId) return;
            const project = projectsData[currentViewingProjectId];
            if (!project) return;

            document.getElementById('edit-project-id').value = project.id;
            document.getElementById('edit-project-name').value = project.name;
            document.getElementById('edit-project-description').value = project.description || '';
            document.getElementById('edit-project-start-date').value = project.start_date;
            document.getElementById('edit-project-due-date').value = project.due_date;
            
            document.getElementById('edit-project-client-search').value = project.client_name;
            document.getElementById('edit-project-client-id').value = project.client_id;
            document.getElementById('edit-project-service-search').value = project.service_name;
            document.getElementById('edit-project-service-id').value = project.service_id;

            closePanel('viewProjectPanel');
            openPanel('editProjectPanel');
        }

        document.getElementById('edit-project-btn-view').addEventListener('click', openEditPanel);

        // Funciones para manejar el modal de confirmación de eliminación
        function openDeleteModal(projectId) {
            pendingDeletionId = projectId;
            const modal = document.getElementById('confirmDeleteModal');
            modal.classList.remove('hidden');
            const modalInner = modal.querySelector('div');
            modalInner.classList.remove('scale-95', 'opacity-0');
            modalInner.classList.add('scale-100', 'opacity-100');
        }

        function closeDeleteModal() {
            const modal = document.getElementById('confirmDeleteModal');
            const modalInner = modal.querySelector('div');
            modalInner.classList.remove('scale-100', 'opacity-100');
            modalInner.classList.add('scale-95', 'opacity-0');
            setTimeout(() => { modal.classList.add('hidden'); }, 300);
        }

        document.getElementById('delete-project-btn-view').addEventListener('click', () => {
             if (currentViewingProjectId) {
                openDeleteModal(currentViewingProjectId);
             }
        });

        document.getElementById('archived-projects-table-body').addEventListener('click', function(e) {
            const button = e.target.closest('.delete-project-btn');
            if (button) {
                const projectId = button.dataset.projectId;
                openDeleteModal(projectId);
            }
        });

        document.getElementById('cancel-delete-button').addEventListener('click', closeDeleteModal);
        document.getElementById('confirm-delete-button').addEventListener('click', () => {
            if (pendingDeletionId) {
                deleteProject(pendingDeletionId);
                closeDeleteModal();
            }
        });
        
        async function deleteProject(projectId) {
            try {
                const response = await fetch(API_DELETE_URL, { 
                    method: 'POST', 
                    headers: { 'Content-Type': 'application/json' }, 
                    body: JSON.stringify({ id: projectId }) 
                });
                const result = await response.json();
                if (result.success) {
                    if (projectsData[projectId]) {
                        delete projectsData[projectId];
                    }
                    archivedProjects = archivedProjects.filter(p => String(p.id) !== String(projectId));
                    
                    renderAll();
                    closePanel('viewProjectPanel');
                    showToast('Proyecto eliminado con éxito', 'success');
                } else { 
                    showToast(result.message || 'Error al eliminar.', 'error'); 
                }
            } catch (error) { 
                showToast('Error de conexión.', 'error'); 
            }
        }

        renderAll();
    });
</script>
</body>
</html>