<?php

declare(strict_types=1);

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

    public static function index(): void
    {
        Auth::requireAdmin();
        $search = $_GET['q'] ?? '';
        $videoFilter = $_GET['videos'] ?? '';
        $hasPhoto = $_GET['photo'] ?? '';
        $country = $_GET['country'] ?? '';
        $sort = $_GET['sort'] ?? 'name';

         
        $typeRows = Database::fetchAll('SELECT video_type, COUNT(*) as cnt FROM album_performers 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[] = 'p.name LIKE ?';
            $params[] = "%{$search}%";
        }
        if ($country !== '') {
            $where[] = 'p.country = ?';
            $params[] = $country;
        }
        if ($hasPhoto === 'yes') {
            $where[] = "p.photo IS NOT NULL AND p.photo != ''";
        } elseif ($hasPhoto === 'no') {
            $where[] = "(p.photo IS NULL OR p.photo = '')";
        }
        if ($typeFilter !== '') {
            $where[] = 'p.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, p.name ASC',
            'newest' => 'p.id DESC',
            default => 'p.name ASC',
        };

        $countRow = Database::fetchOne(
            "SELECT COUNT(*) as cnt FROM (
                SELECT p.id, COUNT(ap.album_id) as album_count
                FROM album_performers p LEFT JOIN album_performer_map ap ON p.id = ap.performer_id
                {$whereClause}
                GROUP BY p.id {$having}
            ) sub",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $pagination = Pagination::fromRequest($total, 100);

        $performers = Database::fetchAll(
            "SELECT p.*, COUNT(ap.album_id) as album_count
            FROM album_performers p
            LEFT JOIN album_performer_map ap ON p.id = ap.performer_id
            {$whereClause}
            GROUP BY p.id {$having}
            ORDER BY {$orderBy}
            LIMIT ? OFFSET ?",
            array_merge($params, [$pagination->perPage, $pagination->offset])
        );

        $filterCountries = Database::fetchAll(
            "SELECT DISTINCT country FROM album_performers WHERE country IS NOT NULL AND country != '' ORDER BY country ASC"
        );

         
        AlbumAsset::assignEntityCovers($performers, 'album_performer_map', 'performer_id', 'photo');

        Router::render('admin/album_performers', [
            'pageTitle' => 'Album Pornstars', 'activeMenu' => 'album_performers', 'contentTemplate' => '_album_performers',
            'headerAction' => ['url' => '/admin/albums/performers/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New Album Pornstar'],
            'performers' => $performers,
            'pagination' => $pagination, 'search' => $search,
            'filterCountries' => $filterCountries,
            'currentVideoFilter' => $videoFilter,
            'currentPhoto' => $hasPhoto,
            'currentCountry' => $country,
            'currentSort' => $sort,
            'showTypeFilter' => $showTypeFilter,
            'availableTypes' => $availableTypes,
            'typeCounts' => $typeCounts,
            'currentType' => $typeFilter,
        ]);
    }

    public static function create(): void
    {
        Auth::requireAdmin();
        Router::render('admin/album_performer_form', [
            'pageTitle' => 'New Album Pornstar', 'activeMenu' => 'album_performers', 'contentTemplate' => '_album_performer_form',
            'performer' => null, 'error' => null,
        ]);
    }

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

        $videoType = in_array($_POST['video_type'] ?? '', Video::VALID_TYPES, true) ? $_POST['video_type'] : Video::DEFAULT_TYPE;
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => Slug::unique('album_performers', $_POST['name'] ?? '', null, ['video_type' => $videoType]),
            'bio' => trim($_POST['bio'] ?? ''),
            'country' => trim($_POST['country'] ?? ''),
            'birth_date' => !empty($_POST['birth_date']) ? $_POST['birth_date'] : null,
            'social_links' => json_encode(array_filter([
                'link' => trim($_POST['link'] ?? ''),
            ])),
            'video_type' => $videoType,
        ];

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

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

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

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

        Router::render('admin/album_performer_form', [
            'pageTitle' => 'Edit Album Pornstar', 'activeMenu' => 'album_performers', 'contentTemplate' => '_album_performer_form',
            'performer' => $performer, 'error' => null,
            'entityTranslations' => $translations,
            'entityLanguages' => $languages,
            'defaultLang' => $defaultLang,
        ]);
    }

    public static function update(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/albums/performers'); }
        $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::unique('album_performers', $_POST['name'] ?? '', $id, ['video_type' => $videoType]),
            'bio' => trim($_POST['bio'] ?? ''),
            'country' => trim($_POST['country'] ?? ''),
            'birth_date' => !empty($_POST['birth_date']) ? $_POST['birth_date'] : null,
            'social_links' => json_encode(array_filter([
                'link' => trim($_POST['link'] ?? ''),
            ])),
            'video_type' => $videoType,
        ];

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

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

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

    public static function bulkDelete(): void
    {
        Auth::requireAdmin();
        Gate::authorize('manage_performers');  
        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);
        foreach ($ids as $id) { AlbumPerformer::delete($id); }
        $_SESSION['flash'] = ['type' => 'success', 'message' => count($ids) . ' album pornstar(s) deleted.'];
        echo json_encode(['deleted' => count($ids)]);
    }

    public static function saveTranslations(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::json(['error' => 'Invalid CSRF token'], 403); }
        $id = (int) Router::param('id');
        $entity = AlbumPerformer::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);
            $bio = trim($fields['bio'] ?? '');

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

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