<?php

declare(strict_types=1);

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

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

        $orderBy = match ($sort) {
            'videos' => 'album_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(acm.album_id) as album_count
                FROM album_channels s LEFT JOIN album_channel_map acm ON s.id = acm.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(acm.album_id) as album_count
            FROM album_channels s
            LEFT JOIN album_channel_map acm ON s.id = acm.channel_id
            {$whereClause}
            GROUP BY s.id {$having}
            ORDER BY {$orderBy}
            LIMIT ? OFFSET ?",
            array_merge($params, [$pagination->perPage, $pagination->offset])
        );

         
        AlbumAsset::assignEntityCovers($channels, 'album_channel_map', 'channel_id', 'logo');

        Router::render('admin/album_channels', [
            'pageTitle' => 'Album Channels', 'activeMenu' => 'album_channels', 'contentTemplate' => '_album_channels',
            'headerExtra' => EntityTranslateAdmin::headerButtons('album_channel'),
            'headerAction' => ['url' => '/admin/albums/channels/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New Album 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/album_channel_form', [
            'pageTitle' => 'New Album Channel', 'activeMenu' => 'album_channels', 'contentTemplate' => '_album_channel_form',
            'channel' => null, 'error' => null,
        ]);
    }

    public static function store(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/albums/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('album_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']; }
        }

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

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

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

        Router::render('admin/album_channel_form', [
            'pageTitle' => 'Edit Album Channel', 'activeMenu' => 'album_channels', 'contentTemplate' => '_album_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/albums/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('album_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']; }
        }

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

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

        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_channels 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 = AlbumChannel::create([
            'name' => $name,
            'slug' => Slug::unique('album_channels', $name, null, ['video_type' => $videoType]),
            'video_type' => $videoType,
        ]);
        $row = AlbumChannel::find($id);
        SitemapController::markDirty();
        Router::json(['success' => true, 'id' => (int) $id, 'name' => $row['name'], 'slug' => $row['slug'], 'video_type' => $row['video_type'], 'created' => true]);
    }
}
