<?php

declare(strict_types=1);

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

    public static function aiTranslateInit(): void   { EntityTranslateAdmin::init('album_tag'); }
    public static function aiTranslateStart(): void  { EntityTranslateAdmin::start('album_tag'); }
    public static function aiTranslateStatus(): void { EntityTranslateAdmin::status('album_tag'); }
    public static function aiTranslateCancel(): void { EntityTranslateAdmin::cancel('album_tag'); }
    public static function aiTranslatePause(): void  { EntityTranslateAdmin::pause('album_tag'); }
    public static function aiTranslateResume(): void { EntityTranslateAdmin::resume('album_tag'); }
    public static function aiTranslateRetry(): void  { EntityTranslateAdmin::retry('album_tag'); }
    public static function aiTranslateAuto(): void   { EntityTranslateAdmin::auto('album_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 album_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 album_count > 0';
        elseif ($videoFilter === 'empty') $having = 'HAVING album_count = 0';

        $orderBy = match ($sort) {
            'videos' => 'album_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(at2.album_id) as album_count
                FROM album_tags t LEFT JOIN album_tag_map at2 ON t.id = at2.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(at2.album_id) as album_count
            FROM album_tags t LEFT JOIN album_tag_map at2 ON t.id = at2.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 album_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/album_tags', [
            'pageTitle' => 'Album Tags', 'activeMenu' => 'album_tags', 'contentTemplate' => '_album_tags',
            'headerExtra' => EntityTranslateAdmin::headerButtons('album_tag'),
            'headerAction' => ['url' => '/admin/albums/tags/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New Album 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/album_tag_form', [
            'pageTitle' => 'New Album Tag', 'activeMenu' => 'album_tags', 'contentTemplate' => '_album_tag_form',
            'tag' => null, 'error' => null,
        ]);
    }

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

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

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

        Router::render('admin/album_tag_form', [
            'pageTitle' => 'Edit Album Tag', 'activeMenu' => 'album_tags', 'contentTemplate' => '_album_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/albums/tags'); }
        $id = (int) Router::param('id');
        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;
        AlbumTag::update($id, [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::fromInput('album_tags', $_POST['slug'] ?? '', $_POST['name'] ?? '', $id, ['video_type' => $videoType]),
            'video_type' => $videoType,
        ]);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Album tag updated successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/albums/tags');
    }

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/albums/tags'); }
        AlbumTag::delete((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Album tag deleted successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/albums/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('album_tags', $batch));
        $_SESSION['flash'] = ['type' => 'success', 'message' => BulkDelete::message($result, 'album tag', 'album 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 = AlbumTag::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 album_tag_translations WHERE tag_id = ? AND lang_code = ?', [$id, $langCode]);
            } else {
                $slug = Slug::uniqueEntityTranslation('album_tag_translations', 'tag_id', 'album_tags', $name, $langCode, $id, $videoType);
                $existing = Database::fetchOne('SELECT id FROM album_tag_translations WHERE tag_id = ? AND lang_code = ?', [$id, $langCode]);
                if ($existing) {
                    Database::query(
                        'UPDATE album_tag_translations SET name = ?, slug = ? WHERE tag_id = ? AND lang_code = ?',
                        [$name, $slug, $id, $langCode]
                    );
                } else {
                    Database::query(
                        'INSERT INTO album_tag_translations (tag_id, lang_code, name, slug) VALUES (?, ?, ?, ?)',
                        [$id, $langCode, $name, $slug]
                    );
                }
            }
        }

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

    

    public static function ajaxCreate(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::json(['error' => 'Invalid CSRF token'], 403); }

        $input = json_decode(file_get_contents('php://input'), true) ?: [];
        $name = trim((string) ($input['name'] ?? $_POST['name'] ?? ''));
        if ($name === '') { Router::json(['error' => 'Name is required'], 400); }

        $rawType = (string) ($input['video_type'] ?? $_POST['video_type'] ?? '');
        $videoType = in_array($rawType, Video::VALID_TYPES, true) ? $rawType : Video::DEFAULT_TYPE;

        $existing = Database::fetchOne('SELECT * FROM album_tags WHERE name = ? AND video_type = ? LIMIT 1', [$name, $videoType]);
        if ($existing) {
            Router::json(['success' => true, 'id' => (int) $existing['id'], 'name' => $existing['name'], 'slug' => $existing['slug'], 'video_type' => $existing['video_type'], 'created' => false]);
        }

        $id = AlbumTag::create([
            'name' => $name,
            'slug' => Slug::unique('album_tags', $name, null, ['video_type' => $videoType]),
            'video_type' => $videoType,
        ]);
        $row = AlbumTag::find($id);
        SitemapController::markDirty();
        Router::json(['success' => true, 'id' => (int) $id, 'name' => $row['name'], 'slug' => $row['slug'], 'video_type' => $row['video_type'], 'created' => true]);
    }
}
