<?php

declare(strict_types=1);

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

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

    private static function getEnabledLangs(): array
    {
        $langs = [];
        foreach (Translator::available() as $lang) {
            if (!empty($lang['is_enabled'])) {
                $langs[] = $lang;
            }
        }
        return $langs;
    }

    

    private static function detectContactForm(): int
    {
        foreach ($_POST as $key => $value) {
            if (is_string($value) && ($key === 'body' || str_ends_with($key, '_body')) && Shortcode::contains($value, 'contact_form')) {
                return 1;
            }
        }
        return 0;
    }

    public static function index(): void
    {
        Auth::requireAdmin();
        $total = Page::count();
        $pagination = Pagination::fromRequest($total, 100);
        $pages = Page::all($pagination->perPage, $pagination->offset);
        $translationData = Page::allTranslationStatuses();

        Router::render('admin/pages', [
            'pageTitle' => 'Pages', 'activeMenu' => 'pages', 'contentTemplate' => '_pages',
            'headerExtra' => EntityTranslateAdmin::headerButtons('page'),
            'headerAction' => ['url' => '/admin/pages/create', 'label' => 'New Page'],
            'pages' => $pages,
            'pagination' => $pagination,
            'translationData' => $translationData,
        ]);
    }

    public static function create(): void
    {
        Auth::requireAdmin();
        $enabledLangs = self::getEnabledLangs();
        $defaultLang = Translator::getDefaultCode();

        Router::render('admin/page_form', [
            'pageTitle' => 'New Page', 'activeMenu' => 'pages', 'contentTemplate' => '_page_form',
            'page' => null, 'error' => null,
            'enabledLangs' => $enabledLangs,
            'defaultLang' => $defaultLang,
            'translations' => [],
        ]);
    }

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

        $defaultLang = Translator::getDefaultCode();
        $enabledLangs = self::getEnabledLangs();

        $slug = trim($_POST['slug'] ?? '');
        if ($slug === '') {
            $slug = Slug::unique('pages', $_POST['title'] ?? '');
        } else {
            $slug = Slug::unique('pages', $slug);
        }

        $pageId = Page::create([
            'title' => trim($_POST['title'] ?? ''),
            'slug' => $slug,
            'body' => Sanitizer::richHtml($_POST['body'] ?? ''),
            'meta_title' => trim($_POST['meta_title'] ?? '') ?: null,
            'meta_description' => trim($_POST['meta_description'] ?? '') ?: null,
            'status' => in_array($_POST['status'] ?? '', ['draft', 'published'], true) ? $_POST['status'] : 'draft',
            'show_in_footer' => isset($_POST['show_in_footer']) ? 1 : 0,
            'has_contact_form' => self::detectContactForm(),
            'sort_order' => 0,
        ]);

         
        foreach ($enabledLangs as $lang) {
            $code = $lang['code'];
            if ($code === $defaultLang) continue;

            $transTitle = trim($_POST["trans_{$code}_title"] ?? '');
            if ($transTitle === '') continue;

            $transSlug = trim($_POST["trans_{$code}_slug"] ?? '');
            if ($transSlug === '') {
                $transSlug = Slug::uniqueTranslation($transTitle, $code);
            } else {
                $transSlug = Slug::uniqueTranslation($transSlug, $code);
            }

            Page::saveTranslation($pageId, $code, [
                'title' => $transTitle,
                'slug' => $transSlug,
                'body' => Sanitizer::richHtml($_POST["trans_{$code}_body"] ?? ''),
                'meta_title' => trim($_POST["trans_{$code}_meta_title"] ?? '') ?: null,
                'meta_description' => trim($_POST["trans_{$code}_meta_description"] ?? '') ?: null,
            ]);
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Page created successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/pages');
    }

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

        $enabledLangs = self::getEnabledLangs();
        $defaultLang = Translator::getDefaultCode();
        $translations = Page::translations((int) $page['id']);

        Router::render('admin/page_form', [
            'pageTitle' => 'Edit Page', 'activeMenu' => 'pages', 'contentTemplate' => '_page_form',
            'page' => $page, 'error' => null,
            'enabledLangs' => $enabledLangs,
            'defaultLang' => $defaultLang,
            'translations' => $translations,
        ]);
    }

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

        $id = (int) Router::param('id');
        $defaultLang = Translator::getDefaultCode();
        $enabledLangs = self::getEnabledLangs();

        $slug = trim($_POST['slug'] ?? '');
        if ($slug === '') {
            $slug = Slug::unique('pages', $_POST['title'] ?? '', $id);
        } else {
            $slug = Slug::unique('pages', $slug, $id);
        }

        Page::update($id, [
            'title' => trim($_POST['title'] ?? ''),
            'slug' => $slug,
            'body' => Sanitizer::richHtml($_POST['body'] ?? ''),
            'meta_title' => trim($_POST['meta_title'] ?? '') ?: null,
            'meta_description' => trim($_POST['meta_description'] ?? '') ?: null,
            'status' => in_array($_POST['status'] ?? '', ['draft', 'published'], true) ? $_POST['status'] : 'draft',
            'show_in_footer' => isset($_POST['show_in_footer']) ? 1 : 0,
            'has_contact_form' => self::detectContactForm(),
            'sort_order' => 0,
        ]);

         
        foreach ($enabledLangs as $lang) {
            $code = $lang['code'];
            if ($code === $defaultLang) continue;

            $transTitle = trim($_POST["trans_{$code}_title"] ?? '');
            if ($transTitle === '') {
                 
                Page::deleteTranslation($id, $code);
                continue;
            }

            $transSlug = trim($_POST["trans_{$code}_slug"] ?? '');
            if ($transSlug === '') {
                $transSlug = Slug::uniqueTranslation($transTitle, $code, $id);
            } else {
                $transSlug = Slug::uniqueTranslation($transSlug, $code, $id);
            }

            Page::saveTranslation($id, $code, [
                'title' => $transTitle,
                'slug' => $transSlug,
                'body' => Sanitizer::richHtml($_POST["trans_{$code}_body"] ?? ''),
                'meta_title' => trim($_POST["trans_{$code}_meta_title"] ?? '') ?: null,
                'meta_description' => trim($_POST["trans_{$code}_meta_description"] ?? '') ?: null,
            ]);
        }

        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Page updated successfully.'];
        SitemapController::markDirty();
        Router::redirect('/admin/pages');
    }

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

    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('pages', $batch));
        $_SESSION['flash'] = ['type' => 'success', 'message' => BulkDelete::message($result, 'page', 'pages')];
        echo json_encode(BulkDelete::payload($result));
    }
}
