<?php

namespace Views;

use Classe\AnnonceDetail;
use Views\LoginModalHtml;

class AnnonceDetailHtml
{
    /**
     * Affiche les détails complets d'une annonce
     */
    public static function displayAnnonceDetail($annonceObj)
    {
        $annonce = $annonceObj->getAnnonce();
        $images = $annonceObj->getImages();
        $caracteristiques = $annonceObj->getCaracteristiques();
        $similaires = $annonceObj->getAnnoncesSimilaires();

        if (empty($annonce)) {
            self::displayNotFound();
            return;
        }

        $transaction_badge = $annonce['type_transaction_id'] == 1 ?
            '<span class="badge bg-success"><i class="fas fa-tag me-1"></i>À vendre</span>' :
            '<span class="badge bg-info"><i class="fas fa-key me-1"></i>À louer</span>';

?>
        <!-- Contenu principal -->
        <div class="container annonce-detail-page mb-5">
            <div class="row">
                <!-- Colonne principale (gauche) -->
                <div class="col-lg-9 property-detail-main">
                    <!-- Bouton retour -->
                    <a href="javascript:history.back()" class="btn btn-outline-primary mb-3">
                        <i class="fas fa-arrow-left me-2"></i>Retour aux résultats
                    </a>

                    <!-- Conteneur galerie + onglets -->
                    <div class="property-content-wrapper border rounded-3 mb-4">
                        <!-- Galerie d'images -->
                        <div class="annonce-gallery mb-4">
                            <div id="mainImageCarousel" class="carousel slide" data-bs-ride="carousel">
                                <div class="carousel-indicators">
                                    <?php foreach ($images as $index => $image): ?>
                                        <button type="button" data-bs-target="#mainImageCarousel"
                                            data-bs-slide-to="<?= $index ?>"
                                            class="<?= $index === 0 ? 'active' : '' ?>"
                                            aria-current="<?= $index === 0 ? 'true' : 'false' ?>"
                                            aria-label="Slide <?= $index + 1 ?>"></button>
                                    <?php endforeach; ?>
                                </div>
                                <div class="carousel-inner">
                                    <?php foreach ($images as $index => $image): ?>
                                        <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>">
                                            <img src="<?= $image ?>" class="d-block w-100" alt="Image <?= $index + 1 ?>">
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button class="carousel-control-prev" type="button" data-bs-target="#mainImageCarousel" data-bs-slide="prev">
                                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                    <span class="visually-hidden">Précédent</span>
                                </button>
                                <button class="carousel-control-next" type="button" data-bs-target="#mainImageCarousel" data-bs-slide="next">
                                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                    <span class="visually-hidden">Suivant</span>
                                </button>
                            </div>

                            <!-- Navigation galerie avec compteur et description -->
                            <div class="gallery-navigation">
                                <div class="d-flex align-items-center justify-content-between">
                                    <button class="btn btn-link text-decoration-none p-0" type="button" data-bs-target="#mainImageCarousel" data-bs-slide="prev">
                                        <i class="fas fa-arrow-left me-2"></i>Retour
                                    </button>

                                    <div class="gallery-info text-center flex-grow-1">
                                        <span class="gallery-counter fw-bold">1/<?= count($images) ?></span>
                                        <span class="gallery-description ms-3 text-muted">Photo de la propriété</span>
                                    </div>

                                    <button class="btn btn-link text-decoration-none p-0" type="button" data-bs-target="#mainImageCarousel" data-bs-slide="next">
                                        Suivant<i class="fas fa-arrow-right ms-2"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Onglets Description / Carte -->
                        <div class="property-detail-tabs mb-4">
                            <ul class="nav nav-tabs">
                                <li class="nav-item">
                                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#description-panel">
                                        <i class="fas fa-file-alt me-2"></i>Description
                                    </button>
                                </li>
                                <li class="nav-item">
                                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#map-panel">
                                        <i class="fas fa-map-marked-alt me-2"></i>Carte
                                    </button>
                                </li>
                            </ul>

                            <div class="tab-content">
                                <!-- Onglet Description -->
                                <div class="tab-pane fade show active" id="description-panel">
                                    <div class="p-4">
                                        <!-- Caractéristiques principales -->
                                        <div class="annonce-features mb-4 border rounded-3 p-3">
                                            <div class="d-flex flex-wrap gap-3">
                                                <?php if ($annonce['surface']): ?>
                                                    <div class="flex-fill text-center">
                                                        <i class="fas fa-ruler-combined text-primary mb-2 d-block"></i>
                                                        <div class="feature-value"><?= number_format($annonce['surface'], 0) ?> m²</div>
                                                        <div class="feature-label">Surface</div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if ($annonce['nb_pieces']): ?>
                                                    <div class="flex-fill text-center">
                                                        <i class="fas fa-door-open text-primary mb-2 d-block"></i>
                                                        <div class="feature-value"><?= $annonce['nb_pieces'] ?></div>
                                                        <div class="feature-label">Pièces</div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if ($annonce['nb_chambres']): ?>
                                                    <div class="flex-fill text-center">
                                                        <i class="fas fa-bed text-primary mb-2 d-block"></i>
                                                        <div class="feature-value"><?= $annonce['nb_chambres'] ?></div>
                                                        <div class="feature-label">Chambres</div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if ($annonce['nb_salles_bain']): ?>
                                                    <div class="flex-fill text-center">
                                                        <i class="fas fa-bath text-primary mb-2 d-block"></i>
                                                        <div class="feature-value"><?= $annonce['nb_salles_bain'] ?></div>
                                                        <div class="feature-label">Salles de bain</div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (isset($annonce['surface_terrain']) && $annonce['surface_terrain']): ?>
                                                    <div class="flex-fill text-center">
                                                        <i class="fas fa-mountain text-primary mb-2 d-block"></i>
                                                        <div class="feature-value"><?= number_format($annonce['surface_terrain'], 0) ?> m²</div>
                                                        <div class="feature-label">Terrain</div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <!-- Description -->
                                        <div class="annonce-description mb-4 border rounded-3 p-3">
                                            <h3 class="section-title mb-3">
                                                <i class="fas fa-file-alt text-primary me-2"></i>Description
                                            </h3>
                                            <div class="description-content">
                                                <?= nl2br(htmlspecialchars($annonce['description'])) ?>
                                            </div>
                                        </div>

                                        <!-- Caractéristiques -->
                                        <?php if (!empty($caracteristiques)): ?>
                                            <div class="annonce-caracteristiques border rounded-3 p-3">
                                                <h3 class="section-title mb-3">
                                                    <i class="fas fa-list-check text-primary me-2"></i>Caractéristiques
                                                </h3>
                                                <div class="caracteristiques-grid">
                                                    <?php foreach ($caracteristiques as $key => $value): ?>
                                                        <?php if ($value === true || $value === 'true' || $value === 1): ?>
                                                            <div class="caracteristique-item">
                                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                                <?= ucfirst(str_replace('_', ' ', $key)) ?>
                                                            </div>
                                                        <?php elseif ($value !== false && $value !== 'false' && $value !== 0): ?>
                                                            <div class="caracteristique-item">
                                                                <i class="fas fa-info-circle text-primary me-2"></i>
                                                                <strong><?= ucfirst(str_replace('_', ' ', $key)) ?>:</strong> <?= htmlspecialchars($value) ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <!-- Onglet Carte -->
                                <div class="tab-pane fade" id="map-panel">
                                    <?php if ($annonce['latitude'] && $annonce['longitude']): ?>
                                        <div class="p-4">
                                            <div class="annonce-localisation">
                                                <h3 class="section-title mb-3">Localisation</h3>
                                                <p class="text-muted mb-3">
                                                    <i class="fas fa-map-marker-alt me-2"></i>
                                                    <?= htmlspecialchars($annonce['adresse']) ?>,
                                                    <?= htmlspecialchars($annonce['ville']) ?>,
                                                    <?= htmlspecialchars($annonce['pays']) ?>
                                                </p>
                                                <div class="map-container rounded-3 overflow-hidden">
                                                    <iframe
                                                        width="100%"
                                                        height="500"
                                                        frameborder="0"
                                                        scrolling="no"
                                                        marginheight="0"
                                                        marginwidth="0"
                                                        src="https://www.openstreetmap.org/export/embed.html?bbox=<?= $annonce['longitude'] - 0.01 ?>%2C<?= $annonce['latitude'] - 0.01 ?>%2C<?= $annonce['longitude'] + 0.01 ?>%2C<?= $annonce['latitude'] + 0.01 ?>&amp;layer=mapnik&amp;marker=<?= $annonce['latitude'] ?>%2C<?= $annonce['longitude'] ?>">
                                                    </iframe>
                                                </div>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="p-4 text-center text-muted">
                                            <i class="fas fa-map-marked-alt fa-3x mb-3"></i>
                                            <p>Localisation non disponible pour cette annonce</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Fin conteneur galerie + onglets -->
                </div>

                <!-- Sidebar (droite) -->
                <div class="col-lg-3 property-detail-sidebar">
                    <!-- Titre et infos principales -->
                    <div class="annonce-header mb-4 border rounded-3 p-3">
                        <!-- Prix -->
                        <div class="annonce-price-simple mb-3">
                            <h2 class="price-amount"><?= AnnonceDetail::formatPrice($annonce['prix']) ?></h2>
                            <?php if ($annonce['type_transaction_id'] == 2): ?>
                                <span class="price-period">/ mois</span>
                            <?php endif; ?>
                        </div>

                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <h1 class="annonce-title mb-2"><?= htmlspecialchars($annonce['titre']) ?></h1>
                                <p class="text-muted mb-0">
                                    <i class="fas fa-map-marker-alt me-2"></i>
                                    <?= htmlspecialchars($annonce['adresse']) ?>,
                                    <?= htmlspecialchars($annonce['ville']) ?>,
                                    <?= htmlspecialchars($annonce['pays']) ?>
                                </p>
                            </div>
                            <button class="btn btn-outline-danger btn-favorite" data-annonce-id="<?= $annonce['id'] ?>">
                                <i class="far fa-heart fa-lg"></i>
                            </button>
                        </div>

                        <div class="d-flex flex-wrap align-items-center gap-3">
                            <?= $transaction_badge ?>
                            <span class="badge bg-primary"><?= htmlspecialchars($annonce['categorie_nom']) ?></span>
                            <span class="text-muted">
                                <i class="fas fa-eye me-1"></i><?= $annonce['vues'] ?> vues
                            </span>
                            <span class="text-muted">
                                <i class="fas fa-clock me-1"></i>
                                Publié le <?= date('d/m/Y', strtotime($annonce['date_publication'])) ?>
                            </span>
                        </div>
                    </div>

                    <!-- Formulaire de contact -->
                    <div class="contact-card">
                        <h4 class="mb-4">
                            <i class="fas fa-envelope me-2"></i>Contacter le vendeur
                        </h4>
                        <form id="contact-form">
                            <input type="hidden" name="annonce_id" value="<?= $annonce['id'] ?>">

                            <div class="mb-3">
                                <label class="form-label">Votre nom</label>
                                <input type="text" class="form-control" name="nom" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Votre email</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Votre téléphone</label>
                                <input type="tel" class="form-control" name="telephone" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Votre message</label>
                                <textarea class="form-control" name="message" rows="4" required>Bonjour, je suis intéressé(e) par cette annonce. Pouvez-vous me contacter ?</textarea>
                            </div>

                            <button type="submit" class="btn btn-primary w-100 btn-lg">
                                <i class="fas fa-paper-plane me-2"></i>Envoyer le message
                            </button>
                        </form>

                        <div class="mt-3 text-center">
                            <button class="btn btn-outline-primary w-100">
                                <i class="fas fa-phone me-2"></i>Afficher le téléphone
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Annonces similaires -->
            <?php if (!empty($similaires)): ?>
                <div class="row mt-5">
                    <div class="col-12 similar-properties-section">
                        <h3 class="section-title mb-4">Annonces similaires</h3>
                        <div class="row g-4">
                            <?php foreach ($similaires as $sim): ?>
                                <div class="col-md-4">
                                    <?= self::generateSimilarCard($sim) ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <?php
        // Afficher le modal de connexion et son script
        LoginModalHtml::renderLoginModal();
        LoginModalHtml::renderLoginModalScript('.btn-favorite');
        ?>
    <?php
    }

    /**
     * Génère une carte pour une annonce similaire
     */
    private static function generateSimilarCard($annonce)
    {
        $image = 'https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=600&q=80';
        $badge_class = $annonce['type_transaction_id'] == 1 ? 'badge-sale' : 'badge-rent';
        $badge_text = $annonce['type_transaction_id'] == 1 ? 'Vente' : 'Location';

        ob_start();
    ?>
        <a href="index.php?page=annonce&id=<?= $annonce['id'] ?>" class="text-decoration-none">
            <div class="property-card h-100">
                <div class="property-image">
                    <img src="<?= $image ?>" alt="<?= htmlspecialchars($annonce['titre']) ?>">
                    <span class="badge <?= $badge_class ?>"><?= $badge_text ?></span>
                </div>
                <div class="property-content">
                    <h5 class="property-title"><?= htmlspecialchars($annonce['titre']) ?></h5>
                    <p class="property-location">
                        <i class="fas fa-map-marker-alt me-1"></i>
                        <?= htmlspecialchars($annonce['ville']) ?>
                    </p>
                    <div class="property-price"><?= AnnonceDetail::formatPrice($annonce['prix']) ?></div>
                    <div class="property-features-small">
                        <?php if ($annonce['surface']): ?>
                            <span><i class="fas fa-ruler-combined me-1"></i><?= $annonce['surface'] ?> m²</span>
                        <?php endif; ?>
                        <?php if ($annonce['nb_pieces']): ?>
                            <span><i class="fas fa-door-open me-1"></i><?= $annonce['nb_pieces'] ?> pièces</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </a>
    <?php
        return ob_get_clean();
    }

    /**
     * Affiche une page 404 si l'annonce n'existe pas
     */
    private static function displayNotFound()
    {
    ?>
        <div class="container my-5">
            <div class="text-center py-5">
                <i class="fas fa-home fa-5x text-muted mb-4"></i>
                <h1 class="display-4">Annonce introuvable</h1>
                <p class="lead text-muted mb-4">
                    Désolé, cette annonce n'existe pas ou n'est plus disponible.
                </p>
                <a href="index.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-arrow-left me-2"></i>Retour à l'accueil
                </a>
            </div>
        </div>
<?php
    }
}
