<?php

declare(strict_types=1);

class AlbumChannel
{
    public static function find(int $id): ?array
    {
        return Database::fetchOne('SELECT * FROM album_channels 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.channel_id FROM album_channel_translations ct
                  JOIN album_channels c ON ct.channel_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) {
                $channel = self::find((int) $trans['channel_id']);
                return $channel ? self::localize($channel) : null;
            }
        }

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

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

        return $channel ? self::localize($channel) : 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.total_views 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_channels 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_channels', implode(' AND ', $conds), $params);
        }
        return Database::count('album_channels');
    }

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

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

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

    

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

    

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

    

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

        $row = Database::fetchOne(
            'SELECT name, slug, description FROM album_channel_translations WHERE channel_id = ? AND lang_code = ?',
            [(int) $channel['id'], Translator::locale()]
        );

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

        return $channel;
    }

    

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

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

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

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

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

        foreach ($channels as &$channel) {
            $cid = (int) $channel['id'];
            if (isset($map[$cid])) {
                $tr = $map[$cid];
                if ($tr['name'] !== null && $tr['name'] !== '') {
                    $channel['name'] = $tr['name'];
                }
                if ($tr['slug'] !== null && $tr['slug'] !== '') {
                    $channel['slug'] = $tr['slug'];
                }
                if (isset($tr['description']) && $tr['description'] !== null && $tr['description'] !== '') {
                    $channel['description'] = $tr['description'];
                }
            }
        }
        unset($channel);

        return $channels;
    }
}
