<?php
declare(strict_types=1);

/**
 * /functional/board/edit.php
 * Редагування оголошення
 */

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

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

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

$settings = brd_load_settings($pdo);
$adId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$ad = brd_load_ad($pdo, $adId);

if (!$ad || !brd_owner_can_edit($ad, $me) || (string)($ad['status'] ?? '') === 'deleted') {
    http_response_code(404);
    exit('Ad not found.');
}

$countryCode = brd_detect_country_code($me, $settings);
$categories = brd_categories($pdo);
$regions = brd_regions($pdo, $countryCode);
$additionalImages = brd_ad_images($pdo, $adId);
$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.'
            ));
        }

        $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;
        }

        $deleteImageIds = array_map('intval', (array)($_POST['delete_image_ids'] ?? []));
        $currentGalleryCount = brd_count_additional_images($pdo, $adId);
        $futureGalleryCount = $currentGalleryCount - count($deleteImageIds) + count($realGalleryFiles);

        if ($futureGalleryCount > 10) {
            throw new RuntimeException(brd_t(
                'Після оновлення в оголошенні може бути максимум 10 додаткових фото.',
                'После обновления в объявлении может быть максимум 10 дополнительных фото.',
                'After update the ad can have up to 10 additional images.'
            ));
        }

        $alreadyPaid = ((string)($ad['payment_status'] ?? 'unpaid') === 'paid');
        $publishPrice = max(0, (int)($settings['board_publish_price'] ?? 25));
        $newStatus = ($action === 'submit') ? 'pending' : 'draft';
        $newPaymentStatus = $alreadyPaid ? 'paid' : (($action === 'submit') ? 'paid' : 'unpaid');
        $newPaidAt = $alreadyPaid ? ($ad['paid_at'] ?? date('Y-m-d H:i:s')) : (($action === 'submit') ? date('Y-m-d H:i:s') : null);
        $newPublishPrice = $alreadyPaid ? (int)($ad['publish_price'] ?? $publishPrice) : (($action === 'submit') ? $publishPrice : 0);

        $pdo->beginTransaction();

        $up = $pdo->prepare("
            UPDATE board_ads
            SET category_id = ?,
                title = ?,
                description = ?,
                price_amount = ?,
                contact_name = ?,
                contact_phone = ?,
                contact_email = ?,
                contact_telegram = ?,
                country_code = ?,
                region_id = ?,
                region_name = ?,
                city_name = ?,
                status = ?,
                payment_status = ?,
                publish_price = ?,
                paid_at = ?,
                approved_at = NULL,
                approved_by_user_id = NULL,
                rejected_at = NULL,
                rejected_by_user_id = NULL,
                moderation_note = NULL,
                published_at = CASE WHEN ? = 'approved' THEN published_at ELSE published_at END,
                updated_at = NOW()
            WHERE id = ?
        ");
        $up->execute([
            (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'],
            $newStatus,
            $newPaymentStatus,
            $newPublishPrice,
            $newPaidAt,
            $newStatus,
            $adId,
        ]);

        brd_log_moderation($pdo, $adId, null, 'edited', 'Updated by user');

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

        if (isset($_FILES['main_image']) && (int)($_FILES['main_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
            $newMain = brd_store_uploaded_image($_FILES['main_image'], $dirs['main_fs'], $dirs['main_rel']);
            brd_delete_rel_file((string)($ad['main_image_path'] ?? ''));

            $upMain = $pdo->prepare("
                UPDATE board_ads
                SET main_image_path = ?, main_image_original_name = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $upMain->execute([
                $newMain['rel_path'],
                $newMain['original_name'],
                $adId,
            ]);
            $ad['main_image_path'] = $newMain['rel_path'];
        }

        if ($deleteImageIds) {
            $selDel = $pdo->prepare("
                SELECT id, rel_path
                FROM board_ad_images
                WHERE ad_id = ?
                  AND id = ?
                LIMIT 1
            ");
            $del = $pdo->prepare("DELETE FROM board_ad_images WHERE ad_id = ? AND id = ?");

            foreach ($deleteImageIds as $imgId) {
                if ($imgId <= 0) {
                    continue;
                }
                $selDel->execute([$adId, $imgId]);
                $row = $selDel->fetch(PDO::FETCH_ASSOC);
                if ($row) {
                    brd_delete_rel_file((string)$row['rel_path']);
                    $del->execute([$adId, $imgId]);
                }
            }
        }

        if ($realGalleryFiles) {
            $sortStart = brd_count_additional_images($pdo, $adId) + 1;
            $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())
            ");

            foreach ($realGalleryFiles as $idx => $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'],
                    $sortStart + $idx,
                ]);
            }
        }

        if ($action === 'submit' && !$alreadyPaid) {
            $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.'));
            }
        }

        if ($action === 'submit') {
            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 updated and submitted for moderation.')
                : brd_t('Чернетку оновлено.', 'Черновик обновлен.', 'Draft updated.')
        );

        brd_redirect('/functional/board/my.php');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $flashError = $e->getMessage();
    }

    $ad = brd_load_ad($pdo, $adId) ?: $ad;
    $additionalImages = brd_ad_images($pdo, $adId);
}

$pageTitle = brd_t('Редагувати оголошення', 'Редактировать объявление', 'Edit ad');
$formAction = '/functional/board/edit.php?id=' . $adId;
$maxAdditional = 10;
$isEdit = true;

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