<?php
/**
 * Módulo Escritorios - Listado
 */

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Definir BASE_PATH si no está definido (ruta a simple_crm)
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Incluir configuración y conexión de base de datos
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Helper de autenticación si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

$db = getDB();

// Asegurar existencia de tabla desk_allowed_statuses en instalaciones antiguas
try {
    $pdo = $db->getConnection();
    $pdo->exec("CREATE TABLE IF NOT EXISTS desk_allowed_statuses (
        id INT AUTO_INCREMENT PRIMARY KEY,
        desk_id INT NOT NULL,
        status VARCHAR(50) NOT NULL,
        position INT DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_desk_status (desk_id, status),
        FOREIGN KEY (desk_id) REFERENCES desks(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (Exception $e) {
    // Ignorar errores de creación para no bloquear la vista
}

// Obtener escritorios con estadísticas usando subconsultas (sin GROUP BY)
$desks = $db->select(
    "SELECT d.*, 
            u.username AS manager_name,
            COALESCE((SELECT COUNT(DISTINCT du.user_id) FROM desk_users du WHERE du.desk_id = d.id), 0) AS total_users,
            COALESCE((SELECT COUNT(*) FROM leads l WHERE l.desk_id = d.id), 0) AS total_leads,
            COALESCE((SELECT COUNT(*) FROM desk_allowed_statuses das WHERE das.desk_id = d.id), 0) AS total_statuses
     FROM desks d
     LEFT JOIN users u ON d.manager_id = u.id
     ORDER BY d.created_at DESC"
);
?>

<?php
// Integración con layout corporativo
$page_title = 'Escritorios';
$current_module = 'desks';
$current_action = 'index';
$content_file = BASE_PATH . '/modules/desks/desks_content.php';
include BASE_PATH . '/modules/shared/layout.php';
return; // Evita render duplicado del HTML legacy
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Escritorios - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
</head>
<body>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>
    
    <div class="container">
        <div class="card">
            <div class="card-header d-flex justify-between align-center">
                <h1 class="card-title">Gestión de Escritorios</h1>
                <a href="?module=desks&action=create" class="btn btn-success">Nuevo Escritorio</a>
            </div>
            
            <?php if (empty($desks)): ?>
                <div class="alert alert-info">
                    No hay escritorios configurados en el sistema.
                </div>
            <?php else: ?>
                <table class="table data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Descripción</th>
                            <th>Manager</th>
                            <th>Usuarios</th>
                            <th>Leads</th>
                            <th>Nuevos</th>
                            <th>Estado</th>
                            <th>Horario</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($desks as $desk): ?>
                            <tr>
                                <td><?php echo $desk['id']; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($desk['name']); ?></strong>
                                </td>
                                <td>
                                    <small><?php echo htmlspecialchars(substr($desk['description'], 0, 50)); ?>
                                    <?php echo strlen($desk['description']) > 50 ? '...' : ''; ?></small>
                                </td>
                                <td>
                                    <?php if ($desk['manager_name']): ?>
                                        <?php echo htmlspecialchars($desk['manager_name']); ?>
                                    <?php else: ?>
                                        <small class="text-muted">Sin asignar</small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-info"><?php echo $desk['total_users']; ?></span>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-primary"><?php echo $desk['total_leads']; ?></span>
                                </td>
                                <td class="text-center">
                                    <?php if ($desk['new_leads'] > 0): ?>
                                        <span class="badge badge-warning"><?php echo $desk['new_leads']; ?></span>
                                    <?php else: ?>
                                        <span class="badge badge-secondary">0</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-<?php echo $desk['status']; ?>">
                                        <?php echo ucfirst($desk['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <small>
                                        <?php echo htmlspecialchars($desk['working_hours_start']); ?> - 
                                        <?php echo htmlspecialchars($desk['working_hours_end']); ?>
                                    </small>
                                </td>
                                <td>
                                    <a href="?module=desks&action=view&id=<?php echo $desk['id']; ?>" 
                                       class="btn btn-small">Ver</a>
                                    <a href="?module=desks&action=edit&id=<?php echo $desk['id']; ?>" 
                                       class="btn btn-small btn-warning">Editar</a>
                                    <a href="?module=desks&action=delete&id=<?php echo $desk['id']; ?>" 
                                       class="btn btn-small btn-danger btn-delete"
                                       onclick="return confirmDelete('¿Eliminar este escritorio?')">Eliminar</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Estadísticas rápidas -->
        <div class="stats-grid">
            <?php
            $total_desks = count($desks);
            $active_desks = count(array_filter($desks, function($d) { return $d['status'] === 'active'; }));
            $total_desk_users = array_sum(array_column($desks, 'total_users'));
            $total_desk_leads = array_sum(array_column($desks, 'total_leads'));
            ?>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_desks; ?></div>
                <div class="stat-label">Total Escritorios</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $active_desks; ?></div>
                <div class="stat-label">Activos</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_desk_users; ?></div>
                <div class="stat-label">Usuarios Asignados</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_desk_leads; ?></div>
                <div class="stat-label">Leads Totales</div>
            </div>
        </div>
    </div>
    
    <script src="/public/script.js"></script>
    <style>
        .badge {
            padding: 0.25rem 0.5rem;
            border-radius: 3px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        .badge-active { background: #28a745; color: white; }
        .badge-inactive { background: #6c757d; color: white; }
        .badge-info { background: #17a2b8; color: white; }
        .badge-primary { background: #007bff; color: white; }
        .badge-warning { background: #ffc107; color: #212529; }
        .badge-secondary { background: #6c757d; color: white; }
        .text-muted { color: #6c757d; }
        .text-center { text-align: center; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-top: 2rem;
        }
        
        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #007bff;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
    </style>
</body>
</html>