<?php
@session_start();
require_once '../db.php';
$pdo = pdo();

// TODO: acá después agregamos control de sesión admin

// Traer todos los modelos
$stmt = $pdo->query("
    SELECT *
    FROM modelos_casas
    ORDER BY orden ASC, created_at DESC
");
$modelos = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="es" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <title>Modelos de Cabañas - Panel Administrativo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">
    
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --glass-bg: rgba(255, 255, 255, 0.9);
            --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 8px 32px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 20px 60px rgba(0, 0, 0, 0.15);
            --border-radius-sm: 12px;
            --border-radius-md: 16px;
            --border-radius-lg: 24px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        * {
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding-top: 20px;
            padding-bottom: 40px;
        }
        
        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: var(--shadow-lg);
            border-radius: var(--border-radius-lg);
            overflow: hidden;
        }
        
        .header-section {
            background: var(--primary-gradient);
            color: white;
            padding: 2.5rem 0;
            border-radius: 0 0 var(--border-radius-lg) var(--border-radius-lg);
            position: relative;
            overflow: hidden;
        }
        
        .header-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 100" preserveAspectRatio="none"><path d="M0,0V100H1000V0C750,50 500,100 250,50S0,0,0,0Z" fill="rgba(255,255,255,0.1)"/></svg>');
            background-size: cover;
        }
        
        .header-title {
            font-weight: 700;
            font-size: 2.2rem;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header-subtitle {
            font-weight: 400;
            opacity: 0.9;
            font-size: 1.1rem;
        }
        
        .content-section {
            padding: 2.5rem;
        }
        
        .btn-primary-custom {
            background: var(--primary-gradient);
            border: none;
            color: white;
            padding: 0.85rem 2rem;
            border-radius: 12px;
            font-weight: 600;
            font-size: 1rem;
            transition: var(--transition);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            color: white;
        }
        
        .btn-success-custom {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border: none;
            color: white;
            padding: 0.85rem 2rem;
            border-radius: 12px;
            font-weight: 600;
            font-size: 1rem;
            transition: var(--transition);
            box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
        }
        
        .btn-success-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
            color: white;
        }
        
        .btn-warning-custom {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            border: none;
            color: white;
            padding: 0.5rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            font-size: 0.9rem;
            transition: var(--transition);
        }
        
        .btn-warning-custom:hover {
            transform: translateY(-1px);
            color: white;
        }
        
        .btn-danger-custom {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            border: none;
            color: white;
            padding: 0.5rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            font-size: 0.9rem;
            transition: var(--transition);
        }
        
        .btn-danger-custom:hover {
            transform: translateY(-1px);
            color: white;
        }
        
        .modelo-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: var(--shadow-sm);
            border-left: 4px solid #667eea;
            transition: var(--transition);
        }
        
        .modelo-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-md);
        }
        
        .modelo-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 12px;
            margin-bottom: 1rem;
            transition: var(--transition);
        }
        
        .modelo-image:hover {
            transform: scale(1.03);
        }
        
        .no-image-placeholder {
            width: 100%;
            height: 180px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #718096;
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .modelo-title {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 0.5rem;
            font-size: 1.2rem;
        }
        
        .modelo-desc {
            color: #718096;
            font-size: 0.9rem;
            margin-bottom: 1rem;
            line-height: 1.5;
        }
        
        .modelo-stats {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }
        
        .stat-item {
            background: #f7fafc;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.85rem;
            color: #4a5568;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .stat-item i {
            color: #667eea;
        }
        
        .price-tag {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1.1rem;
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .status-active {
            background: rgba(72, 187, 120, 0.1);
            color: #38a169;
        }
        
        .status-inactive {
            background: rgba(245, 101, 101, 0.1);
            color: #e53e3e;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        .counter-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: var(--shadow-sm);
            margin-bottom: 1.5rem;
            border-top: 4px solid #667eea;
        }
        
        .counter-number {
            font-size: 2.5rem;
            font-weight: 700;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            line-height: 1;
        }
        
        .counter-label {
            color: #718096;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .table-custom {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }
        
        .table-custom thead {
            background: var(--primary-gradient);
            color: white;
        }
        
        .table-custom th {
            border: none;
            font-weight: 600;
            padding: 1rem 1.5rem;
        }
        
        .table-custom tbody tr {
            transition: var(--transition);
        }
        
        .table-custom tbody tr:hover {
            background-color: #f7fafc;
            transform: translateY(-1px);
        }
        
        .table-custom td {
            padding: 1rem 1.5rem;
            vertical-align: middle;
            border-color: #e2e8f0;
        }
        
        .table-image {
            width: 80px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            box-shadow: var(--shadow-sm);
        }
        
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
        }
        
        .empty-state-icon {
            font-size: 4rem;
            color: #cbd5e0;
            margin-bottom: 1.5rem;
        }
        
        .empty-state-title {
            color: #4a5568;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .empty-state-text {
            color: #718096;
            margin-bottom: 2rem;
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .search-box {
            position: relative;
            margin-bottom: 1.5rem;
        }
        
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #a0aec0;
        }
        
        .search-box input {
            padding-left: 2.8rem;
            border-radius: 12px;
            border: 2px solid #e2e8f0;
            transition: var(--transition);
        }
        
        .search-box input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        @media (max-width: 768px) {
            .content-section {
                padding: 1.5rem;
            }
            
            .header-title {
                font-size: 1.8rem;
            }
            
            .modelo-stats {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .action-buttons {
                flex-wrap: wrap;
            }
        }
        
        .view-toggle {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1.5rem;
            background: white;
            padding: 0.5rem;
            border-radius: 12px;
            width: fit-content;
            box-shadow: var(--shadow-sm);
        }
        
        .view-toggle-btn {
            padding: 0.5rem 1.5rem;
            border: none;
            border-radius: 8px;
            background: transparent;
            color: #718096;
            font-weight: 500;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .view-toggle-btn.active {
            background: var(--primary-gradient);
            color: white;
            box-shadow: var(--shadow-sm);
        }
        
        .view-toggle-btn:hover {
            background: #f7fafc;
        }
        
        .view-toggle-btn.active:hover {
            background: var(--primary-gradient);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12 col-xl-12">
                <div class="glass-card fade-in">
                    <!-- Header -->
                    <div class="header-section text-center">
                        <div class="position-relative">
                            <h1 class="header-title">
                                <i class="fas fa-home"></i> Modelos de Cabañas
                            </h1>
                            <p class="header-subtitle">
                                Administra todos los modelos disponibles en el catálogo
                            </p>
                        </div>
                    </div>
                    
                    <!-- Content -->
                    <div class="content-section">
                        <!-- Stats Cards -->
                        <div class="row mb-5">
                            <div class="col-md-3">
                                <div class="counter-card">
                                    <div class="counter-number"><?php echo count($modelos); ?></div>
                                    <div class="counter-label">Total de Modelos</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="counter-card">
                                    <div class="counter-number">
                                        <?php echo count(array_filter($modelos, fn($m) => $m['activo'])); ?>
                                    </div>
                                    <div class="counter-label">Modelos Activos</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="counter-card">
                                    <div class="counter-number">
                                        <?php echo count(array_filter($modelos, fn($m) => !$m['activo'])); ?>
                                    </div>
                                    <div class="counter-label">Modelos Inactivos</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="counter-card">
                                    <div class="counter-number">
                                        <?php echo count(array_filter($modelos, fn($m) => empty($m['imagen_portada']))); ?>
                                    </div>
                                    <div class="counter-label">Sin Imagen</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Header Actions -->
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div>
                                <div class="search-box">
                                    <i class="fas fa-search"></i>
                                    <input type="text" id="searchInput" class="form-control" 
                                           placeholder="Buscar modelos por nombre...">
                                </div>
                            </div>
                            <div>
                                <div class="view-toggle">
                                    <button class="view-toggle-btn active" id="tableViewBtn">
                                        <i class="fas fa-table"></i> Tabla
                                    </button>
                                    <button class="view-toggle-btn" id="cardViewBtn">
                                        <i class="fas fa-th-large"></i> Tarjetas
                                    </button>
                                </div>
                            </div>
                            <div>
                                <a href="modelos_nuevo.php" class="btn btn-primary-custom">
                                    <i class="fas fa-plus me-2"></i> Nuevo Modelo
                                </a>
                            </div>
                        </div>
                        
                        <?php if (empty($modelos)): ?>
                            <!-- Empty State -->
                            <div class="empty-state">
                                <div class="empty-state-icon">
                                    <i class="fas fa-home"></i>
                                </div>
                                <h4 class="empty-state-title">No hay modelos cargados</h4>
                                <p class="empty-state-text">
                                    Comienza agregando tu primer modelo al catálogo
                                </p>
                                <a href="modelos_nuevo.php" class="btn btn-success-custom">
                                    <i class="fas fa-plus me-2"></i> Crear Primer Modelo
                                </a>
                            </div>
                            
                        <?php else: ?>
                            
                            <!-- Table View -->
                            <div id="tableView" class="fade-in">
                                <div class="table-responsive">
                                    <table class="table table-custom" id="modelosTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Imagen</th>
                                                <th>Nombre</th>
                                                <th>Metros</th>
                                                <th>Sistema</th>
                                                <th>Precio Desde</th>
                                                <th>Orden</th>
                                                <th>Estado</th>
                                                <th>Acciones</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($modelos as $m): ?>
                                            <tr class="modelo-row" data-search="<?php echo strtolower(htmlspecialchars($m['nombre'])); ?>">
                                                <td class="fw-bold">#<?php echo $m['id']; ?></td>
                                                <td>
                                                    <?php if (!empty($m['imagen_portada'])): ?>
                                                        <img src="<?php echo htmlspecialchars($m['imagen_portada']); ?>" 
                                                             class="table-image"
                                                             data-bs-toggle="modal" 
                                                             data-bs-target="#imageModal"
                                                             data-image="<?php echo htmlspecialchars($m['imagen_portada']); ?>"
                                                             data-title="<?php echo htmlspecialchars($m['nombre']); ?>">
                                                    <?php else: ?>
                                                        <div class="text-center text-muted">
                                                            <i class="fas fa-image fa-lg"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="fw-bold"><?php echo htmlspecialchars($m['nombre']); ?></div>
                                                    <?php if (!empty($m['descripcion_corta'])): ?>
                                                        <small class="text-muted"><?php echo htmlspecialchars($m['descripcion_corta']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="d-flex flex-column">
                                                        <span class="badge bg-primary mb-1">
                                                            <i class="fas fa-home me-1"></i> <?php echo $m['metros_cubiertos']; ?> m²
                                                        </span>
                                                        <?php if ($m['metros_galeria'] > 0): ?>
                                                            <span class="badge bg-info">
                                                                <i class="fas fa-border-all me-1"></i> +<?php echo $m['metros_galeria']; ?> m²
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <?php 
                                                        $sistemaLabels = [
                                                            'estructura' => '🏗️ Estructura',
                                                            'estructura_plataforma' => '🏗️➕ Estructura + Plataforma',
                                                            'llave_en_mano' => '🔑 Llave en Mano'
                                                        ];
                                                        echo $sistemaLabels[$m['sistema_default']] ?? $m['sistema_default'];
                                                    ?>
                                                </td>
                                                <td class="fw-bold text-success">
                                                    $ <?php echo number_format($m['precio_desde'], 2, ',', '.'); ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary"><?php echo $m['orden']; ?></span>
                                                </td>
                                                <td>
                                                    <?php if ($m['activo']): ?>
                                                        <span class="status-badge status-active">
                                                            <i class="fas fa-check-circle me-1"></i> Activo
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="status-badge status-inactive">
                                                            <i class="fas fa-times-circle me-1"></i> Inactivo
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="action-buttons">
                                                        <a href="modelos_editar.php?id=<?php echo $m['id']; ?>" 
                                                           class="btn btn-warning-custom btn-sm"
                                                           data-bs-toggle="tooltip" title="Editar modelo">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="modelos_eliminar.php?id=<?php echo $m['id']; ?>" 
                                                           class="btn btn-danger-custom btn-sm"
                                                           data-bs-toggle="tooltip" title="Eliminar modelo"
                                                           onclick="return confirm('¿Estás seguro de eliminar el modelo <?php echo addslashes($m['nombre']); ?>? Esta acción no se puede deshacer.');">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                        <a href="#" 
                                                           class="btn btn-outline-primary btn-sm"
                                                           data-bs-toggle="tooltip" title="Ver detalles">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Card View -->
                            <div id="cardView" class="row d-none">
                                <?php foreach ($modelos as $m): ?>
                                <div class="col-12 col-md-6 col-xl-4 mb-4">
                                    <div class="modelo-card" data-search="<?php echo strtolower(htmlspecialchars($m['nombre'])); ?>">
                                        <!-- Imagen -->
                                        <?php if (!empty($m['imagen_portada'])): ?>
                                            <img src="<?php echo htmlspecialchars($m['imagen_portada']); ?>" 
                                                 class="modelo-image"
                                                 data-bs-toggle="modal" 
                                                 data-bs-target="#imageModal"
                                                 data-image="<?php echo htmlspecialchars($m['imagen_portada']); ?>"
                                                 data-title="<?php echo htmlspecialchars($m['nombre']); ?>">
                                        <?php else: ?>
                                            <div class="no-image-placeholder">
                                                <i class="fas fa-home"></i>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- Título -->
                                        <h5 class="modelo-title">
                                            <?php echo htmlspecialchars($m['nombre']); ?>
                                            <span class="badge bg-primary float-end">#<?php echo $m['id']; ?></span>
                                        </h5>
                                        
                                        <!-- Descripción -->
                                        <?php if (!empty($m['descripcion_corta'])): ?>
                                            <p class="modelo-desc"><?php echo htmlspecialchars($m['descripcion_corta']); ?></p>
                                        <?php endif; ?>
                                        
                                        <!-- Stats -->
                                        <div class="modelo-stats">
                                            <div class="stat-item">
                                                <i class="fas fa-ruler-combined"></i>
                                                <?php echo $m['metros_cubiertos']; ?> m²
                                            </div>
                                            <?php if ($m['metros_galeria'] > 0): ?>
                                                <div class="stat-item">
                                                    <i class="fas fa-border-all"></i>
                                                    +<?php echo $m['metros_galeria']; ?> m²
                                                </div>
                                            <?php endif; ?>
                                            <div class="stat-item">
                                                <?php 
                                                    $sistemaIcons = [
                                                        'estructura' => '🏗️',
                                                        'estructura_plataforma' => '🏗️➕',
                                                        'llave_en_mano' => '🔑'
                                                    ];
                                                    echo $sistemaIcons[$m['sistema_default']] ?? '';
                                                ?>
                                                <?php echo $m['sistema_default']; ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Precio -->
                                        <div class="price-tag">
                                            $ <?php echo number_format($m['precio_desde'], 2, ',', '.'); ?>
                                        </div>
                                        
                                        <!-- Estado y Orden -->
                                        <div class="d-flex justify-content-between align-items-center">
                                            <?php if ($m['activo']): ?>
                                                <span class="status-badge status-active">
                                                    <i class="fas fa-check-circle me-1"></i> Activo
                                                </span>
                                            <?php else: ?>
                                                <span class="status-badge status-inactive">
                                                    <i class="fas fa-times-circle me-1"></i> Inactivo
                                                </span>
                                            <?php endif; ?>
                                            <span class="text-muted">
                                                <i class="fas fa-sort-numeric-down me-1"></i> Orden: <?php echo $m['orden']; ?>
                                            </span>
                                        </div>
                                        
                                        <!-- Acciones -->
                                        <div class="action-buttons">
                                            <a href="modelos_editar.php?id=<?php echo $m['id']; ?>" 
                                               class="btn btn-warning-custom flex-grow-1">
                                                <i class="fas fa-edit me-2"></i> Editar
                                            </a>
                                            <a href="modelos_eliminar.php?id=<?php echo $m['id']; ?>" 
                                               class="btn btn-danger-custom"
                                               onclick="return confirm('¿Estás seguro de eliminar el modelo <?php echo addslashes($m['nombre']); ?>?');">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Image Modal -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="imageModalLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="modalImage" src="" class="img-fluid rounded" style="max-height: 70vh;">
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- DataTables JS -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        // Initialize DataTable
        $(document).ready(function() {
            $('#modelosTable').DataTable({
                responsive: true,
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json'
                },
                order: [[5, 'asc']], // Order by Orden column
                pageLength: 10,
                dom: '<"top"f>rt<"bottom"lip><"clear">'
            });
        });
        
        // Initialize tooltips
        const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
        
        // View Toggle
        const tableViewBtn = document.getElementById('tableViewBtn');
        const cardViewBtn = document.getElementById('cardViewBtn');
        const tableView = document.getElementById('tableView');
        const cardView = document.getElementById('cardView');
        
        tableViewBtn.addEventListener('click', () => {
            tableViewBtn.classList.add('active');
            cardViewBtn.classList.remove('active');
            tableView.classList.remove('d-none');
            tableView.classList.add('fade-in');
            cardView.classList.add('d-none');
        });
        
        cardViewBtn.addEventListener('click', () => {
            cardViewBtn.classList.add('active');
            tableViewBtn.classList.remove('active');
            cardView.classList.remove('d-none');
            cardView.classList.add('fade-in');
            tableView.classList.add('d-none');
        });
        
        // Search functionality
        const searchInput = document.getElementById('searchInput');
        const modeloCards = document.querySelectorAll('.modelo-card');
        const modeloRows = document.querySelectorAll('.modelo-row');
        
        searchInput.addEventListener('input', (e) => {
            const searchTerm = e.target.value.toLowerCase().trim();
            
            if (tableView.classList.contains('d-none')) {
                // Card view search
                modeloCards.forEach(card => {
                    const searchData = card.getAttribute('data-search');
                    if (searchData.includes(searchTerm)) {
                        card.style.display = 'block';
                        card.classList.add('fade-in');
                    } else {
                        card.style.display = 'none';
                    }
                });
            } else {
                // Table view search - handled by DataTables
                const dataTable = $('#modelosTable').DataTable();
                dataTable.search(searchTerm).draw();
            }
        });
        
        // Image Modal
        const imageModal = document.getElementById('imageModal');
        imageModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const imageSrc = button.getAttribute('data-image');
            const imageTitle = button.getAttribute('data-title');
            
            const modalTitle = imageModal.querySelector('.modal-title');
            const modalImage = imageModal.querySelector('#modalImage');
            
            modalTitle.textContent = imageTitle;
            modalImage.src = imageSrc;
        });
        
        // Filter functionality
        function filterModels(status) {
            const dataTable = $('#modelosTable').DataTable();
            
            if (status === 'all') {
                dataTable.column(7).search('').draw();
            } else if (status === 'active') {
                dataTable.column(7).search('Activo').draw();
            } else if (status === 'inactive') {
                dataTable.column(7).search('Inactivo').draw();
            }
        }
        
        // Auto refresh stats
        function updateStats() {
            const totalCount = <?php echo count($modelos); ?>;
            const activeCount = <?php echo count(array_filter($modelos, fn($m) => $m['activo'])); ?>;
            const inactiveCount = <?php echo count(array_filter($modelos, fn($m) => !$m['activo'])); ?>;
            const noImageCount = <?php echo count(array_filter($modelos, fn($m) => empty($m['imagen_portada']))); ?>;
            
            // Animate counter updates
            const counters = document.querySelectorAll('.counter-number');
            counters[0].textContent = totalCount;
            counters[1].textContent = activeCount;
            counters[2].textContent = inactiveCount;
            counters[3].textContent = noImageCount;
        }
        
        // Update stats every 30 seconds (optional)
        setInterval(updateStats, 30000);
        
        // Export functionality
        function exportToCSV() {
            const dataTable = $('#modelosTable').DataTable();
            const data = dataTable.rows().data().toArray();
            
            let csv = 'ID,Nombre,Metros Cubiertos,Metros Galería,Sistema,Precio Desde,Estado\n';
            
            data.forEach(row => {
                const nombre = row[2].replace(/<[^>]*>/g, ''); // Remove HTML tags
                const estado = row[7].includes('Activo') ? 'Activo' : 'Inactivo';
                csv += `"${row[0]}","${nombre}","${row[3]}","${row[4]}","${row[5]}","${row[6]}","${estado}"\n`;
            });
            
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.setAttribute('hidden', '');
            a.setAttribute('href', url);
            a.setAttribute('download', 'modelos_casas.csv');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
</body>
</html>