<?php
/**
 * POST /api/admin/ads_create.php (multipart/form-data)
 * Admin-only. Fields:
 *   placement_key, ad_type ('google'|'custom'), width, height, display_order
 *   google: google_ad_slot
 *   custom: custom_link_url, custom_alt_text, and an uploaded image[] file
 */

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

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

const VALID_PLACEMENTS = [
    'marketplace_top', 'marketplace_infeed', 'marketplace_bottom', 'marketplace_card',
    'product_details_top', 'product_details_bottom',
    'vendors_top', 'vendors_infeed', 'vendors_bottom',
    'vendor_profile_top', 'vendor_profile_bottom',
];

$placementKey = trim($_POST['placement_key'] ?? '');
$adType = $_POST['ad_type'] ?? '';
$width = (int) ($_POST['width'] ?? 0);
$height = (int) ($_POST['height'] ?? 0);
$displayOrder = (int) ($_POST['display_order'] ?? 0);

if (!in_array($placementKey, VALID_PLACEMENTS, true)) {
    send_error('Unknown placement_key.', 422);
}
if (!in_array($adType, ['google', 'custom'], true)) {
    send_error('ad_type must be "google" or "custom".', 422);
}
if ($placementKey === 'marketplace_card' && $adType === 'google') {
    // A card-shaped ad blending into the listing grid is a "native" ad unit -
    // a different, more involved Google integration than the standard
    // rectangle/banner units this app supports. Custom (image + link) is
    // the only option here for now, and it works immediately either way.
    send_error('The listing-card placement only supports custom ads (image + link) for now.', 422);
}
if ($width <= 0 || $height <= 0) {
    send_error('A valid width and height are required.', 422);
}

$googleAdSlot = null;
$isTestMode = 0;
$customImagePath = null;
$customLinkUrl = null;
$customAltText = null;

if ($adType === 'google') {
    $googleAdSlot = trim($_POST['google_ad_slot'] ?? '');
    if ($googleAdSlot === '') {
        send_error('google_ad_slot is required for a Google ad.', 422);
    }
    $isTestMode = !empty($_POST['is_test_mode']) ? 1 : 0;
} else {
    $customLinkUrl = trim($_POST['custom_link_url'] ?? '');
    $customAltText = trim($_POST['custom_alt_text'] ?? '');
    if ($customLinkUrl === '') {
        send_error('custom_link_url is required for a custom ad.', 422);
    }
    if (!isset($_FILES['image']) || $_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) {
        send_error('An image is required for a custom ad.', 422);
    }
    $result = save_uploaded_image($_FILES['image'], 'ads');
    if (!$result['ok']) {
        send_error($result['error'], 422);
    }
    $customImagePath = $result['path'];
}

$pdo = Database::connect();
$stmt = $pdo->prepare(
    'INSERT INTO ad_placements (placement_key, ad_type, width, height, google_ad_slot, is_test_mode, custom_image_path, custom_link_url, custom_alt_text, display_order)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([$placementKey, $adType, $width, $height, $googleAdSlot, $isTestMode, $customImagePath, $customLinkUrl, $customAltText, $displayOrder]);

send_json(true, 'Ad created.', ['id' => (int) $pdo->lastInsertId()], 201);
