<?php
/**
 * Ad Display Engine
 * This function fetches a random ACTIVE ad for a specific slot from the database.
 */
function display_ad_slot($pdo, $slot_name) {
    // If PDO isn't passed or isn't valid, fail silently so we don't break the page
    if (!$pdo) return;

    try {
        $stmt = $pdo->prepare("SELECT target_url, banner_code FROM campaigns WHERE slot = ? AND status = 'ACTIVE' ORDER BY RAND() LIMIT 1");
        $stmt->execute([$slot_name]);
        $ad = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($ad) {
            echo '<div class="w-full flex justify-center items-center overflow-hidden relative group my-2">';
            
            // Add a subtle "Advertisement" label
            echo '<span class="absolute top-0 right-0 bg-slate-900/80 text-slate-400 text-[8px] uppercase tracking-widest px-2 py-0.5 rounded-bl z-10">Ad</span>';

            if (!empty($ad['target_url'])) {
                echo '<a href="' . htmlspecialchars($ad['target_url']) . '" target="_blank" rel="noopener sponsored" class="w-full text-center hover:opacity-90 transition-opacity">';
            }
            
            // Output the raw HTML or Image code from the database
            echo $ad['banner_code'];
            
            if (!empty($ad['target_url'])) {
                echo '</a>';
            }
            
            echo '</div>';
        }
    } catch (PDOException $e) {
        // Fail silently on the front end if the table doesn't exist yet
        return;
    }
}
?>