<?php
// /ad_detail.php

// First, process the ad data and set Open Graph variables
require_once 'config.php';
require_once 'includes/functions.php';

// --- Initialize variables ---
$ad = null;
$ad_images = [];
$ad_features = [];
$is_favorited = false;
$is_own_ad = false;
$error_message = null; // NEW: Track errors gracefully

// --- Get Ad ID and Fetch Data ---
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    redirect_to('/listing.php');
}
$ad_id = (int)$_GET['id'];

// Only proceed with database operations if connection exists
if (isset($conn) && $conn) {
    // Increment the view count for this ad (silently fail if this errors)
    $conn->query("UPDATE ads SET views = views + 1 WHERE id = $ad_id");

    // Fetch all ad details with joins, including more seller info
    $stmt = $conn->prepare("
        SELECT
            a.*,
            u.username as seller_username,
            u.profile_image as seller_avatar,
            u.created_at as seller_join_date,
            u.is_verified as seller_is_verified,
            u.location as seller_location,
            u.shop_address as seller_shop_address,
            c.name as category_name,
            c.slug as category_slug
        FROM ads a
        JOIN users u ON a.user_id = u.id
        JOIN categories c ON a.category_id = c.id
        WHERE a.id = ? AND a.status = 'active'
    ");

    if ($stmt === false) {
        // FIX: Don't die(), set error and continue to render page with header/footer
        $error_message = 'Database query failed: ' . htmlspecialchars($conn->error);
        $page_title = "System Error";
    } else {
        $stmt->bind_param("i", $ad_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        if ($result && $result->num_rows > 0) {
            $ad = $result->fetch_assoc();
            $page_title = escape($ad['title']);
            
            // --- Set Open Graph meta tags for this specific ad ---
            $og_title = escape($ad['title']);
            $og_description = substr(strip_tags($ad['description']), 0, 200) . '...';
            $og_type = 'product';
            $og_url = SITE_URL . '/ad_detail.php?id=' . $ad_id;
            
            // Get the first image for the Open Graph image (absolute URL required for OG tags)
            $images_result = $conn->query("SELECT image_url FROM ad_images WHERE ad_id = $ad_id ORDER BY is_thumbnail DESC, id ASC LIMIT 1");
            if ($images_result && $images_result->num_rows > 0) {
                $image = $images_result->fetch_assoc();
                // FIX: Trim leading slash to prevent double slashes in URL
                $og_image = SITE_URL . '/' . ltrim($image['image_url'], '/');
            } else {
                $og_image = SITE_URL . '/assets/images/placeholder.png';
            }

            // --- Breadcrumb ---
            $breadcrumbs = [
                ['name' => 'Home', 'url' => '/'],
                ['name' => 'Listing', 'url' => '/listing.php'],
                ['name' => $ad['category_name'], 'url' => '/listing.php?category=' . urlencode($ad['category_slug'])],
                ['name' => escape($ad['title']), 'url' => '']
            ];

            // Fetch Images
            $images_result = $conn->query("SELECT id, image_url FROM ad_images WHERE ad_id = $ad_id ORDER BY is_thumbnail DESC, id ASC");
            if ($images_result) {
                $ad_images = $images_result->fetch_all(MYSQLI_ASSOC);
            }

            // Fetch Features
            $features_result = $conn->query("SELECT id, feature_name, feature_value FROM ad_features WHERE ad_id = $ad_id");
            if ($features_result) {
                $ad_features = $features_result->fetch_all(MYSQLI_ASSOC);
            }

            // Check if current user has favorited this ad
            if (isset($_SESSION['user_id'])) {
                $user_id = $_SESSION['user_id'];
                $is_own_ad = ($user_id == $ad['user_id']);

                $fav_stmt = $conn->prepare("SELECT id FROM favorites WHERE user_id = ? AND ad_id = ?");
                if ($fav_stmt) {
                    $fav_stmt->bind_param("ii", $user_id, $ad_id);
                    $fav_stmt->execute();
                    $is_favorited = $fav_stmt->get_result()->num_rows > 0;
                    $fav_stmt->close();
                }
            }

            // Fetch Seller Reviews and Average Rating
            $seller_reviews = [];
            $seller_average_rating = 0;
            $seller_total_reviews = 0;

            $seller_review_stmt = $conn->prepare("
                SELECT r.rating
                FROM reviews r
                JOIN ads a ON r.ad_id = a.id
                WHERE a.user_id = ?
            ");
            if ($seller_review_stmt) {
                $seller_review_stmt->bind_param("i", $ad['user_id']);
                $seller_review_stmt->execute();
                $seller_review_result = $seller_review_stmt->get_result();
                if($seller_review_result) {
                    $seller_reviews = $seller_review_result->fetch_all(MYSQLI_ASSOC);
                }
                $seller_review_stmt->close();

                if (count($seller_reviews) > 0) {
                    $seller_total_reviews = count($seller_reviews);
                    $total_rating_sum = array_sum(array_column($seller_reviews, 'rating'));
                    $seller_average_rating = round($total_rating_sum / $seller_total_reviews, 1);
                }
            }

        } else {
            // Ad not found or not active
            $page_title = "Ad Not Found";
        }
    }
} else {
    // FIX: Handle missing database connection gracefully
    $error_message = "Database connection unavailable.";
    $page_title = "System Error";
}

// Now include the header which will use the Open Graph variables we set above
require_once 'includes/header.php';
?>

<style>
.is-favorited {
    color: #8B5CF6; /* Tailwind CSS purple-500 */
    background-color: #F5F3FF; /* Tailwind CSS purple-50 */
}
.is-favorited:hover {
    color: #8B5CF6;
    background-color: #EDE9FE; /* Tailwind CSS purple-100 */
}
</style>

<div class="container mx-auto px-4 lg:px-6 py-8">
    <?php if ($error_message): // FIX: Display error within layout instead of dying ?>
        <div class="bg-red-50 border border-red-200 p-6 rounded-lg text-center max-w-2xl mx-auto">
            <i data-lucide="alert-circle" class="w-16 h-16 mx-auto text-red-400 mb-4"></i>
            <h1 class="text-2xl font-bold text-red-800 mb-2">System Error</h1>
            <p class="text-red-600 mb-4"><?php echo $error_message; ?></p>
            <a href="/listing.php" class="inline-block bg-red-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-red-700">
                Browse Other Ads
            </a>
        </div>
    <?php elseif ($ad): // Only render the page content if the ad was found ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-2">
            <div class="bg-white p-4 rounded-lg shadow-md mb-6">
                <div class="mb-4">
                    <!-- FIX: Use root-relative path / instead of SITE_URL -->
                    <img id="main-image" src="/<?php echo (!empty($ad_images) ? escape($ad_images[0]['image_url']) : 'assets/images/placeholder.png'); ?>"
                         alt="Main ad image"
                         class="w-full h-auto max-h-[500px] object-contain rounded-lg bg-gray-100"
                         onerror="this.onerror=null;this.src='https://placehold.co/800x600/e2e8f0/4a5568?text=Image+Not+Available';">
                </div>
                <?php if (count($ad_images) > 1): ?>
                <div class="grid grid-cols-3 sm:grid-cols-5 gap-2">
                    <?php foreach ($ad_images as $image): ?>
                    <!-- FIX: Use root-relative path / instead of SITE_URL -->
                    <img src="/<?php echo escape($image['image_url']); ?>"
                         alt="Ad thumbnail"
                         class="w-full h-24 object-cover rounded-md cursor-pointer border-2 border-transparent hover:border-blue-500 transition"
                         onclick="document.getElementById('main-image').src = this.src">
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="bg-white p-6 rounded-lg shadow-md">
                <div class="mb-4">
                    <a href="/listing.php?category=<?php echo urlencode($ad['category_slug']); ?>" class="text-sm font-medium text-blue-600 hover:underline"><?php echo escape($ad['category_name']); ?></a>
                    <h1 class="text-3xl font-bold text-gray-900 mt-1"><?php echo escape($ad['title']); ?></h1>
                </div>
                <div class="flex flex-wrap items-center text-sm text-gray-500 mb-4">
                    <span>Posted on <?php echo date('F j, Y', strtotime($ad['created_at'])); ?></span>
                    <?php if(!empty($ad['location'])): ?>
                    <span class="mx-2">|</span>
                    <i data-lucide="map-pin" class="w-4 h-4 mr-1"></i>
                    <span><?php echo escape($ad['location']); ?></span>
                    <?php endif; ?>
                </div>
                
                <div class="lg:hidden space-y-6 my-6">
                    <div class="bg-white p-6 rounded-lg shadow-md border">
                        <div class="flex justify-between items-start pb-4 border-b">
                            <div>
                                <p class="text-4xl font-bold text-blue-600">
                                    <?php echo ($ad['currency'] === 'NGN' ? '₦' : '$') . number_format($ad['price']); ?>
                                </p>
                                <?php if ($ad['price_type'] === 'negotiable'): ?>
                                    <span class="text-sm font-normal text-gray-500">(Negotiable)</span>
                                <?php endif; ?>
                            </div>
                            <button id="favorite-btn-mobile" data-ad-id="<?php echo $ad_id; ?>" class="favorite-btn p-2 rounded-full text-gray-400 hover:bg-purple-50 hover:text-purple-500 transition-colors <?php echo $is_favorited ? 'is-favorited' : ''; ?>">
                                <i data-lucide="heart" class="w-7 h-7 <?php echo $is_favorited ? 'fill-current' : ''; ?>"></i>
                                <span class="sr-only">Favorite</span>
                            </button>
                        </div>

                        <div class="mt-4">
                            <h3 class="font-bold text-lg mb-4">Seller Information</h3>
                            <div class="flex items-center mb-4">
                                <a href="/<?php echo urlencode($ad['seller_username']); ?>">
                                    <!-- FIX: Use root-relative path for seller avatar -->
                                    <img src="/assets/images/profiles/<?php echo escape($ad['seller_avatar'] ?? 'default.png'); ?>" class="w-16 h-16 rounded-full object-cover mr-4 bg-gray-200" onerror="this.onerror=null;this.src='https://placehold.co/64x64/e2e8f0/4a5568?text=<?php echo substr($ad['seller_username'], 0, 1); ?>';">
                                </a>
                                <div>
                                    <a href="/<?php echo urlencode($ad['seller_username']); ?>" class="font-semibold text-xl hover:text-blue-600 hover:underline flex items-center">
                                        <?php echo escape($ad['seller_username']); ?>
                                        <?php if ($ad['seller_is_verified']): ?>
                                            <i data-lucide="badge-check" class="w-5 h-5 text-blue-600 ml-1.5" title="Verified Seller"></i>
                                        <?php endif; ?>
                                    </a>
                                    <p class="text-sm text-gray-500">Member since <?php echo date('M Y', strtotime($ad['seller_join_date'])); ?></p>
                                </div>
                            </div>

                            <div class="flex items-center mb-4">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i data-lucide="star" class="w-5 h-5 <?php echo ($i <= $seller_average_rating) ? 'text-yellow-400 fill-current' : 'text-gray-300'; ?>"></i>
                                <?php endfor; ?>
                                <a href="/seller_reviews.php?username=<?php echo urlencode($ad['seller_username']); ?>" class="ml-2 text-sm text-blue-600 hover:underline">
                                    (<?php echo number_format($seller_average_rating, 1); ?> from <?php echo $seller_total_reviews; ?> reviews)
                                </a>
                            </div>

                            <div class="space-y-3 text-sm text-gray-600 mb-6">
                                <?php if (!empty($ad['seller_location'])): ?>
                                <div class="flex items-center">
                                    <i data-lucide="map-pin" class="w-4 h-4 mr-2 text-gray-400 flex-shrink-0"></i>
                                    <span><?php echo escape($ad['seller_location']); ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($ad['seller_shop_address'])): ?>
                                <div class="flex items-start">
                                    <i data-lucide="store" class="w-4 h-4 mr-2 text-gray-400 mt-1 flex-shrink-0"></i>
                                    <span><?php echo escape($ad['seller_shop_address']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <div class="space-y-3">
                                <?php if ($is_own_ad): ?>
                                    <a href="/user/edit_ad.php?id=<?php echo $ad['id']; ?>" class="w-full bg-gray-600 text-white font-bold py-3 rounded-lg transition flex items-center justify-center">
                                        <i data-lucide="edit" class="w-5 h-5 mr-2"></i> Edit Your Ad
                                    </a>
                                <?php elseif (isset($_SESSION['user_id'])): ?>
                                    <a href="/user/messages.php?ad_id=<?php echo $ad['id']; ?>&with=<?php echo $ad['user_id']; ?>" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition flex items-center justify-center">
                                        <i data-lucide="message-circle" class="w-5 h-5 mr-2"></i> Message Seller
                                    </a>
                                <?php else: ?>
                                    <a href="/login.php?redirect=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition flex items-center justify-center">
                                        <i data-lucide="log-in" class="w-5 h-5 mr-2"></i> Login to Message
                                    </a>
                                <?php endif; ?>
                                <?php $whatsapp_num = !empty($ad['whatsapp_number']) ? $ad['whatsapp_number'] : $ad['phone_number']; ?>
                                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $whatsapp_num); ?>?text=Hello, I'm interested in your ad '<?php echo urlencode($ad['title']); ?>' on ZeeloQ." target="_blank" class="w-full bg-green-500 text-white font-bold py-3 rounded-lg hover:bg-green-600 transition flex items-center justify-center">
                                    <i data-lucide="message-circle" class="w-5 h-5 mr-2"></i> Chat on WhatsApp
                                </a>
                                <button class="show-phone-btn w-full bg-gray-200 text-gray-800 font-bold py-3 rounded-lg hover:bg-gray-300 transition flex items-center justify-center">
                                    <i data-lucide="phone" class="w-5 h-5 mr-2"></i>
                                    <span>Show Phone Number</span>
                                </button>
                                <p class="phone-number-display text-center text-2xl font-bold pt-2 hidden"><?php echo escape($ad['phone_number']); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="bg-blue-50 border border-blue-200 p-6 rounded-lg">
                        <h3 class="font-bold text-lg mb-3 text-blue-800">Safety Tips</h3>
                        <ul class="space-y-2 text-sm text-blue-700 list-disc list-inside">
                            <li>Avoid sending any prepayments.</li>
                            <li>Meet with the seller at a safe public place.</li>
                            <li>Inspect what you're going to buy.</li>
                            <li>Check all docs and only pay if you're satisfied.</li>
                        </ul>
                    </div>
                </div>
                <hr class="my-6">
                <h2 class="text-xl font-semibold mb-3">Description</h2>
                <div class="prose max-w-none text-gray-700 overflow-wrap break-words">
                    <?php echo nl2br(htmlspecialchars_decode(escape($ad['description']))); ?>
                </div>

                <?php if (!empty($ad['condition']) || !empty($ad_features)): ?>
                <h2 class="text-xl font-semibold mt-8 mb-4">Features & Specifications</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <?php if (!empty($ad['condition'])): ?>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <div class="flex justify-between">
                            <span class="font-medium text-gray-600">Condition:</span>
                            <span class="text-gray-800 font-semibold"><?php echo ucfirst(escape($ad['condition'])); ?></span>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php foreach ($ad_features as $feature): ?>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <div class="flex justify-between">
                            <span class="font-medium text-gray-600"><?php echo escape($feature['feature_name']); ?>:</span>
                            <span class="text-gray-800 font-semibold"><?php echo escape($feature['feature_value']); ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="lg:col-span-1 space-y-6 lg:sticky lg:top-24 hidden lg:block">
            <div class="bg-white p-6 rounded-lg shadow-md">
                <div class="flex justify-between items-start pb-4 border-b">
                    <div>
                        <p class="text-4xl font-bold text-blue-600">
                            <?php echo ($ad['currency'] === 'NGN' ? '₦' : '$') . number_format($ad['price']); ?>
                        </p>
                        <?php if ($ad['price_type'] === 'negotiable'): ?>
                            <span class="text-sm font-normal text-gray-500">(Negotiable)</span>
                        <?php endif; ?>
                    </div>
                    <button id="favorite-btn-desktop" data-ad-id="<?php echo $ad_id; ?>" class="favorite-btn p-2 rounded-full text-gray-400 hover:bg-purple-50 hover:text-purple-500 transition-colors <?php echo $is_favorited ? 'is-favorited' : ''; ?>">
                        <i data-lucide="heart" class="w-7 h-7 <?php echo $is_favorited ? 'fill-current' : ''; ?>"></i>
                        <span class="sr-only">Favorite</span>
                    </button>
                </div>

                <div class="mt-4">
                    <h3 class="font-bold text-lg mb-4">Seller Information</h3>
                    <div class="flex items-center mb-4">
                        <a href="/<?php echo urlencode($ad['seller_username']); ?>">
                            <!-- FIX: Use root-relative path for seller avatar -->
                            <img src="/assets/images/profiles/<?php echo escape($ad['seller_avatar'] ?? 'default.png'); ?>" class="w-16 h-16 rounded-full object-cover mr-4 bg-gray-200" onerror="this.onerror=null;this.src='https://placehold.co/64x64/e2e8f0/4a5568?text=<?php echo substr($ad['seller_username'], 0, 1); ?>';">
                        </a>
                        <div>
                            <a href="/<?php echo urlencode($ad['seller_username']); ?>" class="font-semibold text-xl hover:text-blue-600 hover:underline flex items-center">
                                <?php echo escape($ad['seller_username']); ?>
                                <?php if ($ad['seller_is_verified']): ?>
                                    <i data-lucide="badge-check" class="w-5 h-5 text-blue-600 ml-1.5" title="Verified Seller"></i>
                                <?php endif; ?>
                            </a>
                            <p class="text-sm text-gray-500">Member since <?php echo date('M Y', strtotime($ad['seller_join_date'])); ?></p>
                        </div>
                    </div>

                    <div class="flex items-center mb-4">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <i data-lucide="star" class="w-5 h-5 <?php echo ($i <= $seller_average_rating) ? 'text-yellow-400 fill-current' : 'text-gray-300'; ?>"></i>
                        <?php endfor; ?>
                        
                        <a href="/seller_reviews.php?username=<?php echo urlencode($ad['seller_username']); ?>" class="ml-2 text-sm text-blue-600 hover:underline">
                            (<?php echo number_format($seller_average_rating, 1); ?> from <?php echo $seller_total_reviews; ?> reviews)
                        </a>
                    </div>

                    <div class="space-y-3 text-sm text-gray-600 mb-6">
                        <?php if (!empty($ad['seller_location'])): ?>
                        <div class="flex items-center">
                            <i data-lucide="map-pin" class="w-4 h-4 mr-2 text-gray-400 flex-shrink-0"></i>
                            <span><?php echo escape($ad['seller_location']); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if (!empty($ad['seller_shop_address'])): ?>
                        <div class="flex items-start">
                            <i data-lucide="store" class="w-4 h-4 mr-2 text-gray-400 mt-1 flex-shrink-0"></i>
                            <span><?php echo escape($ad['seller_shop_address']); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>

                    <div class="space-y-3">
                         <?php if ($is_own_ad): ?>
                            <a href="/user/edit_ad.php?id=<?php echo $ad['id']; ?>" class="w-full bg-gray-600 text-white font-bold py-3 rounded-lg transition flex items-center justify-center">
                                <i data-lucide="edit" class="w-5 h-5 mr-2"></i> Edit Your Ad
                            </a>
                        <?php elseif (isset($_SESSION['user_id'])): ?>
                            <a href="/user/messages.php?ad_id=<?php echo $ad['id']; ?>&with=<?php echo $ad['user_id']; ?>" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition flex items-center justify-center">
                                <i data-lucide="message-circle" class="w-5 h-5 mr-2"></i> Message Seller
                            </a>
                        <?php else: ?>
                            <a href="/login.php?redirect=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition flex items-center justify-center">
                                 <i data-lucide="log-in" class="w-5 h-5 mr-2"></i> Login to Message
                            </a>
                        <?php endif; ?>
                        <?php $whatsapp_num = !empty($ad['whatsapp_number']) ? $ad['whatsapp_number'] : $ad['phone_number']; ?>
                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $whatsapp_num); ?>?text=Hello, I'm interested in your ad '<?php echo urlencode($ad['title']); ?>' on ZeeloQ." target="_blank" class="w-full bg-green-500 text-white font-bold py-3 rounded-lg hover:bg-green-600 transition flex items-center justify-center">
                            <i data-lucide="message-circle" class="w-5 h-5 mr-2"></i> Chat on WhatsApp
                        </a>
                        <button class="show-phone-btn w-full bg-gray-200 text-gray-800 font-bold py-3 rounded-lg hover:bg-gray-300 transition flex items-center justify-center">
                            <i data-lucide="phone" class="w-5 h-5 mr-2"></i>
                            <span>Show Phone Number</span>
                        </button>
                        <p class="phone-number-display text-center text-2xl font-bold pt-2 hidden"><?php echo escape($ad['phone_number']); ?></p>
                    </div>
                </div>
            </div>

            <div class="bg-blue-50 border border-blue-200 p-6 rounded-lg">
                <h3 class="font-bold text-lg mb-3 text-blue-800">Safety Tips</h3>
                <ul class="space-y-2 text-sm text-blue-700 list-disc list-inside">
                    <li>Avoid sending any prepayments.</li>
                    <li>Meet with the seller at a safe public place.</li>
                    <li>Inspect what you're going to buy.</li>
                    <li>Check all docs and only pay if you're satisfied.</li>
                </ul>
            </div>
        </div>
    </div>

    <?php
        // Include the related ads partial only if we have a valid ad.
        // It requires the current ad's ID and category ID to find similar ads.
        // We define them here to pass the context to the included file.
        if ($ad) {
            $current_ad_id = $ad['id'];
            $current_category_id = $ad['category_id'];
            include 'related_ads.php';
        }
    ?>

    <?php else: // Show an error message if the ad was not found ?>
        <div class="text-center py-20 max-w-2xl mx-auto">
            <i data-lucide="search-x" class="w-24 h-24 mx-auto text-gray-300"></i>
            <h1 class="text-3xl font-bold mt-4">Ad Not Found</h1>
            <p class="text-gray-600 mt-2">Sorry, this ad is not available. It may have been deleted, expired, or is pending approval.</p>
            <a href="/listing.php" class="mt-6 inline-block bg-blue-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-blue-700">Browse Other Ads</a>
        </div>
    <?php endif; ?>
</div>
<script>
    // Safe Lucide initialization that works with deferred scripts
    function initLucideIcons() {
        if (typeof lucide !== 'undefined' && lucide.createIcons) {
            try {
                lucide.createIcons();
                return true;
            } catch (e) {
                console.error('Lucide initialization error:', e);
            }
        }
        return false;
    }

    // Initialize when DOM is ready (after deferred scripts load)
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initLucideIcons);
    } else {
        initLucideIcons();
    }
    
    // Fallback: Also try on window load to catch any late loaders
    window.addEventListener('load', initLucideIcons);

    // Show Phone Number Logic
    const showPhoneBtns = document.querySelectorAll('.show-phone-btn');
    showPhoneBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const parentContainer = this.closest('.space-y-3');
            if (parentContainer) {
                const phoneDisplay = parentContainer.querySelector('.phone-number-display');
                if (phoneDisplay) {
                    phoneDisplay.classList.remove('hidden');
                    this.style.display = 'none';
                }
            }
        });
    });

    // Favorite Button Logic
    const favoriteBtns = document.querySelectorAll('.favorite-btn');
    favoriteBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const adId = this.dataset.adId;
            const isCurrentlyFavorited = this.classList.contains('is-favorited');
            
            // Toggle visual state immediately for better UX
            favoriteBtns.forEach(b => {
                b.classList.toggle('is-favorited');
                const icon = b.querySelector('i[data-lucide="heart"]');
                if (icon) {
                    icon.classList.toggle('fill-current');
                }
            });
            
            // Re-render icons after state change
            initLucideIcons();
            
            fetch('/user/toggle_favorite.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `ad_id=${adId}&action=${isCurrentlyFavorited ? 'remove' : 'add'}`
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    console.error('Failed to update favorite:', data.message);
                    favoriteBtns.forEach(b => {
                        b.classList.toggle('is-favorited');
                        const icon = b.querySelector('i[data-lucide="heart"]');
                        if (icon) { icon.classList.toggle('fill-current'); }
                    });
                    alert('Error: ' + (data.message || 'Could not update your favorites.'));
                }
            })
            .catch(error => {
                console.error('Fetch Error:', error);
                favoriteBtns.forEach(b => {
                    b.classList.toggle('is-favorited');
                    const icon = b.querySelector('i[data-lucide="heart"]');
                    if (icon) { icon.classList.toggle('fill-current'); }
                });
            });
        });
    });
</script>


<?php
require_once 'includes/footer.php';
?>
