<?php
declare(strict_types=1);

/**
 * Variables expected:
 * $pageTitle, $formAction, $ad, $categories, $regions, $countryCode, $flashError, $maxAdditional, $additionalImages, $isEdit
 */
$additionalImages = is_array($additionalImages ?? null) ? $additionalImages : [];
$maxAdditional = (int)($maxAdditional ?? 10);
$isEdit = !empty($isEdit);
?>
<div class="container my-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
        <h1 class="h3 m-0"><?= brd_h((string)$pageTitle) ?></h1>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-secondary" href="/functional/board/my.php"><?= brd_h(brd_t('Мої оголошення', 'Мои объявления', 'My ads')) ?></a>
            <a class="btn btn-outline-secondary" href="/board.php"><?= brd_h(brd_t('До каталогу', 'К каталогу', 'To catalog')) ?></a>
        </div>
    </div>

    <?php if (!empty($flashError)): ?>
        <div class="alert alert-danger"><?= brd_h((string)$flashError) ?></div>
    <?php endif; ?>

    <div class="card card-app p-3">
        <form method="post" action="<?= brd_h((string)$formAction) ?>" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="csrf" value="<?= brd_h(brd_csrf_token()) ?>">

            <div class="col-lg-8">
                <label class="form-label"><?= brd_h(brd_t('Заголовок', 'Заголовок', 'Title')) ?></label>
                <input type="text" name="title" maxlength="180" class="form-control" required value="<?= brd_h((string)($ad['title'] ?? '')) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Категорія', 'Категория', 'Category')) ?></label>
                <select name="category_id" class="form-select" required>
                    <option value="0"><?= brd_h(brd_t('Оберіть категорію', 'Выберите категорию', 'Choose category')) ?></option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= (int)$cat['id'] ?>" <?= ((int)$cat['id'] === (int)($ad['category_id'] ?? 0) ? 'selected' : '') ?>>
                            <?= brd_h((string)$cat['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-12">
                <label class="form-label"><?= brd_h(brd_t('Опис', 'Описание', 'Description')) ?></label>
                <textarea name="description" class="form-control" rows="7" required><?= brd_h((string)($ad['description'] ?? '')) ?></textarea>
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Вартість', 'Стоимость', 'Price')) ?></label>
                <input type="text" name="price_amount" class="form-control" value="<?= brd_h((string)($ad['price_amount'] ?? '0.00')) ?>" placeholder="0.00">
                <div class="form-text"><?= brd_h(brd_t('Для безкоштовних оголошень можна вказати 0.', 'Для бесплатных объявлений можно указать 0.', 'Use 0 for free items.')) ?></div>
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Країна', 'Страна', 'Country')) ?></label>
                <input type="text" class="form-control" value="<?= brd_h($countryCode) ?>" disabled>
                <input type="hidden" name="country_code" value="<?= brd_h($countryCode) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Регіон', 'Регион', 'Region')) ?></label>
                <?php if ($regions): ?>
                    <select name="region_id" class="form-select">
                        <option value="0"><?= brd_h(brd_t('Оберіть регіон', 'Выберите регион', 'Choose region')) ?></option>
                        <?php foreach ($regions as $region): ?>
                            <option value="<?= (int)$region['id'] ?>" <?= ((int)$region['id'] === (int)($ad['region_id'] ?? 0) ? 'selected' : '') ?>>
                                <?= brd_h((string)$region['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <input type="hidden" name="region_name" value="">
                <?php else: ?>
                    <input type="text" name="region_name" class="form-control" value="<?= brd_h((string)($ad['region_name'] ?? '')) ?>">
                    <input type="hidden" name="region_id" value="0">
                <?php endif; ?>
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Місто', 'Город', 'City')) ?></label>
                <input type="text" name="city_name" class="form-control" required value="<?= brd_h((string)($ad['city_name'] ?? '')) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Контактне імʼя', 'Контактное имя', 'Contact name')) ?></label>
                <input type="text" name="contact_name" class="form-control" value="<?= brd_h((string)($ad['contact_name'] ?? '')) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Телефон', 'Телефон', 'Phone')) ?></label>
                <input type="text" name="contact_phone" class="form-control" value="<?= brd_h((string)($ad['contact_phone'] ?? '')) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Email', 'Email', 'Email')) ?></label>
                <input type="email" name="contact_email" class="form-control" value="<?= brd_h((string)($ad['contact_email'] ?? '')) ?>">
            </div>

            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Telegram', 'Telegram', 'Telegram')) ?></label>
                <input type="text" name="contact_telegram" class="form-control" value="<?= brd_h((string)($ad['contact_telegram'] ?? '')) ?>" placeholder="@username">
            </div>

            <div class="col-lg-8">
                <label class="form-label"><?= brd_h(brd_t('Головне фото', 'Главное фото', 'Main image')) ?></label>
                <input type="file" name="main_image" accept="image/*" class="form-control" <?= $isEdit ? '' : 'required' ?>>
                <?php if ($isEdit && trim((string)($ad['main_image_path'] ?? '')) !== ''): ?>
                    <div class="mt-2">
                        <img src="<?= brd_h((string)$ad['main_image_path']) ?>" alt="" style="max-width:220px;max-height:160px;object-fit:cover;" class="rounded border">
                    </div>
                <?php endif; ?>
            </div>

            <div class="col-12">
                <label class="form-label"><?= brd_h(brd_t('Додаткові фото (до 10)', 'Дополнительные фото (до 10)', 'Additional images (up to 10)')) ?></label>
                <input type="file" name="gallery_images[]" accept="image/*" multiple class="form-control">
                <div class="form-text">
                    <?= brd_h(brd_t(
                        'Додаткові фото не обовʼязкові. Максимум 10 штук.',
                        'Дополнительные фото необязательны. Максимум 10 штук.',
                        'Additional images are optional. Maximum 10 files.'
                    )) ?>
                </div>
            </div>

            <?php if ($isEdit && $additionalImages): ?>
                <div class="col-12">
                    <div class="fw-semibold mb-2"><?= brd_h(brd_t('Поточні додаткові фото', 'Текущие дополнительные фото', 'Current additional images')) ?></div>
                    <div class="row g-3">
                        <?php foreach ($additionalImages as $img): ?>
                            <div class="col-md-4 col-xl-3">
                                <div class="border rounded p-2 h-100">
                                    <img src="<?= brd_h((string)$img['rel_path']) ?>" alt="" class="img-fluid rounded mb-2" style="width:100%;height:160px;object-fit:cover;">
                                    <label class="form-check">
                                        <input class="form-check-input" type="checkbox" name="delete_image_ids[]" value="<?= (int)$img['id'] ?>">
                                        <span class="form-check-label"><?= brd_h(brd_t('Видалити', 'Удалить', 'Delete')) ?></span>
                                    </label>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div class="col-12 d-flex flex-wrap gap-2 mt-3">
                <button type="submit" name="action" value="save_draft" class="btn btn-outline-secondary">
                    <?= brd_h(brd_t('Зберегти як чернетку', 'Сохранить как черновик', 'Save as draft')) ?>
                </button>

                <button type="submit" name="action" value="submit" class="btn btn-primary">
                    <?= brd_h(brd_t('Надіслати на модерацію', 'Отправить на модерацию', 'Submit for moderation')) ?>
                </button>
            </div>
        </form>
    </div>
</div>
