<?php

declare(strict_types=1);

class Channel
{
    public static function find(int $id): ?array
    {
        return Database::fetchOne('SELECT * FROM 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 st.channel_id FROM channel_translations st
                  JOIN channels s ON st.channel_id = s.id
                  WHERE st.slug = ? AND st.lang_code = ?';
            $p = [$slug, $locale];
            if ($vt !== '') { $q .= ' AND s.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 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 channels WHERE slug = ?', [$slug]);
        }

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

    public static function all(string $search = '', int $limit = 24, int $offset = 0, string $sort = 'alphabetical', string $videoType = '', bool $onlyPopulated = false): array
    {
        $override = HookSystem::applyFilter('channel.listing', null, $search, $limit, $offset, $sort, $videoType, $onlyPopulated);
        if ($override !== null && $override !== []) {
            VideoAsset::assignUniqueThumbFolders($override, 'video_channels', 'channel_id', 'logo');
            return self::localizeResults($override);
        }

        $orderBy = match ($sort) {
            'popularity' => 's.total_views DESC, s.name ASC',
            default => 's.name ASC',
        };

        $conditions = [];
        $params = [];
        if ($search !== '') {
            if (mb_strlen($search) >= 3) {
                $conditions[] = 'MATCH(s.name) AGAINST(? IN BOOLEAN MODE)';
                $params[] = $search;
            } else {
                $conditions[] = 's.name LIKE ?';
                $params[] = $search . '%';
            }
        }
        if ($videoType !== '') {
            $conditions[] = 's.video_type = ?';
            $params[] = $videoType;
        }
         
        if ($onlyPopulated) { $conditions[] = 's.video_count > 0'; }
        $where = !empty($conditions) ? ' WHERE ' . implode(' AND ', $conditions) : '';

        $params[] = $limit;
        $params[] = $offset;

        $results = Database::fetchAll(
            "SELECT s.* FROM channels s{$where} ORDER BY {$orderBy} LIMIT ? OFFSET ?",
            $params
        );
        VideoAsset::assignUniqueThumbFolders($results, 'video_channels', 'channel_id', 'logo');
        return self::localizeResults($results);
    }

    public static function count(string $search = '', string $videoType = '', bool $onlyPopulated = false): int
    {
        $where = [];
        $params = [];
        if ($search !== '') {
            if (mb_strlen($search) >= 3) {
                $where[] = 'MATCH(name) AGAINST(? IN BOOLEAN MODE)';
                $params[] = $search;
            } else {
                $where[] = 'name LIKE ?';
                $params[] = $search . '%';
            }
        }
        if ($videoType !== '') {
            $where[] = 'video_type = ?';
            $params[] = $videoType;
        }
        if ($onlyPopulated) { $where[] = 'video_count > 0'; }
        if (!empty($where)) {
            return Database::count('channels', implode(' AND ', $where), $params);
        }
        return Database::count('channels');
    }

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

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

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

    

    public static function updateCounts(int $id): void
    {
        $row = Database::fetchOne(
            "SELECT COUNT(*) as cnt, COALESCE(SUM(v.views), 0) as tv
             FROM video_channels vs
             JOIN videos v ON vs.video_id = v.id
             WHERE vs.channel_id = ? AND v.status = 'published'",
            [$id]
        );
        Database::update('channels', [
            'video_count' => (int) ($row['cnt'] ?? 0),
            'total_views' => (int) ($row['tv'] ?? 0),
        ], 'id = ?', [$id]);
    }

    

    public static function recalcAllCounts(): void
    {
        Database::query(
            "UPDATE channels s LEFT JOIN (
                SELECT vs.channel_id, COUNT(*) as cnt, COALESCE(SUM(v.views), 0) as tv
                FROM video_channels vs
                JOIN videos v ON vs.video_id = v.id AND v.status = 'published'
                GROUP BY vs.channel_id
            ) agg ON s.id = agg.channel_id
            SET s.video_count = COALESCE(agg.cnt, 0),
                s.total_views = COALESCE(agg.tv, 0)"
        );
    }

    

    public static function translations(int $channelId): array
    {
        $rows = Database::fetchAll(
            'SELECT lang_code, name, slug, description FROM 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 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 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) {
            $sid = (int) $channel['id'];
            if (isset($map[$sid])) {
                $tr = $map[$sid];
                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;
    }
}
