<?php
declare(strict_types=1);

/**
 * /functional/board/my.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;
}

[$flashType, $flashText] = brd_flash_get('board_my');

$statusFilter = brd_trimmed($_GET['status'] ?? '');
$allowedStatuses = ['draft', 'pending', 'approved', 'rejected', 'archived', 'deleted'];
if ($statusFilter !== '' && !in_array($statusFilter, $allowedStatuses, true)) {
    $statusFilter = '';
}

$where = ['a.user_id = ?'];
$params = [(int)$me['id']];

if ($statusFilter !== '') {
    $where[] = 'a.status = ?';
    $params[] = $statusFilter;
}

$sql = "
    SELECT
        a.*,
        " . (brd_lang() === 'ru' ? 'c.name_ru' : (brd_lang() === 'en' ? 'c.name_en' : 'c.name_uk')) . " AS category_name
    FROM board_ads a
    LEFT JOIN board_categories c ON c.id = a.category_id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY a.updated_at DESC, a.id DESC
";

$rows = [];
try {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $rows = [];
}

$title = brd_t('Мої оголошення', 'Мои объявления', 'My ads');
$meta_desc = $title;

require dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="container my-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
        <div>
            <h1 class="h3 m-0"><?= brd_h($title) ?></h1>
            <div class="text-muted"><?= brd_h(brd_t('Керуйте своїми оголошеннями, модерацією та статистикою.', 'Управляйте своими объявлениями, модерацией и статистикой.', 'Manage your ads, moderation and statistics.')) ?></div>
        </div>
        <div class="d-flex gap-2">
            <a class="btn btn-primary" href="/functional/board/create.php"><?= brd_h(brd_t('Нове оголошення', 'Новое объявление', 'New ad')) ?></a>
            <a class="btn btn-outline-secondary" href="/board.php"><?= brd_h(brd_t('Каталог', 'Каталог', 'Catalog')) ?></a>
        </div>
    </div>

    <?php if ($flashType !== '' && $flashText !== ''): ?>
        <div class="alert alert-<?= brd_h($flashType) ?>"><?= brd_h($flashText) ?></div>
    <?php endif; ?>

    <div class="card card-app p-3 mb-3">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <label class="form-label"><?= brd_h(brd_t('Статус', 'Статус', 'Status')) ?></label>
                <select name="status" class="form-select">
                    <option value=""><?= brd_h(brd_t('Усі', 'Все', 'All')) ?></option>
                    <?php foreach ($allowedStatuses as $st): ?>
                        <option value="<?= brd_h($st) ?>" <?= ($statusFilter === $st ? 'selected' : '') ?>>
                            <?= brd_h(brd_status_label($st)) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-12 d-flex gap-2">
                <button class="btn btn-outline-primary"><?= brd_h(brd_t('Застосувати', 'Применить', 'Apply')) ?></button>
                <a class="btn btn-outline-secondary" href="/functional/board/my.php"><?= brd_h(brd_t('Скинути', 'Сбросить', 'Reset')) ?></a>
            </div>
        </form>
    </div>

    <?php if (!$rows): ?>
        <div class="alert alert-light border">
            <?= brd_h(brd_t('У вас ще немає оголошень.', 'У вас ещё нет объявлений.', 'You have no ads yet.')) ?>
        </div>
    <?php else: ?>
        <div class="vstack gap-3">
            <?php foreach ($rows as $row): ?>
                <?php
                $status = (string)$row['status'];
                $badgeClass = brd_status_badge_class($status);
                $rejectNote = trim((string)($row['moderation_note'] ?? ''));
                ?>
                <div class="card card-app p-3">
                    <div class="d-flex flex-wrap gap-3 justify-content-between">
                        <div class="d-flex gap-3">
                            <?php if (trim((string)($row['main_image_path'] ?? '')) !== ''): ?>
                                <img src="<?= brd_h((string)$row['main_image_path']) ?>" alt="" style="width:140px;height:100px;object-fit:cover;" class="rounded border">
                            <?php endif; ?>
                            <div>
                                <div class="d-flex flex-wrap gap-2 align-items-center mb-1">
                                    <a class="fw-semibold text-decoration-none" href="<?= brd_h(brd_ad_url((int)$row['id'])) ?>">
                                        <?= brd_h((string)$row['title']) ?>
                                    </a>
                                    <span class="badge bg-<?= brd_h($badgeClass) ?>"><?= brd_h(brd_status_label($status)) ?></span>
                                    <?php if (trim((string)($row['category_name'] ?? '')) !== ''): ?>
                                        <span class="badge bg-light text-dark border"><?= brd_h((string)$row['category_name']) ?></span>
                                    <?php endif; ?>
                                </div>

                                <div class="text-muted small mb-1">
                                    <?= brd_h((string)$row['region_name']) ?>
                                    <?= ((string)$row['city_name'] !== '' ? brd_h(', ' . (string)$row['city_name']) : '') ?>
                                </div>

                                <div class="small">
                                    <strong><?= brd_h(brd_t('Перегляди', 'Просмотры', 'Views')) ?>:</strong>
                                    <?= (int)($row['total_views'] ?? 0) ?>
                                    ·
                                    <strong><?= brd_h(brd_t('Унікальні', 'Уникальные', 'Unique')) ?>:</strong>
                                    <?= (int)($row['unique_views'] ?? 0) ?>
                                    ·
                                    <strong><?= brd_h(brd_t('Сплачено', 'Оплачено', 'Paid')) ?>:</strong>
                                    <?= (string)($row['payment_status'] ?? 'unpaid') === 'paid'
                                        ? brd_h((string)($row['publish_price'] ?? 0) . ' VM Coins')
                                        : brd_h(brd_t('ні', 'нет', 'no')) ?>
                                </div>

                                <?php if ($rejectNote !== '' && $status === 'rejected'): ?>
                                    <div class="alert alert-danger py-2 px-3 mt-2 mb-0">
                                        <strong><?= brd_h(brd_t('Причина відхилення:', 'Причина отклонения:', 'Rejection reason:')) ?></strong>
                                        <?= brd_h($rejectNote) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="d-flex flex-wrap gap-2 align-content-start">
                            <a class="btn btn-sm btn-outline-primary" href="/functional/board/edit.php?id=<?= (int)$row['id'] ?>">
                                <?= brd_h(brd_t('Редагувати', 'Редактировать', 'Edit')) ?>
                            </a>

                            <a class="btn btn-sm btn-outline-secondary" href="<?= brd_h(brd_ad_url((int)$row['id'])) ?>">
                                <?= brd_h(brd_t('Відкрити', 'Открыть', 'Open')) ?>
                            </a>

                            <?php if (in_array($status, ['draft', 'rejected', 'archived'], true)): ?>
                                <form method="post" action="/functional/board/manage.php" class="m-0">
                                    <input type="hidden" name="csrf" value="<?= brd_h(brd_csrf_token()) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <input type="hidden" name="do" value="submit">
                                    <button class="btn btn-sm btn-primary"><?= brd_h(brd_t('На модерацію', 'На модерацию', 'Submit')) ?></button>
                                </form>
                            <?php endif; ?>

                            <?php if ($status === 'approved'): ?>
                                <form method="post" action="/functional/board/manage.php" class="m-0">
                                    <input type="hidden" name="csrf" value="<?= brd_h(brd_csrf_token()) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <input type="hidden" name="do" value="archive">
                                    <button class="btn btn-sm btn-outline-warning"><?= brd_h(brd_t('В архів', 'В архив', 'Archive')) ?></button>
                                </form>
                            <?php endif; ?>

                            <?php if ($status === 'archived'): ?>
                                <form method="post" action="/functional/board/manage.php" class="m-0">
                                    <input type="hidden" name="csrf" value="<?= brd_h(brd_csrf_token()) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <input type="hidden" name="do" value="restore_draft">
                                    <button class="btn btn-sm btn-outline-success"><?= brd_h(brd_t('Повернути в чернетку', 'Вернуть в черновик', 'Restore to draft')) ?></button>
                                </form>
                            <?php endif; ?>

                            <?php if ($status !== 'deleted'): ?>
                                <form method="post" action="/functional/board/manage.php" class="m-0" onsubmit="return confirm(<?= json_encode(brd_t('Видалити оголошення?', 'Удалить объявление?', 'Delete the ad?'), JSON_UNESCAPED_UNICODE) ?>);">
                                    <input type="hidden" name="csrf" value="<?= brd_h(brd_csrf_token()) ?>">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <input type="hidden" name="do" value="delete">
                                    <button class="btn btn-sm btn-outline-danger"><?= brd_h(brd_t('Видалити', 'Удалить', 'Delete')) ?></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>
