<?php

declare(strict_types=1);

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

    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 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 video_count > 0';
        elseif ($videoFilter === 'empty') $having = 'HAVING video_count = 0';

        $orderBy = match ($sort) {
            'videos' => 'video_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(vp.video_id) as video_count
                FROM performers p LEFT JOIN video_performers vp ON p.id = vp.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(vp.video_id) as video_count
            FROM performers p
            LEFT JOIN video_performers vp ON p.id = vp.performer_id
            {$whereClause}
            GROUP BY p.id {$having}
            ORDER BY {$orderBy}
            LIMIT ? OFFSET ?",
            array_merge($params, [$pagination->perPage, $pagination->offset])
        );
         
         
        VideoAsset::assignUniqueThumbFolders($performers, 'video_performers', 'performer_id', 'photo');

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

        Router::render('admin/performers', [
            'pageTitle' => 'Pornstars', 'activeMenu' => 'performers', 'contentTemplate' => '_performers',
            'headerAction' => ['url' => '/admin/performers/create' . ($typeFilter !== '' ? '?type=' . $typeFilter : ''), 'label' => 'New 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/performer_form', [
            'pageTitle' => 'New Pornstar', 'activeMenu' => 'performers', 'contentTemplate' => '_performer_form',
            'performer' => null, 'error' => null,
        ]);
    }

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

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

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

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

        Router::render('admin/performer_form', [
            'pageTitle' => 'Edit Pornstar', 'activeMenu' => 'performers', 'contentTemplate' => '_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/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('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']; }
        }

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

    public static function destroy(): void
    {
        Auth::requireAdmin();
        if (!Router::verifyCsrf()) { Router::redirect('/admin/performers'); }
        Performer::delete((int) Router::param('id'));
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Pornstar deleted successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/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) { Performer::delete($id); }
        $_SESSION['flash'] = ['type' => 'success', 'message' => count($ids) . ' 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 = Performer::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 performer_translations WHERE performer_id = ? AND lang_code = ?', [$id, $langCode]);
            } else {
                $slug = Slug::uniqueEntityTranslation('performer_translations', 'performer_id', 'performers', $name, $langCode, $id, $videoType);
                $existing = Database::fetchOne('SELECT id FROM performer_translations WHERE performer_id = ? AND lang_code = ?', [$id, $langCode]);
                if ($existing) {
                    Database::query(
                        'UPDATE performer_translations SET name = ?, slug = ?, bio = ? WHERE performer_id = ? AND lang_code = ?',
                        [$name, $slug, $bio, $id, $langCode]
                    );
                } else {
                    Database::query(
                        'INSERT INTO performer_translations (performer_id, lang_code, name, slug, bio) VALUES (?, ?, ?, ?, ?)',
                        [$id, $langCode, $name, $slug, $bio]
                    );
                }
            }
        }

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