<?php
/**
 * GET /api/admin/ads_list.php
 * Admin-only. Every ad, active or not, for the management screen.
 */

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

require_login();
require_role(['admin']);

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$total = (int) $pdo->query('SELECT COUNT(*) FROM ad_placements')->fetchColumn();

$stmt = $pdo->prepare("SELECT * FROM ad_placements ORDER BY placement_key ASC, display_order ASC, id ASC LIMIT $perPage OFFSET $offset");
$stmt->execute();
$ads = $stmt->fetchAll();

foreach ($ads as &$ad) {
    $ad['custom_image_url'] = $ad['custom_image_path'] ? UPLOAD_URL . $ad['custom_image_path'] : null;
}

send_json(true, 'OK', [
    'ads' => $ads,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
