<?php
/**
 * GET /api/ads/list.php?placement_key=marketplace_top
 * Public. Returns every active ad configured for that placement, in
 * display order. The AdSense client ID is joined in for any Google-type
 * ad so the front-end doesn't need a second request to render it.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/settings.php';

$placementKey = trim($_GET['placement_key'] ?? '');
if ($placementKey === '') {
    send_error('placement_key is required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare(
    'SELECT id, ad_type, width, height, google_ad_slot, is_test_mode, custom_image_path, custom_link_url, custom_alt_text
     FROM ad_placements
     WHERE placement_key = ? AND is_active = 1
     ORDER BY display_order ASC, id ASC'
);
$stmt->execute([$placementKey]);
$ads = $stmt->fetchAll();

$adsenseClientId = get_setting($pdo, 'adsense_client_id', '');

foreach ($ads as &$ad) {
    if ($ad['ad_type'] === 'custom' && $ad['custom_image_path']) {
        $ad['custom_image_url'] = UPLOAD_URL . $ad['custom_image_path'];
    } else {
        $ad['custom_image_url'] = null;
    }
    unset($ad['custom_image_path']);
    $ad['is_test_mode'] = (bool) $ad['is_test_mode'];
    if ($ad['ad_type'] === 'google') {
        $ad['adsense_client_id'] = $adsenseClientId;
    }
}

send_json(true, 'OK', ['ads' => $ads]);
