<?php
declare(strict_types=1);

Auth::requireRole('analyst');
Csrf::check();

$id = post('id') ? (int) post('id') : null;
$nameEn = trim((string) post('name_en', ''));

if ($nameEn === '') {
    Flash::add('error', t('tag_name_en') . ': ' . t('required'));
    redirect('tags', 'index');
}

$color = trim((string) post('color', ''));
if ($color !== '' && !preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
    $color = '';
}

$groups = ['product', 'technology', 'domain'];
$group  = in_array(post('tag_group'), $groups, true) ? (string) post('tag_group') : 'product';

$fields = [
    'name_en'             => $nameEn,
    'name_he'             => trim((string) post('name_he', '')) ?: null,
    'tag_group'           => $group,
    'color'               => $color ?: null,
    'sort_order'          => max(0, min(9999, (int) post('sort_order', 100))),
    'is_core_competition' => post('is_core_competition') === '1' ? 1 : 0,
];

if ($id === null) {
    $fields['slug'] = unique_slug(slugify($nameEn), 'tags');
    Database::run(
        'INSERT INTO tags (slug, name_en, name_he, tag_group, color, sort_order, is_core_competition)
         VALUES (:slug, :name_en, :name_he, :tag_group, :color, :sort_order, :is_core_competition)',
        $fields
    );
    Audit::log('create', 'tag', Database::lastId(), ['name' => $nameEn]);
} else {
    Database::run(
        'UPDATE tags SET name_en = :name_en, name_he = :name_he, tag_group = :tag_group,
                color = :color, sort_order = :sort_order, is_core_competition = :is_core_competition
          WHERE id = :id',
        $fields + ['id' => $id]
    );
    Audit::log('update', 'tag', $id, ['name' => $nameEn]);
}

Flash::add('ok', t('tag_saved'));
redirect('tags', 'index');
