<?php

declare(strict_types=1);

class AlbumTag
{
    public static function find(int $id): ?array
    {
        return Database::fetchOne('SELECT * FROM album_tags WHERE id = ?', [$id]);
    }

    public static function findBySlug(string $slug): ?array
    {
        $vt = Video::activeType();
        $locale = Translator::locale();
        $defaultLang = Translator::getDefaultCode();

         
        if ($locale !== $defaultLang) {
            $q = 'SELECT ct.tag_id FROM album_tag_translations ct
                  JOIN album_tags c ON ct.tag_id = c.id
                  WHERE ct.slug = ? AND ct.lang_code = ?';
            $p = [$slug, $locale];
            if ($vt !== '') { $q .= ' AND c.video_type = ?'; $p[] = $vt; }
            $trans = Database::fetchOne($q, $p);
            if ($trans) {
                $tag = self::find((int) $trans['tag_id']);
                return $tag ? self::localize($tag) : null;
            }
        }

         
        $q = 'SELECT * FROM album_tags WHERE slug = ?';
        $p = [$slug];
        if ($vt !== '') { $q .= ' AND video_type = ?'; $p[] = $vt; }
        $tag = Database::fetchOne($q, $p);

         
        if (!$tag && $vt !== '') {
            $tag = Database::fetchOne('SELECT * FROM album_tags WHERE slug = ?', [$slug]);
        }

        return $tag ? self::localize($tag) : null;
    }

    public static function all(int $limit = 0, int $offset = 0, string $sort = 'alphabetical', string $videoType = '', bool $onlyPopulated = false): array
    {
        $orderBy = match ($sort) {
            'popularity' => 'c.album_count DESC, c.name ASC',
            default => 'c.name ASC',
        };

        $conds = [];
        $params = [];
        if ($videoType !== '') { $conds[] = 'c.video_type = ?'; $params[] = $videoType; }
         
        if ($onlyPopulated) { $conds[] = 'c.album_count > 0'; }
        $where = !empty($conds) ? ' WHERE ' . implode(' AND ', $conds) : '';

        $limitClause = $limit > 0 ? ' LIMIT ? OFFSET ?' : '';
        if ($limit > 0) {
            $params[] = $limit;
            $params[] = $offset;
        }

        $results = Database::fetchAll(
            "SELECT c.* FROM album_tags c{$where} ORDER BY {$orderBy}" . $limitClause,
            $params
        );
        return self::localizeResults($results);
    }

    public static function count(string $videoType = '', bool $onlyPopulated = false): int
    {
        $conds = []; $params = [];
        if ($videoType !== '') { $conds[] = 'video_type = ?'; $params[] = $videoType; }
        if ($onlyPopulated) { $conds[] = 'album_count > 0'; }
        if (!empty($conds)) {
            return Database::count('album_tags', implode(' AND ', $conds), $params);
        }
        return Database::count('album_tags');
    }

    public static function create(array $data): int
    {
        return Database::insert('album_tags', $data);
    }

    public static function update(int $id, array $data): void
    {
        Database::update('album_tags', $data, 'id = ?', [$id]);
    }

    public static function delete(int $id): void
    {
        Database::delete('album_tags', 'id = ?', [$id]);
    }

    

    public static function updateCounts(int $id): void
    {
        $row = Database::fetchOne(
            "SELECT COUNT(*) as cnt
             FROM album_tag_map m
             JOIN albums a ON m.album_id = a.id
             WHERE m.tag_id = ? AND a.status = 'published'",
            [$id]
        );
        Database::update('album_tags', [
            'album_count' => (int) ($row['cnt'] ?? 0),
        ], 'id = ?', [$id]);
    }

    

    public static function translations(int $tagId): array
    {
        $rows = Database::fetchAll(
            'SELECT lang_code, name, slug FROM album_tag_translations WHERE tag_id = ? ORDER BY lang_code',
            [$tagId]
        );
        $result = [];
        foreach ($rows as $row) {
            $result[$row['lang_code']] = $row;
        }
        return $result;
    }

    

    public static function localize(?array $tag): ?array
    {
        if ($tag === null || Translator::locale() === Translator::getDefaultCode()) {
            return $tag;
        }

        $row = Database::fetchOne(
            'SELECT name, slug FROM album_tag_translations WHERE tag_id = ? AND lang_code = ?',
            [(int) $tag['id'], Translator::locale()]
        );

        if ($row) {
            if ($row['name'] !== null && $row['name'] !== '') {
                $tag['name'] = $row['name'];
            }
            if ($row['slug'] !== null && $row['slug'] !== '') {
                $tag['slug'] = $row['slug'];
            }
        }

        return $tag;
    }

    

    public static function localizeResults(array $tags): array
    {
        if (empty($tags) || Translator::locale() === Translator::getDefaultCode()) {
            return $tags;
        }

        $ids = array_column($tags, 'id');
        if (empty($ids)) {
            return $tags;
        }

        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $params = array_merge([Translator::locale()], $ids);

        $rows = Database::fetchAll(
            "SELECT tag_id, name, slug FROM album_tag_translations WHERE lang_code = ? AND tag_id IN ({$placeholders})",
            $params
        );

        $map = [];
        foreach ($rows as $row) {
            $map[(int) $row['tag_id']] = $row;
        }

        foreach ($tags as &$tag) {
            $tid = (int) $tag['id'];
            if (isset($map[$tid])) {
                $tr = $map[$tid];
                if ($tr['name'] !== null && $tr['name'] !== '') {
                    $tag['name'] = $tr['name'];
                }
                if ($tr['slug'] !== null && $tr['slug'] !== '') {
                    $tag['slug'] = $tr['slug'];
                }
            }
        }
        unset($tag);

        return $tags;
    }
}
