<?php
/**
 * Sidebar compartido para todas las páginas del CRM
 */
// Asegurar que $current_module esté definido para evitar warnings
if (!isset($current_module)) {
    $current_module = $_GET['module'] ?? 'dashboard';
}
// Acción actual para resaltar submódulos como tickets
$current_action = $_GET['action'] ?? 'index';

// Helpers de permisos para visibilidad de menú
if (!function_exists('getDB')) {
    require_once BASE_PATH . '/database/connection.php';
}
$pdo = getDB()->getConnection();
$current_user_id = $_SESSION['user_id'] ?? null;

if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}
if (!function_exists('isAdminRole')) {
    function isAdminRole($pdo, $userId) {
        if (empty($userId)) return false;
        try {
            $stmt = $pdo->prepare("SELECT 1 FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.name = 'admin' LIMIT 1");
            $stmt->execute([$userId]);
            return (bool)$stmt->fetchColumn();
        } catch (Exception $e) {
            return false;
        }
    }
}
?>

<aside class="sidebar">
    <div class="sidebar-header">
        <div class="logo" style="display:flex;align-items:center;gap:.75rem;">
            <div class="logo-icon">
                <?php
                $logo_src = '';
                if (!empty($company_logo)) {
                    if (preg_match('/^https?:\/\//', $company_logo) || str_starts_with($company_logo, '/')) {
                        $logo_src = $company_logo;
                    } else {
                        $logo_src = asset('public/uploads/' . $company_logo);
                    }
                } else {
                    $logo_src = asset('public/branding/profix_logo.svg');
                }
                ?>
                <img src="<?php echo htmlspecialchars($logo_src); ?>" alt="Logo">
            </div>
            
        </div>
    </div>

    <nav class="sidebar-nav">
        <ul class="nav-list">
            <?php if (userHasPermissionByName($pdo, 'menu.dashboard.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'dashboard']); ?>" class="nav-link <?php echo ($current_module == 'dashboard') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="3" width="7" height="7"/>
                            <rect x="14" y="3" width="7" height="7"/>
                            <rect x="14" y="14" width="7" height="7"/>
                            <rect x="3" y="14" width="7" height="7"/>
                        </svg>
                    </div>
                    <span class="nav-text">Dashboard</span>
                </a>
            </li>
            <?php endif; ?>
            
            <?php if (userHasPermissionByName($pdo, 'menu.leads.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'leads']); ?>" class="nav-link <?php echo ($current_module == 'leads') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                            <circle cx="9" cy="7" r="4"/>
                            <path d="m22 2-5 10-5-5-5 10"/>
                        </svg>
                    </div>
                    <span class="nav-text">Leads</span>
                    <?php if (isset($leads_count) && $leads_count > 0): ?>
                        <span class="nav-badge"><?php echo $leads_count; ?></span>
                    <?php endif; ?>
                </a>
            </li>
            <?php endif; ?>

            

            <?php if (userHasPermissionByName($pdo, 'menu.clients.view', $current_user_id) || isAdminRole($pdo, (int)$current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'clients']); ?>" class="nav-link <?php echo ($current_module == 'clients') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M16 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                            <circle cx="9" cy="7" r="4"/>
                            <path d="M20 8v6m3-3h-6"/>
                        </svg>
                    </div>
                    <span class="nav-text">Clientes</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.calendar.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'calendar']); ?>" class="nav-link <?php echo ($current_module == 'calendar') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="4" width="18" height="18" rx="2"/>
                            <line x1="16" y1="2" x2="16" y2="6"/>
                            <line x1="8" y1="2" x2="8" y2="6"/>
                            <line x1="3" y1="10" x2="21" y2="10"/>
                        </svg>
                    </div>
                    <span class="nav-text">Calendario</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.desks.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'desks']); ?>" class="nav-link <?php echo ($current_module == 'desks') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
                            <line x1="8" y1="21" x2="16" y2="21"/>
                            <line x1="12" y1="17" x2="12" y2="21"/>
                        </svg>
                    </div>
                    <span class="nav-text">Desks</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.tickets.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'desks','action'=>'tickets']); ?>" class="nav-link <?php echo ($current_module == 'desks' && $current_action == 'tickets') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M4 7h16v10H4z"/>
                            <path d="M8 11h8M8 15h6"/>
                        </svg>
                    </div>
                    <span class="nav-text">Soporte</span>
                    <?php
                        // Mostrar badge separado: open | pending
                        $openCount = 0; $pendingCount = 0;
                        if (userHasPermissionByName($pdo, 'tickets.view', (int)$current_user_id)) {
                            // Verificar que la tabla support_tickets exista para evitar errores en instalaciones sin módulo de soporte
                            $ticketsTableExists = false;
                            try {
                                $existsStmt = $pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'support_tickets'");
                                $ticketsTableExists = ((int)$existsStmt->fetchColumn() > 0);
                            } catch (Exception $e) {
                                $ticketsTableExists = false;
                            }

                            if ($ticketsTableExists) {
                                try {
                                    $stmtTC = $pdo->query("SELECT status, COUNT(*) as cnt FROM support_tickets WHERE status IN ('open','pending') GROUP BY status");
                                    while ($r = $stmtTC->fetch()) {
                                        if ($r['status'] === 'open') { $openCount = (int)$r['cnt']; }
                                        elseif ($r['status'] === 'pending') { $pendingCount = (int)$r['cnt']; }
                                    }
                                } catch (Exception $e) {
                                    // En caso de error en consulta, mantener contadores en 0
                                    $openCount = 0; $pendingCount = 0;
                                }
                            }
                        }
                        if ($openCount > 0 || $pendingCount > 0): ?>
                        <span class="nav-badge"><?php echo $openCount . ' | ' . $pendingCount; ?></span>
                    <?php endif; ?>
                </a>
            </li>
            <?php endif; ?>
            
            <?php if (userHasPermissionByName($pdo, 'menu.users.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'users']); ?>" class="nav-link <?php echo ($current_module == 'users') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                            <circle cx="12" cy="7" r="4"/>
                        </svg>
                    </div>
                    <span class="nav-text">Users</span>
                </a>
            </li>
            <?php endif; ?>
            
            <?php if (userHasPermissionByName($pdo, 'menu.roles.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'roles']); ?>" class="nav-link <?php echo ($current_module == 'roles') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                    </div>
                    <span class="nav-text">Roles y Permisos</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.integrations.view', $current_user_id) || userHasPermissionByName($pdo, 'integrations.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'integrations']); ?>" class="nav-link <?php echo ($current_module == 'integrations') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M10 3a2 2 0 1 1 4 0v3h3a2 2 0 1 1 0 4h-3v4h3a2 2 0 1 1 0 4h-3v3a2 2 0 1 1-4 0v-3H7a2 2 0 1 1 0-4h3v-4H7a2 2 0 1 1 0-4h3V3z"/>
                        </svg>
                    </div>
                    <span class="nav-text">Integraciones</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.payments.view', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'payments']); ?>" class="nav-link <?php echo ($current_module == 'payments') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="4" width="20" height="14" rx="2" ry="2"/>
                            <line x1="2" y1="10" x2="22" y2="10"/>
                            <circle cx="8" cy="15" r="1"/>
                            <circle cx="12" cy="15" r="1"/>
                            <circle cx="16" cy="15" r="1"/>
                        </svg>
                    </div>
                    <span class="nav-text">Payments Methods</span>
                </a>
            </li>
            <?php endif; ?>

            <?php if (userHasPermissionByName($pdo, 'menu.settings.view', $current_user_id) || userHasPermissionByName($pdo, 'config.manage', $current_user_id)) : ?>
            <li class="nav-item">
                <a href="<?php echo route_url(['module'=>'config']); ?>" class="nav-link <?php echo ($current_module == 'config') ? 'active' : ''; ?>">
                    <div class="nav-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="3"/>
                            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
                        </svg>
                    </div>
                    <span class="nav-text">Configuración</span>
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </nav>

    <div class="sidebar-footer">
        <div class="user-profile">
            <div class="user-avatar">
                <div class="avatar-circle">
                    <?php echo strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?>
                </div>
            </div>
            <div class="user-info">
                <div class="user-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Usuario'); ?></div>
                <div class="user-role">Administrador</div>
            </div>
        </div>
        
        <div class="logout-section">
            <a href="<?php echo route_url(['module'=>'auth','action'=>'logout']); ?>" class="logout-btn" title="Cerrar Sesión">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7 17H2a2 2 0 01-2-2V3a2 2 0 012-2h5m6 4l4 4-4 4m4-4H9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </a>
        </div>
    </div>
</aside>
