<?php
declare(strict_types=1);

/**
 * /functional/board/create.php
 * Створення оголошення
 */

require_once dirname(__DIR__, 2) . '/includes/start.php';
require_once __DIR__ . '/_lib.php';

$pdo = brd_db();
$me  = brd_require_login();

$settings = brd_load_settings($pdo);

if (!brd_ready($pdo)) {
    http_response_code(500);
    echo 'Board module tables were not found. Run SQL migration first.';
    exit;
}

if (($settings['board_enabled'] ?? '1') !== '1' && !brd_is_admin($me)) {
    http_response_code(404);
    exit('Board is disabled.');
}

$countryCode = brd_detect_country_code($me, $settings);
$categories = brd_categories($pdo);
$regions = brd_regions($pdo, $countryCode);

$ad = [
    'title' => '',
    'description' => '',
    'price_amount' => '0.00',
    'category_id' => 0,
    'region_id' => 0,
    'region_name' => '',
    'city_name' => trim((string)($me['city'] ?? '')),
    'contact_name' => trim((string)($me['full_name'] ?? '')),
    'contact_phone' => trim((string)($me['phone'] ?? '')),
    'contact_email' => trim((string)($me['email'] ?? '')),
    'contact_telegram' => '',
];

$flashError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ad['title'] = brd_trimmed($_POST['title'] ?? '');
    $ad['description'] = brd_trimmed($_POST['description'] ?? '');
    $ad['price_amount'] = brd_price_to_decimal($_POST['price_amount'] ?? '0');
    $ad['category_id'] = (int)($_POST['category_id'] ?? 0);
    $ad['region_id'] = (int)($_POST['region_id'] ?? 0);
    $ad['region_name'] = brd_trimmed($_POST['region_name'] ?? '');
    $ad['city_name'] = brd_trimmed($_POST['city_name'] ?? '');
    $ad['contact_name'] = brd_trimmed($_POST['contact_name'] ?? '');
    $ad['contact_phone'] = brd_phone_norm($_POST['contact_phone'] ?? '');
    $ad['contact_email'] = brd_trimmed($_POST['contact_email'] ?? '');
    $ad['contact_telegram'] = brd_trimmed($_POST['contact_telegram'] ?? '');

    $action = (string)($_POST['action'] ?? 'save_draft');
    if (!in_array($action, ['save_draft', 'submit'], true)) {
        $action = 'save_draft';
    }

    try {
        if (!brd_csrf_check($_POST['csrf'] ?? null)) {
            throw new RuntimeException(brd_t(
                'Помилка безпеки. Оновіть сторінку.',
                'Ошибка безопасности. Обновите страницу.',
                'Security error. Refresh the page.'
            ));
        }

        if ($ad['title'] === '' || mb_strlen($ad['title']) < 5) {
            throw new RuntimeException(brd_t(
                'Заголовок має містити щонайменше 5 символів.',
                'Заголовок должен содержать минимум 5 символов.',
                'Title must contain at least 5 characters.'
            ));
        }

        if ($ad['description'] === '' || mb_strlen($ad['description']) < 20) {
            throw new RuntimeException(brd_t(
                'Опис має містити щонайменше 20 символів.',
                'Описание должно содержать минимум 20 символов.',
                'Description must contain at least 20 characters.'
            ));
        }

        if ((int)$ad['category_id'] <= 0) {
            throw new RuntimeException(brd_t(
                'Оберіть категорію.',
                'Выберите категорию.',
                'Choose a category.'
            ));
        }

        if ($ad['city_name'] === '') {
            throw new RuntimeException(brd_t(
                'Вкажіть місто.',
                'Укажите город.',
                'Specify city.'
            ));
        }

        if ($ad['region_id'] > 0) {
            $ad['region_name'] = brd_region_name_by_id($pdo, (int)$ad['region_id']);
        }

        if ($ad['contact_phone'] === '' && $ad['contact_email'] === '' && $ad['contact_telegram'] === '') {
            throw new RuntimeException(brd_t(
                'Вкажіть хоча б один контакт: телефон, email або Telegram.',
                'Укажите хотя бы один контакт: телефон, email или Telegram.',
                'Specify at least one contact: phone, email or Telegram.'
            ));
        }

        if (
            !isset($_FILES['main_image']) ||
            (int)($_FILES['main_image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
        ) {
            throw new RuntimeException(brd_t(
                'Головне фото є обовʼязковим.',
                'Главное фото обязательно.',
                'Main image is required.'
            ));
        }

        $galleryFiles = brd_normalize_files_array($_FILES['gallery_images'] ?? []);
        $realGalleryFiles = [];
        foreach ($galleryFiles as $f) {
            if ((int)($f['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            $realGalleryFiles[] = $f;
        }
        if (count($realGalleryFiles) > 10) {
            throw new RuntimeException(brd_t(
                'Можна завантажити максимум 10 додаткових фото.',
                'Можно загрузить максимум 10 дополнительных фото.',
                'You can upload up to 10 additional images.'
            ));
        }

        $publishPrice = max(0, (int)($settings['board_publish_price'] ?? 25));
        $status = ($action === 'submit') ? 'pending' : 'draft';
        $paymentStatus = ($action === 'submit') ? 'paid' : 'unpaid';
        $paidAt = ($action === 'submit') ? date('Y-m-d H:i:s') : null;

        $pdo->beginTransaction();

        $st = $pdo->prepare("
            INSERT INTO board_ads
                (user_id, category_id, title, description, price_amount, currency_code,
                 contact_name, contact_phone, contact_email, contact_telegram,
                 country_code, region_id, region_name, city_name,
                 status, payment_status, publish_price, paid_at,
                 created_at, updated_at)
            VALUES
                (?, ?, ?, ?, ?, 'UAH',
                 ?, ?, ?, ?,
                 ?, ?, ?, ?,
                 ?, ?, ?, ?,
                 NOW(), NOW())
        ");
        $st->execute([
            (int)$me['id'],
            (int)$ad['category_id'],
            $ad['title'],
            $ad['description'],
            $ad['price_amount'],
            $ad['contact_name'] !== '' ? $ad['contact_name'] : null,
            $ad['contact_phone'] !== '' ? $ad['contact_phone'] : null,
            $ad['contact_email'] !== '' ? $ad['contact_email'] : null,
            $ad['contact_telegram'] !== '' ? $ad['contact_telegram'] : null,
            $countryCode,
            (int)$ad['region_id'] > 0 ? (int)$ad['region_id'] : null,
            $ad['region_name'] !== '' ? $ad['region_name'] : null,
            $ad['city_name'],
            $status,
            $paymentStatus,
            $action === 'submit' ? $publishPrice : 0,
            $paidAt,
        ]);

        $adId = (int)$pdo->lastInsertId();
        brd_log_moderation($pdo, $adId, null, 'created', 'Created by user');

        $dirs = brd_ad_dirs($me, $adId);

        $mainInfo = brd_store_uploaded_image($_FILES['main_image'], $dirs['main_fs'], $dirs['main_rel']);
        $upMain = $pdo->prepare("
            UPDATE board_ads
            SET main_image_path = ?, main_image_original_name = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $upMain->execute([
            $mainInfo['rel_path'],
            $mainInfo['original_name'],
            $adId,
        ]);

        if ($realGalleryFiles) {
            $insImg = $pdo->prepare("
                INSERT INTO board_ad_images
                    (ad_id, rel_path, original_name, mime, size_bytes, width, height, sort_order, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $sort = 1;
            foreach ($realGalleryFiles as $file) {
                $img = brd_store_uploaded_image($file, $dirs['gallery_fs'], $dirs['gallery_rel']);
                $insImg->execute([
                    $adId,
                    $img['rel_path'],
                    $img['original_name'],
                    $img['mime'],
                    (int)$img['size_bytes'],
                    (int)$img['width'],
                    (int)$img['height'],
                    $sort++,
                ]);
            }
        }

        if ($action === 'submit') {
            $charge = brd_charge_user_coins(
                $pdo,
                (int)$me['id'],
                $publishPrice,
                'board_ad',
                $adId,
                'board_publish',
                'Board ad publish payment',
                ['board_ad_id' => $adId, 'price' => $publishPrice]
            );

            if (empty($charge['ok'])) {
                throw new RuntimeException((string)($charge['message'] ?? 'VM Coins error.'));
            }

            brd_log_moderation($pdo, $adId, null, 'submitted', 'Submitted by user');
        }

        $pdo->commit();

        brd_flash_set(
            'board_my',
            'success',
            $action === 'submit'
                ? brd_t('Оголошення надіслано на модерацію.', 'Объявление отправлено на модерацию.', 'The ad was submitted for moderation.')
                : brd_t('Чернетку збережено.', 'Черновик сохранен.', 'Draft saved.')
        );
        brd_redirect('/functional/board/my.php');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $flashError = $e->getMessage();
    }
}

$pageTitle = brd_t('Нове оголошення', 'Новое объявление', 'New ad');
$formAction = '/functional/board/create.php';
$additionalImages = [];
$maxAdditional = 10;
$isEdit = false;

require dirname(__DIR__, 2) . '/includes/header.php';
require __DIR__ . '/_form.php';
require dirname(__DIR__, 2) . '/includes/footer.php';
