<?php

declare(strict_types=1);

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

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

    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 channels 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[] = 's.name LIKE ?';
            $params[] = "%{$search}%";
        }
        if ($typeFilter !== '') {
            $where[] = 's.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, s.name ASC',
            'newest' => 's.id DESC',
            default => 's.name ASC',
        };

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

        $channels = Database::fetchAll(
            "SELECT s.*, COUNT(vs.video_id) as video_count
            FROM channels s
            LEFT JOIN video_channels vs ON s.id = vs.channel_id
            {$whereClause}
            GROUP BY s.id {$having}
            ORDER BY {$orderBy}
            LIMIT ? OFFSET ?",
            array_merge($params, [$pagination->perPage, $pagination->offset])
        );
         
         
         
        VideoAsset::assignUniqueThumbFolders($channels, 'video_channels', 'channel_id', 'logo');

        Router::render('admin/channels', [
            'pageTitle' => 'Channels', 'activeMenu' => 'channels', 'contentTemplate' => '_channels',
            'headerExtra' => EntityTranslateAdmin::headerButtons('channel'),
            'headerAction' => ['url' => '/admin/channels/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New Channel'],
            'channels' => $channels,
            'pagination' => $pagination, 'search' => $search,
            'currentVideoFilter' => $videoFilter,
            'currentSort' => $sort,
            'showTypeFilter' => $showTypeFilter,
            'availableTypes' => $availableTypes,
            'typeCounts' => $typeCounts,
            'currentType' => $typeFilter,
        ]);
    }

    public static function create(): void
    {
        Auth::requireAdmin();
        Router::render('admin/channel_form', [
            'pageTitle' => 'New Channel', 'activeMenu' => 'channels', 'contentTemplate' => '_channel_form',
            'channel' => null, 'error' => null,
        ]);
    }

    public static function store(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/channels'); }

        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::fromInput('channels', $_POST['slug'] ?? '', $_POST['name'] ?? '', null, ['video_type' => $videoType]),
            'description' => trim($_POST['description'] ?? ''),
            'website' => trim($_POST['website'] ?? ''),
            'video_type' => $videoType,
        ];

        if (!empty($_FILES['logo']['name'])) {
            $upload = FileUpload::image($_FILES['logo'], 'channels');
            if ($upload['success']) { $data['logo'] = $upload['path']; }
        }

        Channel::create($data);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Channel created.'];
        SitemapController::markDirty();
        Router::redirect('/admin/channels');
    }

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

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

        Router::render('admin/channel_form', [
            'pageTitle' => 'Edit Channel', 'activeMenu' => 'channels', 'contentTemplate' => '_channel_form',
            'channel' => $channel, 'error' => null,
            'entityTranslations' => $translations,
            'entityLanguages' => $languages,
            'defaultLang' => $defaultLang,
        ]);
    }

    public static function update(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/channels'); }
        $id = (int) Router::param('id');
        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;

        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::fromInput('channels', $_POST['slug'] ?? '', $_POST['name'] ?? '', $id, ['video_type' => $videoType]),
            'description' => trim($_POST['description'] ?? ''),
            'website' => trim($_POST['website'] ?? ''),
            'video_type' => $videoType,
        ];

        if (!empty($_FILES['logo']['name'])) {
            $upload = FileUpload::image($_FILES['logo'], 'channels');
            if ($upload['success']) { $data['logo'] = $upload['path']; }
        }

        Channel::update($id, $data);
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Channel updated.'];
        SitemapController::markDirty();
        Router::redirect('/admin/channels');
    }

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

    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('channels', $batch));
        $_SESSION['flash'] = ['type' => 'success', 'message' => BulkDelete::message($result, 'channel', 'channels')];
        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 = Channel::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);
            $description = trim($fields['description'] ?? '');

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

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