<?php

declare(strict_types=1);

class AdminTagController
{
    public static function routes(): void
    {
        Router::get('/admin/tags', [self::class, 'index']);
        Router::get('/admin/tags/create', [self::class, 'create']);
        Router::post('/admin/tags/store', [self::class, 'store']);
        Router::get('/admin/tags/{id}/edit', [self::class, 'edit']);
        Router::post('/admin/tags/{id}/update', [self::class, 'update']);
        Router::post('/admin/tags/{id}/delete', [self::class, 'destroy']);
        Router::post('/admin/tags/bulk-delete', [self::class, 'bulkDelete']);
        Router::post('/admin/tags/{id}/translations', [self::class, 'saveTranslations']);
        EntityTranslateAdmin::routes('tag', 'tags', self::class);
    }

    public static function aiTranslateInit(): void   { EntityTranslateAdmin::init('tag'); }
    public static function aiTranslateStart(): void  { EntityTranslateAdmin::start('tag'); }
    public static function aiTranslateStatus(): void { EntityTranslateAdmin::status('tag'); }
    public static function aiTranslateCancel(): void { EntityTranslateAdmin::cancel('tag'); }
    public static function aiTranslatePause(): void  { EntityTranslateAdmin::pause('tag'); }
    public static function aiTranslateResume(): void { EntityTranslateAdmin::resume('tag'); }
    public static function aiTranslateRetry(): void  { EntityTranslateAdmin::retry('tag'); }
    public static function aiTranslateAuto(): void   { EntityTranslateAdmin::auto('tag'); }

    


    public static function index(): void
    {
        Auth::requireAdmin();
        $search = $_GET['q'] ?? '';
        $videoFilter = $_GET['videos'] ?? '';
        $sort = $_GET['sort'] ?? 'name';

         
        $typeRows = Database::fetchAll('SELECT video_type, COUNT(*) as cnt FROM tags GROUP BY video_type ORDER BY ' . Video::typeFieldOrder());
        $availableTypes = array_column($typeRows, 'video_type');
        $typeCounts = array_column($typeRows, 'cnt', 'video_type');
        $showTypeFilter = count($availableTypes) > 1;
        $typeFilter = '';
        if ($showTypeFilter) {
            $typeFilter = $_GET['type'] ?? '';
            if ($typeFilter !== '' && !in_array($typeFilter, Video::VALID_TYPES, true)) {
                $typeFilter = '';
            }
        }

        $where = [];
        $params = [];
        if ($search !== '') {
            $where[] = 't.name LIKE ?';
            $params[] = "%{$search}%";
        }
        if ($typeFilter !== '') {
            $where[] = 't.video_type = ?';
            $params[] = $typeFilter;
        }
        $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

        $having = '';
        if ($videoFilter === 'with') $having = 'HAVING video_count > 0';
        elseif ($videoFilter === 'empty') $having = 'HAVING video_count = 0';

        $orderBy = match ($sort) {
            'videos' => 'video_count DESC, t.name ASC',
            'newest' => 't.id DESC',
            default => 't.name ASC',
        };

        $countRow = Database::fetchOne(
            "SELECT COUNT(*) as cnt FROM (
                SELECT t.id, COUNT(vt.video_id) as video_count
                FROM tags t LEFT JOIN video_tags vt ON t.id = vt.tag_id
                {$whereClause}
                GROUP BY t.id {$having}
            ) sub",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $pagination = Pagination::fromRequest($total, 100);

        $tags = Database::fetchAll(
            "SELECT t.*, COUNT(vt.video_id) as video_count
            FROM tags t LEFT JOIN video_tags vt ON t.id = vt.tag_id
            {$whereClause}
            GROUP BY t.id {$having}
            ORDER BY {$orderBy}
            LIMIT ? OFFSET ?",
            array_merge($params, [$pagination->perPage, $pagination->offset])
        );

         
        $tagTranslations = [];
        $tagIds = array_column($tags, 'id');
        if (!empty($tagIds)) {
            $ph = implode(',', array_fill(0, count($tagIds), '?'));
            $tRows = Database::fetchAll(
                "SELECT tag_id, lang_code, name FROM tag_translations WHERE tag_id IN ({$ph}) ORDER BY tag_id, lang_code",
                $tagIds
            );
            foreach ($tRows as $tr) {
                $tagTranslations[(int) $tr['tag_id']][$tr['lang_code']] = $tr['name'];
            }
        }

        Router::render('admin/tags', [
            'pageTitle' => 'Tags', 'activeMenu' => 'tags', 'contentTemplate' => '_tags',
            'headerExtra' => EntityTranslateAdmin::headerButtons('tag'),
            'headerAction' => ['url' => '/admin/tags/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New Tag'],
            'tags' => $tags,
            'pagination' => $pagination, 'search' => $search,
            'currentVideoFilter' => $videoFilter,
            'currentSort' => $sort,
            'showTypeFilter' => $showTypeFilter,
            'availableTypes' => $availableTypes,
            'typeCounts' => $typeCounts,
            'currentType' => $typeFilter,
            'tagTranslations' => $tagTranslations,
        ]);
    }

    public static function create(): void
    {
        Auth::requireAdmin();
        Router::render('admin/tag_form', [
            'pageTitle' => 'New Tag', 'activeMenu' => 'tags', 'contentTemplate' => '_tag_form',
            'tag' => null, 'error' => null,
        ]);
    }

    public static function store(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/tags'); }
        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;
        Tag::create([
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::fromInput('tags', $_POST['slug'] ?? '', $_POST['name'] ?? '', null, ['video_type' => $videoType]),
            'video_type' => $videoType,
        ]);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Tag created successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/tags');
    }

    public static function edit(): void
    {
        Auth::requireAdmin();
        $tag = Tag::find((int) Router::param('id'));
        if (!$tag) { Router::redirect('/admin/tags'); }

        $translations = Tag::translations((int) $tag['id']);
        $languages = Translator::available();
        $defaultLang = Translator::getDefaultCode();

        Router::render('admin/tag_form', [
            'pageTitle' => 'Edit Tag', 'activeMenu' => 'tags', 'contentTemplate' => '_tag_form',
            'tag' => $tag, 'error' => null,
            'entityTranslations' => $translations,
            'entityLanguages' => $languages,
            'defaultLang' => $defaultLang,
        ]);
    }

    public static function update(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/tags'); }
        $id = (int) Router::param('id');
        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;
        Tag::update($id, [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::fromInput('tags', $_POST['slug'] ?? '', $_POST['name'] ?? '', $id, ['video_type' => $videoType]),
            'video_type' => $videoType,
        ]);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Tag updated successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/tags');
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/tags'); }
        Tag::delete((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Tag deleted successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/tags');
    }

    public static function bulkDelete(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { http_response_code(403); echo json_encode(['error' => 'CSRF']); return; }
        $input = json_decode(file_get_contents('php://input'), true);
        $ids = array_filter(array_map('intval', $input['ids'] ?? []), fn($id) => $id > 0);
        $result = BulkDelete::run($ids, static fn(array $batch): int => BulkDelete::rows('tags', $batch));
        $_SESSION['flash'] = ['type' => 'success', 'message' => BulkDelete::message($result, 'tag', 'tags')];
        echo json_encode(BulkDelete::payload($result));
    }

    public static function saveTranslations(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::json(['error' => 'Invalid CSRF token'], 403); }
        $id = (int) Router::param('id');
        $entity = Tag::find($id);
        if (!$entity) { Router::json(['error' => 'Not found'], 404); }
        $videoType = $entity['video_type'] ?? '';

        $input = json_decode(file_get_contents('php://input'), true) ?: [];
        $translations = $input['translations'] ?? [];

        foreach ($translations as $langCode => $fields) {
            $langCode = preg_replace('/[^a-z]/', '', strtolower($langCode));
            if ($langCode === '' || strlen($langCode) > 5) continue;

            $name = mb_substr(trim($fields['name'] ?? ''), 0, 200);

            if ($name === '') {
                Database::query('DELETE FROM tag_translations WHERE tag_id = ? AND lang_code = ?', [$id, $langCode]);
            } else {
                $slug = Slug::uniqueEntityTranslation('tag_translations', 'tag_id', 'tags', $name, $langCode, $id, $videoType);
                $existing = Database::fetchOne('SELECT id FROM tag_translations WHERE tag_id = ? AND lang_code = ?', [$id, $langCode]);
                if ($existing) {
                    Database::query(
                        'UPDATE tag_translations SET name = ?, slug = ? WHERE tag_id = ? AND lang_code = ?',
                        [$name, $slug, $id, $langCode]
                    );
                } else {
                    Database::query(
                        'INSERT INTO tag_translations (tag_id, lang_code, name, slug) VALUES (?, ?, ?, ?)',
                        [$id, $langCode, $name, $slug]
                    );
                }
            }
        }

        SitemapController::markDirty();
        Router::json(['success' => true]);
    }

    





}
