<?php
declare(strict_types=1);

/**
 * /functional/reclama/edit.php
 * Відповідає за:
 * - редагування кампанії власником
 * - оновлення дат, таргетингу, банерів і поста
 * - повторну відправку на модерацію
 * - stage 8:
 *   - exclude countries
 *   - auth scope: all / guests / users
 *   - segment codes
 */

require_once __DIR__ . '/_bootstrap.php';

$campaignId = max(0, (int)($_GET['id'] ?? $_POST['id'] ?? 0));
$campaign = rc_get_campaign_full($pdo, $campaignId, $meId);

if (!$campaign) {
    rc_flash_set('error', rc_t('Кампанію не знайдено.', 'Кампания не найдена.', 'Campaign not found.'));
    rc_redirect('/functional/reclama/my.php');
}

if (!reclama_user_can_edit($campaign, $meId)) {
    rc_flash_set('error', rc_t('Цю кампанію зараз не можна редагувати.', 'Эту кампанию сейчас нельзя редактировать.', 'This campaign cannot be edited right now.'));
    rc_redirect('/functional/reclama/view.php?id=' . $campaignId);
}

if (!function_exists('rc_edit_upload_abs_path')) {
    function rc_edit_upload_abs_path(string $relativePath): ?string
    {
        $relativePath = trim($relativePath);
        if ($relativePath === '' || $relativePath === '/' || str_contains($relativePath, '..')) {
            return null;
        }

        $root = dirname(__DIR__, 2);
        $abs  = $root . '/' . ltrim(str_replace('\\', '/', $relativePath), '/');
        return is_file($abs) ? $abs : null;
    }
}

if (!function_exists('rc_edit_safe_unlink')) {
    function rc_edit_safe_unlink(string $relativePath): void
    {
        $abs = rc_edit_upload_abs_path($relativePath);
        if ($abs === null) {
            return;
        }

        try {
            @unlink($abs);
        } catch (Throwable $e) {
            // do not break edit flow
        }
    }
}

if (!function_exists('rc_edit_uploaded_now')) {
    function rc_edit_uploaded_now(array|null $file): bool
    {
        if (!is_array($file)) {
            return false;
        }

        return isset($file['error']) && (int)$file['error'] !== UPLOAD_ERR_NO_FILE;
    }
}

$pageTitle = rc_t('Редагування кампанії', 'Редактирование кампании', 'Edit campaign');
if (function_exists('seo_set')) {
    seo_set([
        'title'     => $pageTitle,
        'robots'    => 'noindex,follow',
        'canonical' => '/functional/reclama/edit.php?id=' . $campaignId,
    ]);
}

$form = array_merge(rc_campaign_form_defaults($pdo), [
    'campaign_type'                => (string)($campaign['campaign_type'] ?? 'post'),
    'title'                        => (string)($campaign['title'] ?? ''),
    'source_post_id'               => (string)($campaign['source_post_id'] ?? ''),
    'target_url'                   => (string)($campaign['target_url'] ?? ''),
    'start_date'                   => (string)($campaign['start_date'] ?? ''),
    'end_date'                     => (string)($campaign['end_date'] ?? ''),
    'desktop_banner_path'          => (string)($campaign['desktop_banner_path'] ?? ''),
    'mobile_banner_path'           => (string)($campaign['mobile_banner_path'] ?? ''),
    'desktop_banner_original_name' => (string)($campaign['desktop_banner_original_name'] ?? ''),
    'mobile_banner_original_name'  => (string)($campaign['mobile_banner_original_name'] ?? ''),
    'delete_desktop_banner'        => '',
    'delete_mobile_banner'         => '',
    'country_code'                 => (string)($campaign['country_code'] ?? ''),
    'exclude_countries'            => (string)($campaign['exclude_countries'] ?? ''),
    'city'                         => (string)($campaign['city'] ?? ''),
    'gender'                       => (string)($campaign['gender'] ?? 'any'),
    'age_from'                     => $campaign['age_from'] === null ? '' : (string)$campaign['age_from'],
    'age_to'                       => $campaign['age_to'] === null ? '' : (string)$campaign['age_to'],
    'lang_code'                    => (string)($campaign['lang_code'] ?? 'any'),
    'device_type'                  => (string)($campaign['device_type'] ?? 'all'),
    'auth_scope'                   => (string)($campaign['auth_scope'] ?? 'all'),
    'segment_codes'                => (string)($campaign['segment_codes'] ?? ''),
]);

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!rc_csrf_ok((string)($_POST['csrf'] ?? ''))) {
        $errors[] = rc_t('Недійсний CSRF-токен.', 'Недействительный CSRF-токен.', 'Invalid CSRF token.');
    } else {
        $form = rc_collect_campaign_input($_POST, $form);
        $form['delete_desktop_banner'] = isset($_POST['delete_desktop_banner']) ? '1' : '';
        $form['delete_mobile_banner']  = isset($_POST['delete_mobile_banner']) ? '1' : '';

        $submit            = isset($_POST['submit_for_moderation']);
        $desktopUpload     = $_FILES['desktop_banner'] ?? null;
        $mobileUpload      = $_FILES['mobile_banner'] ?? null;
        $newDesktopNow     = rc_edit_uploaded_now(is_array($desktopUpload) ? $desktopUpload : null);
        $newMobileNow      = rc_edit_uploaded_now(is_array($mobileUpload) ? $mobileUpload : null);
        $deleteDesktopNow  = $form['delete_desktop_banner'] === '1';
        $deleteMobileNow   = $form['delete_mobile_banner'] === '1';
        $resultingType     = trim((string)($form['campaign_type'] ?? ($campaign['campaign_type'] ?? 'post')));
        $oldDesktopPath    = trim((string)($campaign['desktop_banner_path'] ?? ''));
        $oldMobilePath     = trim((string)($campaign['mobile_banner_path'] ?? ''));

        if ($resultingType === 'banner' && $deleteDesktopNow && !$newDesktopNow) {
            $errors[] = rc_t(
                'Для банерної кампанії не можна видалити desktop-банер без завантаження нового.',
                'Для баннерной кампании нельзя удалить desktop-баннер без загрузки нового.',
                'A banner campaign cannot remove its desktop banner without uploading a new one.'
            );
        }

        if (!$errors) {
            $save = rc_save_campaign($pdo, $me, $form, [
                'desktop_banner' => $desktopUpload,
                'mobile_banner'  => $mobileUpload,
            ], $submit, $campaign);

            if (!($save['ok'] ?? false)) {
                $errors = array_merge($errors, (array)($save['errors'] ?? [rc_t('Не вдалося оновити кампанію.', 'Не удалось обновить кампанию.', 'Failed to update campaign.')]));
            } else {
                $savedCampaignId   = (int)($save['campaign_id'] ?? $campaignId);
                $cleanupPerformed  = false;

                if ($deleteDesktopNow || $deleteMobileNow || $newDesktopNow || $newMobileNow) {
                    $savedCampaign = rc_get_campaign_full($pdo, $savedCampaignId, $meId);
                    if (!$savedCampaign) {
                        $savedCampaign = $campaign;
                    }

                    $updates = [];
                    $bind    = [];

                    if ($deleteDesktopNow && !$newDesktopNow) {
                        $updates[] = 'desktop_banner_path = NULL';
                        if (reclama_column_exists($pdo, 'reclama_campaigns', 'desktop_banner_original_name')) {
                            $updates[] = "desktop_banner_original_name = ''";
                        }
                    }

                    if ($deleteMobileNow && !$newMobileNow) {
                        $updates[] = 'mobile_banner_path = NULL';
                        if (reclama_column_exists($pdo, 'reclama_campaigns', 'mobile_banner_original_name')) {
                            $updates[] = "mobile_banner_original_name = ''";
                        }
                    }

                    if ($updates) {
                        $sql = 'UPDATE reclama_campaigns SET ' . implode(', ', $updates) . ', updated_at = NOW() WHERE id = ? AND user_id = ? LIMIT 1';
                        $st  = $pdo->prepare($sql);
                        $st->execute([$savedCampaignId, $meId]);
                        $cleanupPerformed = true;
                    }

                    $savedDesktopPath = trim((string)($savedCampaign['desktop_banner_path'] ?? ''));
                    $savedMobilePath  = trim((string)($savedCampaign['mobile_banner_path'] ?? ''));

                    if ($oldDesktopPath !== '' && (($newDesktopNow && $oldDesktopPath !== $savedDesktopPath) || ($deleteDesktopNow && !$newDesktopNow))) {
                        rc_edit_safe_unlink($oldDesktopPath);
                        $cleanupPerformed = true;
                    }

                    if ($oldMobilePath !== '' && (($newMobileNow && $oldMobilePath !== $savedMobilePath) || ($deleteMobileNow && !$newMobileNow))) {
                        rc_edit_safe_unlink($oldMobilePath);
                        $cleanupPerformed = true;
                    }
                }

                rc_flash_set(
                    'success',
                    ($submit
                        ? rc_t('Кампанію оновлено і відправлено на модерацію.', 'Кампания обновлена и отправлена на модерацию.', 'The campaign was updated and submitted for moderation.')
                        : rc_t('Кампанію оновлено.', 'Кампания обновлена.', 'The campaign was updated.'))
                    . ($cleanupPerformed
                        ? ' ' . rc_t('Старі банери оновлено або видалено.', 'Старые баннеры обновлены или удалены.', 'Old banner files were updated or removed.')
                        : '')
                );
                rc_redirect('/functional/reclama/view.php?id=' . $savedCampaignId);
            }
        }
    }
}

$posts        = rc_user_posts($pdo, $meId, 50);
$pricePerDay  = reclama_price_per_day($pdo);
$minDays      = reclama_min_days($pdo);
$maxDays      = reclama_max_days($pdo);
$userBalance  = reclama_get_user_balance($pdo, $meId);
$previewDays  = reclama_calc_days((string)($form['start_date'] ?? ''), (string)($form['end_date'] ?? ''));
$previewTotal = reclama_calc_total($previewDays, $pricePerDay);
$previewShort = max(0, $previewTotal - $userBalance);

require_once __DIR__ . '/../../includes/header.php';
require __DIR__ . '/_edit_form.php';
require_once __DIR__ . '/../../includes/footer.php';