<?php
/*
 * HORIZONTAL AD COMPONENT (AUTO CENTER)
 *
 * - 1 Ad → Centered
 * - 2 Ads → Centered with equal spacing (desktop only)
 * - 3 Ads → Spread evenly
 * - 0 Ads → Hidden completely
 */
?>

<style>
/* === CONTAINER ALIGNMENT === */
.horizontal-ad-container {
    width: 100%;
    max-width: 1200px;
    margin: 10px auto;
    padding: 0;
    background: transparent;
    overflow: hidden;
}

/* === FLEX ROW === */
.horizontal-ad-container .ad-row {
    display: flex;
    flex-wrap: wrap;
    justify-content: center; /* default center */
    width: 100%;
    margin: 0 -5px;
}

/* === COLUMNS === */
.horizontal-ad-container .ad-column {
    flex: 0 0 33.333%;
    width: 33.333%;
    padding: 0 5px;
}

/* === AD ITEM === */
.horizontal-ad-item {
    max-width: 400px;
    height: 60px;
    margin: 0 auto;
    background: #f0f0f0;
    overflow: hidden;
    border-radius: 10px;
}

.horizontal-ad-item a {
    display: block;
    width: 100%;
    height: 100%;
}

.horizontal-ad-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

/* === RESPONSIVE === */
@media (max-width: 767px) {
    .horizontal-ad-container .ad-row {
        flex-direction: column;
        align-items: center;
        margin: 0;
        padding: 0;
        gap: 10px !important; /* smaller gap for mobile */
    }
    .horizontal-ad-container .ad-column {
        width: 100%;
        padding: 0;
        margin: 0;
    }
    .horizontal-ad-item {
        max-width: 400px;
    }
}
</style>

<?php
// === FETCH ADS FROM DATABASE ===
$horizontal_ads = [];
try {
    if (isset($conn)) {
        $horizontal_ads = $conn->query("SELECT * FROM horizontal_ads ORDER BY RAND() LIMIT 3")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    error_log("Error fetching horizontal ads: " . $e->getMessage());
}

$ad_count = count($horizontal_ads);
?>

<?php if ($ad_count > 0): ?>
    <div class="horizontal-ad-container">
        <div class="ad-row" 
            style="
                <?php 
                    if ($ad_count === 1) echo 'justify-content:center;';
                    elseif ($ad_count === 2) echo 'justify-content:center; gap:40px;';
                    else echo 'justify-content:space-between;';
                ?>
            ">
            <?php foreach ($horizontal_ads as $ad): ?>
                <div class="ad-column" style="<?php echo $ad_count < 3 ? 'flex:0 0 auto; width:auto;' : ''; ?>">
                    <div class="horizontal-ad-item">
                        <a href="<?php echo htmlspecialchars($ad['link_url'] ?? '#'); ?>" target="_blank" rel="noopener noreferrer">
                            <img src="<?php echo BASE_URL; ?>Uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" alt="Advertisement">
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php endif; ?>
