<?php
namespace Classe;

use mysqlDB;

class PublicSearch
{
    private $conn;
    private $searchParams = [];
    private $results = [];
    private $totalResults = 0;
    private $currentPage = 1;
    private $resultsPerPage = 15;

    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    /**
     * Effectuer la recherche avec les paramètres fournis
     */
    public function search($params)
    {
        $this->searchParams = $params;
        $showQuery = false;
        // Pagination
        $this->currentPage = isset($params['page']) ? max(1, intval($params['page'])) : 1;
        $offset = ($this->currentPage - 1) * $this->resultsPerPage;

        // Construction de la requête SQL
        $sql = "SELECT a.*, 
                       u.prenom, u.nom as user_nom, u.telephone, u.email,
                       cb.nom as categorie_nom,
                       tt.nom as type_transaction,
                       (SELECT chemin_fichier FROM photos_annonces WHERE annonce_id = a.id AND principale = 1 LIMIT 1) as photo_principale,
                       (SELECT COUNT(*) FROM photos_annonces WHERE annonce_id = a.id) as nb_photos
                FROM annonces a
                LEFT JOIN users u ON a.user_id = u.id
                LEFT JOIN categories_biens cb ON a.categorie_id = cb.id
                LEFT JOIN types_transaction tt ON a.type_transaction_id = tt.id
                WHERE a.statut = 'publiee' AND a.actif = 1";

        $sqlParams = [];

        // Filtrer par villes (multiples villes possibles)
        if (!empty($params['city_ids']) && is_array($params['city_ids'])) {
            $cityIds = array_map('intval', $params['city_ids']);
            
            // Récupérer les noms des villes depuis la table localites_algerie
            $cityIdsStr = implode(',', $cityIds);
            $citiesQuery = "SELECT nom FROM localites_algerie WHERE id IN ($cityIdsStr)";
            $this->conn->exec($citiesQuery);
            $cityNames = [];
            if (!empty($this->conn->data)) {
                foreach ($this->conn->data as $row) {
                    $cityNames[] = $row['nom'];
                }
            }
            
            if (!empty($cityNames)) {
                $escapedNames = array_map(function($name) {
                    return "'" . mysqli_real_escape_string($this->conn->link_id, $name) . "'";
                }, $cityNames);
                $cityList = implode(',', $escapedNames);
                
                $sql .= " AND (a.ville IN ($cityList)";
                $sql .= " OR a.region IN ($cityList)";
                $sql .= " OR a.departement IN ($cityList))";
            }
        }

        // Filtrer par type de transaction
        if (!empty($params['transaction'])) {
            $transactionMap = [
                'vente' => 1,
                'location' => 2
            ];
            if (isset($transactionMap[$params['transaction']])) {
                $sql .= " AND a.type_transaction_id = " . intval($transactionMap[$params['transaction']]);
            }
        }

        // Filtrer par type de propriété
        if (!empty($params['property'])) {
            $propertyMap = [
                'appartement' => 1,
                'maison' => 2,
                'villa' => 3,
                'terrain' => 4,
                'local_commercial' => 5,
                'bureau' => 6
            ];
            if (isset($propertyMap[$params['property']])) {
                $sql .= " AND a.categorie_id = " . intval($propertyMap[$params['property']]);
            }
        }

        // Filtrer par prix
        if (!empty($params['price_min']) && $params['price_min'] > 0) {
            $sql .= " AND a.prix >= " . intval($params['price_min']);
        }

        if (!empty($params['price_max']) && $params['price_max'] > 0) {
            $sql .= " AND a.prix <= " . intval($params['price_max']);
        }

        // Compter le nombre total de résultats
        $countSql = "SELECT COUNT(*) as total FROM (" . $sql . ") as count_query";
        $this->conn->exec($countSql);
        $this->totalResults = !empty($this->conn->data) ? $this->conn->data[0]['total'] : 0;

        // Ajouter l'ordre et la pagination
        $sql .= " ORDER BY a.mise_en_avant DESC, a.date_publication DESC, a.date_creation DESC";
        $sql .= " LIMIT " . intval($this->resultsPerPage) . " OFFSET " . intval($offset);

        if ($showQuery) {
        // DEBUG: Afficher la requête SQL exécutée
        echo '<div style="background: #f8f9fa; border: 2px solid #007bff; padding: 20px; margin: 20px; border-radius: 8px; font-family: monospace; overflow-x: auto;">';
        echo '<h3 style="color: #007bff; margin-top: 0;">🔍 Requête SQL Exécutée (Annonces par villes)</h3>';
        echo '<pre style="background: white; padding: 15px; border-radius: 4px; overflow-x: auto;">' . htmlspecialchars($sql) . '</pre>';
        echo '<h4 style="color: #28a745;">📊 Paramètres de recherche :</h4>';
        echo '<pre style="background: white; padding: 15px; border-radius: 4px;">' . print_r($params, true) . '</pre>';
        echo '</div>';
        }
        // Exécuter la requête
        try {
            $this->conn->exec($sql);
            $this->results = !empty($this->conn->data) ? $this->conn->data : [];
        } catch (\Exception $e) {
            error_log("Erreur recherche annonces: " . $e->getMessage());
            $this->results = [];
        }

        return $this->results;
    }

    /**
     * Obtenir les résultats de recherche
     */
    public function getResults()
    {
        return $this->results;
    }

    /**
     * Obtenir le nombre total de résultats
     */
    public function getTotalResults()
    {
        return $this->totalResults;
    }

    /**
     * Obtenir le nombre total de pages
     */
    public function getTotalPages()
    {
        return ceil($this->totalResults / $this->resultsPerPage);
    }

    /**
     * Obtenir la page courante
     */
    public function getCurrentPage()
    {
        return $this->currentPage;
    }

    /**
     * Obtenir les paramètres de recherche
     */
    public function getSearchParams()
    {
        return $this->searchParams;
    }

    /**
     * Générer le titre de la page selon les critères
     */
    public function getSearchTitle()
    {
        $parts = [];

        // Type de propriété
        if (!empty($this->searchParams['property'])) {
            $propertyNames = [
                'appartement' => 'Appartements',
                'maison' => 'Maisons',
                'villa' => 'Villas',
                'terrain' => 'Terrains',
                'local_commercial' => 'Locaux commerciaux',
                'bureau' => 'Bureaux'
            ];
            $parts[] = $propertyNames[$this->searchParams['property']] ?? 'Biens';
        } else {
            $parts[] = 'Biens immobiliers';
        }

        // Type de transaction
        if (!empty($this->searchParams['transaction'])) {
            $parts[] = $this->searchParams['transaction'] === 'vente' ? 'à vendre' : 'en location';
        }

        // Villes
        if (!empty($this->searchParams['cities'])) {
            $cities = explode(',', $this->searchParams['cities']);
            if (count($cities) === 1) {
                $parts[] = 'à ' . $cities[0];
            } else {
                $parts[] = 'dans ' . count($cities) . ' villes';
            }
        }

        return implode(' ', $parts);
    }

    /**
     * Obtenir un résumé des filtres actifs
     */
    public function getActiveFilters()
    {
        $filters = [];

        if (!empty($this->searchParams['cities'])) {
            $cities = explode(',', $this->searchParams['cities']);
            foreach ($cities as $city) {
                $filters[] = [
                    'type' => 'city',
                    'label' => trim($city),
                    'value' => trim($city),
                    'removable' => true
                ];
            }
        }

        if (!empty($this->searchParams['transaction'])) {
            $filters[] = [
                'type' => 'transaction',
                'label' => $this->searchParams['transaction'] === 'vente' ? 'Vente' : 'Location',
                'value' => $this->searchParams['transaction'],
                'removable' => true
            ];
        }

        if (!empty($this->searchParams['property'])) {
            $propertyNames = [
                'appartement' => 'Appartement',
                'maison' => 'Maison',
                'villa' => 'Villa',
                'terrain' => 'Terrain',
                'local_commercial' => 'Local commercial',
                'bureau' => 'Bureau'
            ];
            $filters[] = [
                'type' => 'property',
                'label' => $propertyNames[$this->searchParams['property']] ?? $this->searchParams['property'],
                'value' => $this->searchParams['property'],
                'removable' => true
            ];
        }

        if (!empty($this->searchParams['price_min']) || !empty($this->searchParams['price_max'])) {
            $priceLabel = '';
            if (!empty($this->searchParams['price_min']) && !empty($this->searchParams['price_max'])) {
                $priceLabel = $this->formatPrice($this->searchParams['price_min']) . ' - ' . $this->formatPrice($this->searchParams['price_max']);
            } elseif (!empty($this->searchParams['price_min'])) {
                $priceLabel = 'À partir de ' . $this->formatPrice($this->searchParams['price_min']);
            } else {
                $priceLabel = 'Jusqu\'à ' . $this->formatPrice($this->searchParams['price_max']);
            }
            
            $filters[] = [
                'type' => 'price',
                'label' => $priceLabel,
                'value' => 'price_range',
                'removable' => true
            ];
        }

        return $filters;
    }

    /**
     * Formater le prix
     */
    private function formatPrice($price)
    {
        if ($price >= 1000000) {
            return number_format($price / 1000000, 1, ',', ' ') . ' M DA';
        } elseif ($price >= 1000) {
            return number_format($price / 1000, 0, ',', ' ') . ' K DA';
        }
        return number_format($price, 0, ',', ' ') . ' DA';
    }
}
