<?php
/**
 * POST /api/admin/ads_update.php
 * Admin-only. Body (JSON): { id, is_active?, display_order?, google_ad_slot?, custom_link_url?, custom_alt_text? }
 * Toggling active/inactive and editing text fields only - to replace the
 * image on a custom ad, delete it and create a new one (keeps this
 * endpoint simple and avoids a second multipart code path).
 */

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

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

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid ad id is required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id FROM ad_placements WHERE id = ?');
$stmt->execute([$id]);
if (!$stmt->fetch()) {
    send_error('Ad not found.', 404);
}

$set = [];
$params = [];
if (array_key_exists('is_active', $input)) {
    $set[] = 'is_active = ?';
    $params[] = $input['is_active'] ? 1 : 0;
}
if (array_key_exists('display_order', $input)) {
    $set[] = 'display_order = ?';
    $params[] = (int) $input['display_order'];
}
if (array_key_exists('google_ad_slot', $input)) {
    $set[] = 'google_ad_slot = ?';
    $params[] = trim($input['google_ad_slot']);
}
if (array_key_exists('is_test_mode', $input)) {
    $set[] = 'is_test_mode = ?';
    $params[] = $input['is_test_mode'] ? 1 : 0;
}
if (array_key_exists('custom_link_url', $input)) {
    $set[] = 'custom_link_url = ?';
    $params[] = trim($input['custom_link_url']);
}
if (array_key_exists('custom_alt_text', $input)) {
    $set[] = 'custom_alt_text = ?';
    $params[] = trim($input['custom_alt_text']);
}

if (!$set) {
    send_error('No fields to update.', 422);
}

$params[] = $id;
$stmt = $pdo->prepare('UPDATE ad_placements SET ' . implode(', ', $set) . ' WHERE id = ?');
$stmt->execute($params);

send_json(true, 'Ad updated.');
