<?php
declare(strict_types=1);

/**
 * /admin/reclama/campaigns.php
 *
 * Окрема сторінка керування рекламними кампаніями:
 * - Топ кампаній
 * - Черга модерації
 * - Останні кампанії
 * - Швидкі дії: approve / reject / pause / resume / finish / cancel
 * - Повне видалення рекламної кампанії
 */

require_once __DIR__ . '/../../includes/start.php';
require_once __DIR__ . '/../_helpers.php';
require_once __DIR__ . '/../_sidebar.php';

$reclamaLib = __DIR__ . '/../../functional/reclama/_lib.php';
if (is_file($reclamaLib)) {
    require_once $reclamaLib;
}
unset($reclamaLib);

$reclamaStats = __DIR__ . '/../../functional/reclama/_stats.php';
if (is_file($reclamaStats)) {
    require_once $reclamaStats;
}
unset($reclamaStats);

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
    header('Cache-Control: no-store, max-age=0', true);
    header('Pragma: no-cache', true);
}

require_login();

$pdo = (isset($pdo) && $pdo instanceof PDO) ? $pdo : db();
$me  = (isset($me) && is_array($me)) ? $me : current_user();

if (function_exists('require_role')) {
    require_role(['admin']);
} else {
    $role = (string)($me['role'] ?? '');
    if ($role !== 'admin') {
        http_response_code(403);
        exit('Forbidden');
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token(): string
    {
        admin_session_start();
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
        }
        return (string)$_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_check')) {
    function csrf_check(?string $token): bool
    {
        admin_session_start();
        $sent = (string)($token ?? '');
        $sess = (string)($_SESSION['csrf_token'] ?? '');
        return $sent !== '' && $sess !== '' && hash_equals($sess, $sent);
    }
}

if (!function_exists('is_post')) {
    function is_post(): bool
    {
        return strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'POST';
    }
}

if (!function_exists('admin_reclama_t')) {
    function admin_reclama_t(string $key, string $uk, string $ru, string $en): string
    {
        return admin_tt($key, $uk, $ru, $en);
    }
}

if (!function_exists('admin_reclama_redirect_self')) {
    function admin_reclama_redirect_self(): never
    {
        header('Location: /admin/reclama/campaigns.php', true, 303);
        exit;
    }
}

if (!function_exists('admin_reclama_num')) {
    function admin_reclama_num($n): string
    {
        return number_format((float)$n, 0, '.', ' ');
    }
}

if (!function_exists('admin_reclama_money')) {
    function admin_reclama_money($n): string
    {
        return number_format((float)$n, 0, '.', ' ') . ' VM Coins';
    }
}

if (!function_exists('admin_reclama_float')) {
    function admin_reclama_float($n, int $decimals = 2): string
    {
        return number_format((float)$n, $decimals, '.', ' ');
    }
}

if (!function_exists('admin_reclama_campaign_url')) {
    function admin_reclama_campaign_url(int $campaignId): string
    {
        return '/admin/reclama/campaign.php?id=' . max(0, $campaignId);
    }
}

if (!function_exists('admin_reclama_user_label')) {
    function admin_reclama_user_label(array $row): string
    {
        $username = trim((string)($row['username'] ?? ($row['owner_username'] ?? '')));
        $name     = trim((string)($row['name'] ?? ($row['owner_name'] ?? '')));
        $userId   = (int)($row['user_id'] ?? 0);

        if ($username !== '' && $name !== '') {
            return '@' . $username . ' · ' . $name;
        }
        if ($username !== '') {
            return '@' . $username;
        }
        if ($name !== '') {
            return $name;
        }
        return '#' . $userId;
    }
}

if (!function_exists('admin_reclama_status_badge')) {
    function admin_reclama_status_badge(string $status): string
    {
        return match ($status) {
            'active'   => 'success',
            'approved' => 'info',
            'pending'  => 'warning',
            'rejected' => 'danger',
            'paused'   => 'secondary',
            'finished' => 'dark',
            'canceled' => 'secondary',
            default    => 'light',
        };
    }
}

if (!function_exists('admin_reclama_payment_badge')) {
    function admin_reclama_payment_badge(string $status): string
    {
        return match ($status) {
            'paid'           => 'success',
            'reserved'       => 'info',
            'unpaid'         => 'warning',
            'refunded'       => 'secondary',
            'partial_refund' => 'secondary',
            default          => 'light',
        };
    }
}

if (!function_exists('admin_reclama_label_status')) {
    function admin_reclama_label_status(string $status): string
    {
        return match ($status) {
            'draft'    => admin_reclama_t('admin_reclama_st_draft', 'Чернетка', 'Черновик', 'Draft'),
            'pending'  => admin_reclama_t('admin_reclama_st_pending', 'На перевірці', 'На проверке', 'Pending'),
            'approved' => admin_reclama_t('admin_reclama_st_approved', 'Схвалено', 'Одобрено', 'Approved'),
            'rejected' => admin_reclama_t('admin_reclama_st_rejected', 'Відхилено', 'Отклонено', 'Rejected'),
            'active'   => admin_reclama_t('admin_reclama_st_active', 'Активна', 'Активна', 'Active'),
            'paused'   => admin_reclama_t('admin_reclama_st_paused', 'На паузі', 'На паузе', 'Paused'),
            'finished' => admin_reclama_t('admin_reclama_st_finished', 'Завершена', 'Завершена', 'Finished'),
            'canceled' => admin_reclama_t('admin_reclama_st_canceled', 'Скасована', 'Отменена', 'Canceled'),
            default    => $status,
        };
    }
}

if (!function_exists('admin_reclama_label_moderation')) {
    function admin_reclama_label_moderation(string $status): string
    {
        return match ($status) {
            'pending'  => admin_reclama_t('admin_reclama_mod_pending', 'На модерації', 'На модерации', 'In moderation'),
            'approved' => admin_reclama_t('admin_reclama_mod_approved', 'Схвалено модератором', 'Одобрено модератором', 'Moderator approved'),
            'rejected' => admin_reclama_t('admin_reclama_mod_rejected', 'Відхилено модератором', 'Отклонено модератором', 'Moderator rejected'),
            default    => $status !== '' ? $status : '—',
        };
    }
}

if (!function_exists('admin_reclama_label_payment')) {
    function admin_reclama_label_payment(string $status): string
    {
        return match ($status) {
            'paid'           => admin_reclama_t('admin_reclama_pay_paid', 'Оплачено', 'Оплачено', 'Paid'),
            'unpaid'         => admin_reclama_t('admin_reclama_pay_unpaid', 'Не оплачено', 'Не оплачено', 'Unpaid'),
            'reserved'       => admin_reclama_t('admin_reclama_pay_reserved', 'Зарезервовано', 'Зарезервировано', 'Reserved'),
            'refunded'       => admin_reclama_t('admin_reclama_pay_refunded', 'Повернено', 'Возвращено', 'Refunded'),
            'partial_refund' => admin_reclama_t('admin_reclama_pay_part_ref', 'Часткове повернення', 'Частичный возврат', 'Partial refund'),
            default          => $status,
        };
    }
}

if (!function_exists('admin_reclama_targeting_human')) {
    function admin_reclama_targeting_human(array $row): string
    {
        $parts = [];

        $country = trim((string)($row['country_code'] ?? ''));
        $city    = trim((string)($row['city'] ?? ''));
        $gender  = trim((string)($row['gender'] ?? 'any'));
        $lang    = trim((string)($row['lang_code'] ?? 'any'));
        $device  = trim((string)($row['device_type'] ?? 'all'));
        $ageFrom = isset($row['age_from']) && $row['age_from'] !== null ? (int)$row['age_from'] : null;
        $ageTo   = isset($row['age_to']) && $row['age_to'] !== null ? (int)$row['age_to'] : null;

        if ($country !== '') $parts[] = $country;
        if ($city !== '') $parts[] = $city;
        if ($gender !== '' && $gender !== 'any') $parts[] = 'gender:' . $gender;
        if ($lang !== '' && $lang !== 'any') $parts[] = 'lang:' . $lang;
        if ($device !== '' && $device !== 'all') $parts[] = 'device:' . $device;

        if ($ageFrom !== null || $ageTo !== null) {
            $parts[] = 'age:' . ($ageFrom !== null ? $ageFrom : '…') . '–' . ($ageTo !== null ? $ageTo : '…');
        }

        return $parts ? implode(', ', $parts) : '—';
    }
}

if (!function_exists('admin_reclama_delete_campaign')) {
    function admin_reclama_delete_campaign(PDO $pdo, int $campaignId): array
    {
        if ($campaignId <= 0) {
            return ['ok' => false, 'reason' => 'bad_id'];
        }

        if (!function_exists('reclama_get_campaign') || !function_exists('reclama_table_exists')) {
            return ['ok' => false, 'reason' => 'missing_helpers'];
        }

        $campaign = reclama_get_campaign($pdo, $campaignId);
        if (!$campaign) {
            return ['ok' => false, 'reason' => 'not_found'];
        }

        $ownTx = !$pdo->inTransaction();
        if ($ownTx) {
            $pdo->beginTransaction();
        }

        try {
            $childTables = [
                'reclama_campaign_clicks',
                'reclama_campaign_impressions',
                'reclama_campaign_daily_stats',
                'reclama_campaign_moderation',
                'reclama_campaign_targeting',
            ];

            foreach ($childTables as $table) {
                if (!reclama_table_exists($pdo, $table)) {
                    continue;
                }

                $st = $pdo->prepare("DELETE FROM `{$table}` WHERE campaign_id = ?");
                $st->execute([$campaignId]);
            }

            if (!reclama_table_exists($pdo, 'reclama_campaigns')) {
                throw new RuntimeException('campaigns_table_missing');
            }

            $st = $pdo->prepare("DELETE FROM `reclama_campaigns` WHERE id = ? LIMIT 1");
            $st->execute([$campaignId]);

            if ($st->rowCount() < 1) {
                throw new RuntimeException('delete_failed');
            }

            if ($ownTx && $pdo->inTransaction()) {
                $pdo->commit();
            }

            return ['ok' => true];
        } catch (Throwable $e) {
            if ($ownTx && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            error_log('admin/reclama/campaigns.php delete campaign error: ' . $e->getMessage());
            return ['ok' => false, 'reason' => 'delete_failed'];
        }
    }
}

/* ===== actions ===== */

if (is_post()) {
    $action = trim((string)($_POST['action'] ?? ''));

    if (!csrf_check((string)($_POST['csrf'] ?? ''))) {
        admin_flash_set(
            'danger',
            admin_reclama_t(
                'admin_reclama_bad_csrf',
                'Невірний CSRF токен.',
                'Неверный CSRF токен.',
                'Invalid CSRF token.'
            )
        );
        admin_reclama_redirect_self();
    }

    if ($action === 'moderate_campaign') {
        $campaignId = (int)($_POST['campaign_id'] ?? 0);
        $modAction  = trim((string)($_POST['mod_action'] ?? ''));
        $note       = trim((string)($_POST['note'] ?? ''));
        $adminId    = (int)($me['id'] ?? 0);

        if ($modAction === 'rejected' && $note === '') {
            admin_flash_set(
                'danger',
                admin_reclama_t(
                    'admin_reclama_reject_reason_required',
                    'Для відхилення потрібно вказати причину.',
                    'Для отклонения нужно указать причину.',
                    'A rejection reason is required.'
                )
            );
            admin_reclama_redirect_self();
        }

        $res = reclama_admin_change_status($pdo, $campaignId, $modAction, $adminId, $note);

        if (!($res['ok'] ?? false)) {
            admin_flash_set(
                'danger',
                admin_reclama_t(
                    'admin_reclama_mod_fail',
                    'Не вдалося змінити статус кампанії.',
                    'Не удалось изменить статус кампании.',
                    'Failed to change campaign status.'
                )
            );
        } else {
            admin_flash_set(
                'success',
                admin_reclama_t(
                    'admin_reclama_mod_ok',
                    'Статус кампанії оновлено.',
                    'Статус кампании обновлён.',
                    'Campaign status has been updated.'
                )
            );
        }

        admin_reclama_redirect_self();
    }

    if ($action === 'delete_campaign') {
        $campaignId = (int)($_POST['campaign_id'] ?? 0);
        $res = admin_reclama_delete_campaign($pdo, $campaignId);

        if (!($res['ok'] ?? false)) {
            admin_flash_set(
                'danger',
                admin_reclama_t(
                    'admin_reclama_delete_fail',
                    'Не вдалося видалити кампанію.',
                    'Не удалось удалить кампанию.',
                    'Failed to delete campaign.'
                )
            );
            admin_reclama_redirect_self();
        }

        admin_flash_set(
            'success',
            admin_reclama_t(
                'admin_reclama_delete_ok',
                'Рекламну кампанію видалено.',
                'Рекламная кампания удалена.',
                'Advertising campaign has been deleted.'
            )
        );
        admin_reclama_redirect_self();
    }
}

/* ===== view data ===== */

$flash = admin_flash_take();

$topCampaigns = function_exists('reclama_admin_top_campaigns')
    ? reclama_admin_top_campaigns($pdo, 10, 'impressions')
    : [];

$queue = reclama_admin_campaigns($pdo, 20, true);
$recentCampaigns = reclama_admin_campaigns($pdo, 30, false);

$title = admin_reclama_t(
    'admin_reclama_campaigns_title',
    'Рекламні кампанії — адмінка',
    'Рекламные кампании — админка',
    'Ad campaigns — Admin'
);

$seo_noindex = true;
$meta_robots = 'noindex, nofollow, noarchive, nosnippet';
$meta_desc   = '';
$canonical   = function_exists('abs_url') ? abs_url('/admin/reclama/campaigns.php') : '/admin/reclama/campaigns.php';

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="container py-3 py-lg-4">
    <div class="row g-4">
        <div class="col-lg-8">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                <div>
                    <h1 class="h3 mb-1"><?= e(admin_reclama_t('admin_reclama_campaigns_h1', 'Рекламні кампанії', 'Рекламные кампании', 'Ad campaigns')) ?></h1>
                    <div class="text-muted">
                        <?= e(admin_reclama_t(
                            'admin_reclama_campaigns_sub',
                            'Окрема сторінка для списків кампаній, черги модерації, швидких дій і видалення реклами.',
                            'Отдельная страница для списков кампаний, очереди модерации, быстрых действий и удаления рекламы.',
                            'Separate page for campaign lists, moderation queue, quick actions, and ad deletion.'
                        )) ?>
                    </div>
                </div>
            </div>

            <?php if ($flash): ?>
                <div class="alert alert-<?= e((string)$flash['type']) ?> mb-3">
                    <?= e((string)$flash['msg']) ?>
                </div>
            <?php endif; ?>

            <?php if ($topCampaigns): ?>
                <div class="card card-app mb-4">
                    <div class="card-body">
                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                            <h2 class="h5 mb-0"><?= e(admin_reclama_t('admin_reclama_top_campaigns', 'Топ кампаній', 'Топ кампаний', 'Top campaigns')) ?></h2>
                            <span class="text-muted small"><?= e(admin_reclama_t('admin_reclama_top_campaigns_hint', 'За показами.', 'По показам.', 'By impressions.')) ?></span>
                        </div>

                        <div class="d-grid gap-3">
                            <?php foreach ($topCampaigns as $row): ?>
                                <?php
                                $campaignId = (int)($row['id'] ?? 0);
                                $ownerLabel = admin_reclama_user_label($row);
                                $status     = (string)($row['status'] ?? '');
                                $modStatus  = (string)($row['moderation_status'] ?? '');
                                $payStatus  = (string)($row['payment_status'] ?? '');
                                ?>
                                <div class="border rounded-3 p-3">
                                    <div class="d-flex flex-wrap align-items-start justify-content-between gap-3 mb-2">
                                        <div>
                                            <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                                <a class="fw-semibold text-decoration-none" href="<?= e(admin_reclama_campaign_url($campaignId)) ?>">
                                                    #<?= e((string)$campaignId) ?> — <?= e((string)($row['title'] ?? '')) ?>
                                                </a>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($status)) ?>"><?= e(admin_reclama_label_status($status)) ?></span>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($modStatus)) ?>"><?= e(admin_reclama_label_moderation($modStatus)) ?></span>
                                                <span class="badge text-bg-<?= e(admin_reclama_payment_badge($payStatus)) ?>"><?= e(admin_reclama_label_payment($payStatus)) ?></span>
                                            </div>
                                            <div class="small text-muted">
                                                <?= e((string)($row['campaign_type'] ?? '')) ?> · <?= e($ownerLabel) ?>
                                            </div>
                                        </div>

                                        <div class="d-flex flex-wrap gap-2">
                                            <a href="<?= e(admin_reclama_campaign_url($campaignId)) ?>" class="btn btn-sm btn-outline-primary">
                                                <?= e(admin_reclama_t('admin_reclama_open', 'Відкрити', 'Открыть', 'Open')) ?>
                                            </a>

                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_delete_q', 'Повністю видалити цю кампанію?', 'Полностью удалить эту кампанию?', 'Permanently delete this campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="delete_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= e(admin_reclama_t('admin_reclama_delete', 'Видалити', 'Удалить', 'Delete')) ?>
                                                </button>
                                            </form>
                                        </div>
                                    </div>

                                    <div class="row g-3 mb-3">
                                        <div class="col-md-3">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_imps', 'Покази', 'Показы', 'Impressions')) ?></div>
                                            <div class="fw-semibold"><?= e(admin_reclama_num((int)($row['impressions_total'] ?? 0))) ?></div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_clicks', 'Кліки', 'Клики', 'Clicks')) ?></div>
                                            <div class="fw-semibold"><?= e(admin_reclama_num((int)($row['clicks_total'] ?? 0))) ?></div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_unique_viewers', 'Унікальні', 'Уникальные', 'Unique')) ?></div>
                                            <div class="fw-semibold"><?= e(admin_reclama_num((int)($row['unique_viewers_total'] ?? 0))) ?></div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-muted mb-1">CTR</div>
                                            <div class="fw-semibold"><?= e(admin_reclama_float((float)($row['ctr'] ?? 0), 2)) ?>%</div>
                                        </div>
                                    </div>

                                    <div class="d-flex flex-wrap gap-2">
                                        <?php if (in_array($status, ['active', 'approved'], true)): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="paused">
                                                <button type="submit" class="btn btn-sm btn-outline-secondary">
                                                    <?= e(admin_reclama_t('admin_reclama_pause', 'Пауза', 'Пауза', 'Pause')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if ($status === 'paused'): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="resumed">
                                                <button type="submit" class="btn btn-sm btn-outline-success">
                                                    <?= e(admin_reclama_t('admin_reclama_resume', 'Відновити', 'Возобновить', 'Resume')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if (!in_array($status, ['finished', 'canceled'], true)): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_finish_q', 'Завершити кампанію?', 'Завершить кампанию?', 'Finish campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="finished">
                                                <button type="submit" class="btn btn-sm btn-outline-dark">
                                                    <?= e(admin_reclama_t('admin_reclama_finish', 'Завершити', 'Завершить', 'Finish')) ?>
                                                </button>
                                            </form>

                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_cancel_q', 'Скасувати кампанію?', 'Отменить кампанию?', 'Cancel campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="canceled">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= e(admin_reclama_t('admin_reclama_cancel', 'Скасувати', 'Отменить', 'Cancel')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="card card-app mb-4">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <div>
                            <h2 class="h5 mb-0"><?= e(admin_reclama_t('admin_reclama_queue', 'Черга модерації', 'Очередь модерации', 'Moderation queue')) ?></h2>
                            <div class="text-muted small mt-1"><?= e(admin_reclama_t('admin_reclama_queue_hint', 'Тут показуються кампанії, які треба перевірити перед запуском.', 'Здесь показываются кампании, которые нужно проверить перед запуском.', 'Campaigns waiting for moderation are listed here.')) ?></div>
                        </div>
                    </div>

                    <?php if (!$queue): ?>
                        <div class="text-muted">
                            <?= e(admin_reclama_t('admin_reclama_queue_empty', 'Черга поки порожня.', 'Очередь пока пустая.', 'The moderation queue is empty.')) ?>
                        </div>
                    <?php else: ?>
                        <div class="d-grid gap-3">
                            <?php foreach ($queue as $row): ?>
                                <?php
                                $campaignId = (int)($row['id'] ?? 0);
                                $username   = trim((string)($row['username'] ?? ''));
                                $ownerLabel = $username !== '' ? '@' . $username : ('#' . (int)($row['user_id'] ?? 0));
                                $periodText = trim((string)($row['start_date'] ?? '')) . ' → ' . trim((string)($row['end_date'] ?? ''));
                                $status     = (string)($row['status'] ?? '');
                                $modStatus  = (string)($row['moderation_status'] ?? '');
                                $payStatus  = (string)($row['payment_status'] ?? '');
                                ?>
                                <div class="border rounded-3 p-3">
                                    <div class="d-flex flex-wrap align-items-start justify-content-between gap-3 mb-2">
                                        <div>
                                            <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                                <a class="fw-semibold text-decoration-none" href="<?= e(admin_reclama_campaign_url($campaignId)) ?>">
                                                    #<?= e((string)$campaignId) ?> — <?= e((string)($row['title'] ?? '')) ?>
                                                </a>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($status)) ?>">
                                                    <?= e(admin_reclama_label_status($status)) ?>
                                                </span>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($modStatus)) ?>">
                                                    <?= e(admin_reclama_label_moderation($modStatus)) ?>
                                                </span>
                                                <span class="badge text-bg-<?= e(admin_reclama_payment_badge($payStatus)) ?>">
                                                    <?= e(admin_reclama_label_payment($payStatus)) ?>
                                                </span>
                                            </div>
                                            <div class="text-muted small">
                                                <?= e((string)($row['campaign_type'] ?? '')) ?>
                                                <?php if ((int)($row['source_post_id'] ?? 0) > 0): ?>
                                                    · post #<?= e((string)($row['source_post_id'] ?? 0)) ?>
                                                <?php endif; ?>
                                                · <?= e($ownerLabel) ?>
                                            </div>
                                        </div>

                                        <div class="d-flex flex-wrap gap-2">
                                            <a href="<?= e(admin_reclama_campaign_url($campaignId)) ?>" class="btn btn-sm btn-outline-primary">
                                                <?= e(admin_reclama_t('admin_reclama_open', 'Відкрити', 'Открыть', 'Open')) ?>
                                            </a>

                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_delete_q', 'Повністю видалити цю кампанію?', 'Полностью удалить эту кампанию?', 'Permanently delete this campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="delete_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= e(admin_reclama_t('admin_reclama_delete', 'Видалити', 'Удалить', 'Delete')) ?>
                                                </button>
                                            </form>
                                        </div>
                                    </div>

                                    <div class="row g-3 mb-3">
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_period', 'Період', 'Период', 'Period')) ?></div>
                                            <div><?= e($periodText) ?></div>
                                            <div class="small text-muted mt-1">
                                                <?= e(admin_reclama_num((int)($row['days_count'] ?? 0))) ?> <?= e(admin_reclama_t('admin_reclama_days', 'дн.', 'дн.', 'days')) ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_budget', 'Бюджет', 'Бюджет', 'Budget')) ?></div>
                                            <div class="fw-semibold"><?= e(admin_reclama_money((int)($row['total_price'] ?? 0))) ?></div>
                                            <div class="small text-muted mt-1">
                                                <?= e(admin_reclama_num((int)($row['price_per_day'] ?? 0))) ?>/<?= e(admin_reclama_t('admin_reclama_day_1', 'день', 'день', 'day')) ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_target', 'Таргетинг', 'Таргетинг', 'Targeting')) ?></div>
                                            <div><?= e(admin_reclama_targeting_human($row)) ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex flex-wrap gap-2 align-items-start">
                                        <form method="post" action="/admin/reclama/campaigns.php" class="d-flex gap-2">
                                            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="moderate_campaign">
                                            <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                            <input type="hidden" name="mod_action" value="approved">
                                            <button type="submit" class="btn btn-sm btn-success">
                                                <?= e(admin_reclama_t('admin_reclama_approve', 'Схвалити', 'Одобрить', 'Approve')) ?>
                                            </button>
                                        </form>

                                        <form method="post" action="/admin/reclama/campaigns.php" class="d-flex gap-2 flex-wrap flex-md-nowrap">
                                            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="moderate_campaign">
                                            <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                            <input type="hidden" name="mod_action" value="rejected">
                                            <input
                                                type="text"
                                                name="note"
                                                class="form-control form-control-sm"
                                                maxlength="500"
                                                required
                                                placeholder="<?= e(admin_reclama_t('admin_reclama_reject_reason', 'Причина відхилення', 'Причина отклонения', 'Reject reason')) ?>"
                                            >
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <?= e(admin_reclama_t('admin_reclama_reject', 'Відхилити', 'Отклонить', 'Reject')) ?>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card card-app">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <h2 class="h5 mb-0"><?= e(admin_reclama_t('admin_reclama_recent', 'Останні кампанії', 'Последние кампании', 'Recent campaigns')) ?></h2>
                        <span class="text-muted small"><?= e(admin_reclama_t('admin_reclama_recent_hint', 'Останні 30 записів.', 'Последние 30 записей.', 'Latest 30 records.')) ?></span>
                    </div>

                    <?php if (!$recentCampaigns): ?>
                        <div class="text-muted">
                            <?= e(admin_reclama_t('admin_reclama_recent_empty', 'Кампаній поки немає.', 'Кампаний пока нет.', 'There are no campaigns yet.')) ?>
                        </div>
                    <?php else: ?>
                        <div class="d-grid gap-3">
                            <?php foreach ($recentCampaigns as $row): ?>
                                <?php
                                $campaignId = (int)($row['id'] ?? 0);
                                $username   = trim((string)($row['username'] ?? ''));
                                $ownerLabel = $username !== '' ? '@' . $username : ('#' . (int)($row['user_id'] ?? 0));
                                $status     = (string)($row['status'] ?? '');
                                $modStatus  = (string)($row['moderation_status'] ?? '');
                                $payStatus  = (string)($row['payment_status'] ?? '');
                                ?>
                                <div class="border rounded-3 p-3">
                                    <div class="d-flex flex-wrap align-items-start justify-content-between gap-3 mb-2">
                                        <div>
                                            <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                                <a class="fw-semibold text-decoration-none" href="<?= e(admin_reclama_campaign_url($campaignId)) ?>">
                                                    #<?= e((string)$campaignId) ?> — <?= e((string)($row['title'] ?? '')) ?>
                                                </a>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($status)) ?>">
                                                    <?= e(admin_reclama_label_status($status)) ?>
                                                </span>
                                                <span class="badge text-bg-<?= e(admin_reclama_status_badge($modStatus)) ?>">
                                                    <?= e(admin_reclama_label_moderation($modStatus)) ?>
                                                </span>
                                                <span class="badge text-bg-<?= e(admin_reclama_payment_badge($payStatus)) ?>">
                                                    <?= e(admin_reclama_label_payment($payStatus)) ?>
                                                </span>
                                            </div>
                                            <div class="small text-muted">
                                                <?= e((string)($row['campaign_type'] ?? '')) ?> · <?= e($ownerLabel) ?> · <?= e((string)($row['created_at'] ?? '')) ?>
                                            </div>
                                            <?php if (trim((string)($row['target_url'] ?? '')) !== ''): ?>
                                                <div class="small text-muted mt-1"><?= e(mb_strimwidth((string)$row['target_url'], 0, 90, '…')) ?></div>
                                            <?php endif; ?>
                                            <?php if (trim((string)($row['reject_reason'] ?? '')) !== ''): ?>
                                                <div class="small text-danger mt-1"><?= e((string)$row['reject_reason']) ?></div>
                                            <?php endif; ?>
                                        </div>

                                        <div class="d-flex flex-wrap gap-2">
                                            <a href="<?= e(admin_reclama_campaign_url($campaignId)) ?>" class="btn btn-sm btn-outline-primary">
                                                <?= e(admin_reclama_t('admin_reclama_open', 'Відкрити', 'Открыть', 'Open')) ?>
                                            </a>

                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_delete_q', 'Повністю видалити цю кампанію?', 'Полностью удалить эту кампанию?', 'Permanently delete this campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="delete_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= e(admin_reclama_t('admin_reclama_delete', 'Видалити', 'Удалить', 'Delete')) ?>
                                                </button>
                                            </form>
                                        </div>
                                    </div>

                                    <div class="row g-3 mb-3">
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_budget', 'Бюджет', 'Бюджет', 'Budget')) ?></div>
                                            <div class="fw-semibold"><?= e(admin_reclama_money((int)($row['total_price'] ?? 0))) ?></div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_period', 'Період', 'Период', 'Period')) ?></div>
                                            <div><?= e((string)($row['start_date'] ?? '')) ?> → <?= e((string)($row['end_date'] ?? '')) ?></div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="small text-muted mb-1"><?= e(admin_reclama_t('admin_reclama_col_target', 'Таргетинг', 'Таргетинг', 'Targeting')) ?></div>
                                            <div><?= e(admin_reclama_targeting_human($row)) ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex flex-wrap gap-2">
                                        <?php if (in_array($status, ['active', 'approved'], true)): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="paused">
                                                <button type="submit" class="btn btn-sm btn-outline-secondary">
                                                    <?= e(admin_reclama_t('admin_reclama_pause', 'Пауза', 'Пауза', 'Pause')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if ($status === 'paused'): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="resumed">
                                                <button type="submit" class="btn btn-sm btn-outline-success">
                                                    <?= e(admin_reclama_t('admin_reclama_resume', 'Відновити', 'Возобновить', 'Resume')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if (!in_array($status, ['finished', 'canceled'], true)): ?>
                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_finish_q', 'Завершити кампанію?', 'Завершить кампанию?', 'Finish campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="finished">
                                                <button type="submit" class="btn btn-sm btn-outline-dark">
                                                    <?= e(admin_reclama_t('admin_reclama_finish', 'Завершити', 'Завершить', 'Finish')) ?>
                                                </button>
                                            </form>

                                            <form method="post" action="/admin/reclama/campaigns.php" onsubmit="return confirm('<?= e(admin_reclama_t('admin_reclama_cancel_q', 'Скасувати кампанію?', 'Отменить кампанию?', 'Cancel campaign?')) ?>');">
                                                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                                <input type="hidden" name="action" value="moderate_campaign">
                                                <input type="hidden" name="campaign_id" value="<?= e((string)$campaignId) ?>">
                                                <input type="hidden" name="mod_action" value="canceled">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <?= e(admin_reclama_t('admin_reclama_cancel', 'Скасувати', 'Отменить', 'Cancel')) ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <?php if (function_exists('admin_sidebar')) admin_sidebar('reclama_campaigns'); ?>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>