<?php
namespace Views;

class SearchBarCompact
{
    /**
     * Affiche une barre de recherche compacte pour les pages internes
     */
    public static function display($currentParams = [], $showHeader = false, $searchTitle = '', $totalResults = 0, $activeFilters = [])
    {
        ?>
        <!-- Barre de recherche compacte -->
        <div class="search-bar-compact">
            <div class="container container-bordered">
                <form id="compact-search-form" class="compact-search-form" method="GET" action="index.php">
                    <input type="hidden" name="page" value="search">
                    
                    <div class="row g-2 align-items-center">
                        <!-- Ville -->
                        <div class="col-md-3 col-sm-6">
                            <div class="input-group">
                                <span class="input-group-text bg-white">
                                    <i class="fas fa-map-marker-alt text-primary"></i>
                                </span>
                                <input 
                                    type="text" 
                                    class="form-control" 
                                    id="compact-city-search"
                                    name="cities" 
                                    placeholder="Ville, commune..."
                                    value=""
                                >
                            </div>
                        </div>
                        
                        <!-- Type de transaction -->
                        <div class="col-md-2 col-sm-6">
                            <select class="form-select" name="transaction" id="compact-transaction">
                                <option value="">Transaction</option>
                                <option value="1" <?= isset($currentParams['transaction']) && $currentParams['transaction'] == '1' ? 'selected' : '' ?>>
                                    Vente
                                </option>
                                <option value="2" <?= isset($currentParams['transaction']) && $currentParams['transaction'] == '2' ? 'selected' : '' ?>>
                                    Location
                                </option>
                            </select>
                        </div>
                        
                        <!-- Type de propriété -->
                        <div class="col-md-3 col-sm-6">
                            <select class="form-select" name="property" id="compact-property">
                                <option value="">Type de bien</option>
                                <option value="1" <?= isset($currentParams['property']) && $currentParams['property'] == '1' ? 'selected' : '' ?>>
                                    Appartement
                                </option>
                                <option value="2" <?= isset($currentParams['property']) && $currentParams['property'] == '2' ? 'selected' : '' ?>>
                                    Maison/Villa
                                </option>
                                <option value="3" <?= isset($currentParams['property']) && $currentParams['property'] == '3' ? 'selected' : '' ?>>
                                    Villa de luxe
                                </option>
                                <option value="4" <?= isset($currentParams['property']) && $currentParams['property'] == '4' ? 'selected' : '' ?>>
                                    Terrain
                                </option>
                                <option value="5" <?= isset($currentParams['property']) && $currentParams['property'] == '5' ? 'selected' : '' ?>>
                                    Commerce/Bureau
                                </option>
                            </select>
                        </div>
                        
                        <!-- Prix -->
                        <div class="col-md-2 col-sm-6">
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary dropdown-toggle w-100" type="button" data-bs-toggle="dropdown">
                                    <i class="fas fa-tag me-1"></i>Budget
                                </button>
                                <div class="dropdown-menu p-3" style="min-width: 300px;" onclick="event.stopPropagation();">
                                    <div class="mb-2">
                                        <label class="form-label small">Prix min (DA)</label>
                                        <input type="number" class="form-control form-control-sm" name="price_min" 
                                               placeholder="0" min="0" step="100000"
                                               value="<?= isset($currentParams['price_min']) ? $currentParams['price_min'] : '' ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label small">Prix max (DA)</label>
                                        <input type="number" class="form-control form-control-sm" name="price_max" 
                                               placeholder="50000000" min="0" step="100000"
                                               value="<?= isset($currentParams['price_max']) ? $currentParams['price_max'] : '' ?>">
                                    </div>
                                    <div class="d-flex gap-2 flex-wrap">
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="setPriceRange(0, 5000000)">
                                            &lt; 5M
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="setPriceRange(5000000, 10000000)">
                                            5M-10M
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="setPriceRange(10000000, 20000000)">
                                            10M-20M
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="setPriceRange(20000000, 50000000)">
                                            &gt; 20M
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Bouton rechercher -->
                        <div class="col-md-2 col-sm-12">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search me-1"></i>
                                <span class="d-none d-md-inline">Rechercher</span>
                                <span class="d-md-none">Rechercher</span>
                            </button>
                        </div>
                    </div>
                </form>
            <?php if (!empty($activeFilters)): ?>
            <div class="active-filters-container">
                <div class="active-filters">
                    <span class="filters-label">Filtres actifs :</span>
                    <div class="filters-list">
                        <?php foreach ($activeFilters as $filter): ?>
                        <span class="filter-tag" data-filter-type="<?= $filter['type'] ?>" data-filter-value="<?= htmlspecialchars($filter['value'] ?? $filter['label']) ?>">
                            <?= htmlspecialchars($filter['label']) ?>
                            <?php if ($filter['removable']): ?>
                            <button type="button" class="filter-remove" title="Retirer ce filtre">
                                <i class="fas fa-times"></i>
                            </button>
                            <?php endif; ?>
                        </span>
                        <?php endforeach; ?>
                        <button type="button" class="clear-all-filters" title="Effacer tous les filtres">
                            <i class="fas fa-times-circle"></i> Tout effacer
                        </button>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            </div>
        </div>

        <style>
        .search-bar-compact {
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            padding: 20px 30px 20px;
            max-width: 1600px;
            margin: 0 auto;
        }
        
        .compact-search-form .form-control,
        .compact-search-form .form-select,
        .compact-search-form .btn {
            height: 42px;
            border-radius: 0.5rem;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            font-size: 0.95rem;
        }
        
        .compact-search-form .form-control:focus,
        .compact-search-form .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.15);
        }
        
        .compact-search-form .input-group-text {
            height: 42px;
            border: 2px solid #e9ecef;
            border-right: none;
            border-radius: 0.5rem 0 0 0.5rem;
            display: flex;
            align-items: center;
        }
        
        .compact-search-form .input-group .form-control {
            border-left: none;
            border-radius: 0 0.5rem 0.5rem 0;
        }
        
        .compact-search-form .input-group:focus-within .input-group-text {
            border-color: #667eea;
        }
        
        .compact-search-form .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            font-weight: 600;
            height: 42px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .compact-search-form .btn-outline-secondary {
            height: 42px;
            border: 2px solid #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .compact-search-form .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        .compact-search-form .btn-refresh {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
        }
        
        .compact-search-form .btn-refresh:hover {
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3) !important;
        }
        
        /* Conteneur des filtres actifs */
        .active-filters-container {
            padding: 15px 15px;
        }
        
        /* Styles du header de recherche intégré */
        .search-header-content {
            color: #2c3e50;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            flex-wrap: nowrap;
        }
        
        .search-title-section {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: nowrap;
            gap: 15px;
            flex-shrink: 0;
        }
        
        .search-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin: 0;
            color: #2c3e50;
        }
        
        .search-count {
            margin: 0;
            font-size: 1rem;
            color: #667eea;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .search-count i {
            color: #667eea;
        }
        
        .active-filters {
            margin-top: 0;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            flex: 1;
        }
        
        .filters-label {
            font-weight: 600;
            color: #495057;
        }
        
        .filters-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }
        
        .filter-tag {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255, 255, 255, 0.95);
            color: #333;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            transition: opacity 0.3s ease, transform 0.3s ease;
        }
        
        .filter-remove {
            background: transparent;
            border: none;
            color: #dc3545;
            cursor: pointer;
            padding: 0;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.2s;
        }
        
        .filter-remove:hover {
            background: #dc3545;
            color: white;
            transform: rotate(90deg);
        }
        
        .clear-all-filters {
            background: rgba(220, 53, 69, 0.9);
            border: none;
            color: white;
            padding: 6px 15px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: all 0.3s;
        }
        
        .clear-all-filters:hover {
            background: #dc3545;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
        }
        
        @media (max-width: 768px) {
            .search-title {
                font-size: 1.25rem;
            }
            
            .search-title-section {
                flex-direction: column;
                align-items: flex-start;
            }
        }
        </style>

        <script>
        function setPriceRange(min, max) {
            document.querySelector('input[name="price_min"]').value = min;
            document.querySelector('input[name="price_max"]').value = max;
        }
        
        // Autocomplete pour les villes (simple version)
        document.getElementById('compact-city-search')?.addEventListener('input', function(e) {
            // TODO: Implémenter l'autocomplete si nécessaire
        });
        
        // Gestion des filtres actifs
        document.addEventListener('DOMContentLoaded', function() {
            const searchForm = document.getElementById('compact-search-form');
            const submitBtn = searchForm?.querySelector('button[type="submit"]');
            let filtersChanged = false;
            
            // Vérifier si des filtres sont déjà actifs
            const hasActiveFilters = document.querySelector('.active-filters-container') !== null;
            
            // Fonction pour changer le bouton en "Actualiser"
            function changeToRefreshButton() {
                if (submitBtn && !filtersChanged) {
                    filtersChanged = true;
                    submitBtn.innerHTML = '<i class="fas fa-sync-alt me-1"></i><span class="d-none d-md-inline">Actualiser</span><span class="d-md-none">Actualiser</span>';
                    submitBtn.classList.add('btn-refresh');
                }
            }
            
            // Si des filtres sont actifs, empêcher la soumission normale du formulaire
            searchForm?.addEventListener('submit', function(e) {
                if (filtersChanged || hasActiveFilters) {
                    e.preventDefault();
                    window.location.href = 'index.php?page=search';
                }
            });
            
            // Gestion du clic sur le bouton de suppression d'un filtre
            document.querySelectorAll('.filter-remove').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation(); // Empêcher la propagation de l'événement
                    e.stopImmediatePropagation(); // Bloquer tous les autres écouteurs
                    
                    const filterTag = this.closest('.filter-tag');
                    const filterType = filterTag?.getAttribute('data-filter-type');
                    const filterValue = filterTag?.getAttribute('data-filter-value');
                    
                    // Changer immédiatement le bouton en "Actualiser"
                    changeToRefreshButton();
                    
                    // Animation de disparition du tag
                    filterTag.style.opacity = '0';
                    setTimeout(() => {
                        filterTag.remove();
                        
                        // Vérifier s'il reste des filtres
                        const remainingFilters = document.querySelectorAll('.filter-tag').length;
                        if (remainingFilters === 0) {
                            // Si plus de filtres, cacher le conteneur
                            const activeFiltersContainer = document.querySelector('.active-filters-container');
                            if (activeFiltersContainer) {
                                activeFiltersContainer.style.display = 'none';
                            }
                        }
                    }, 300);
                    
                    // Envoyer une requête au serveur pour mettre à jour la session
                    const formData = new FormData();
                    formData.append('remove_filter', '1');
                    formData.append('filter_type', filterType);
                    formData.append('filter_value', filterValue);
                    
                    fetch('index.php?page=search', {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Filtre supprimé avec succès', data);
                        // NE PAS recharger la page - juste mettre à jour la session
                    })
                    .catch(error => {
                        console.error('Erreur lors de la suppression du filtre:', error);
                    });
                    
                    // Important : ne rien faire d'autre - ne pas recharger
                    return false;
                });
            });
            
            // Gestion du bouton "Tout effacer"
            document.querySelector('.clear-all-filters')?.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Effacer tous les champs du formulaire
                document.querySelector('input[name="cities"]').value = '';
                document.querySelector('select[name="transaction"]').value = '';
                document.querySelector('select[name="property"]').value = '';
                document.querySelector('input[name="price_min"]').value = '';
                document.querySelector('input[name="price_max"]').value = '';
                
                // Supprimer la session côté serveur et recharger
                fetch('index.php?page=search&clear_filters=1')
                    .then(() => {
                        window.location.href = 'index.php?page=search';
                    })
                    .catch(() => {
                        // Fallback: recharger simplement la page
                        window.location.href = 'index.php?page=search';
                    });
            });
        });
        </script>
        <?php
    }
}
