<?php

namespace Core\App\Controllers\Admin;

use Core\App\Models\Page;
use Core\System\Csrf;
use Core\System\HtmlSanitizer;
use Core\System\Response;

class PageController
{
    /**
     * Sanitize CMS page content using the centralized HtmlSanitizer,
     * then safely re-inject iframes (HTTPS-only, no allow-same-origin).
     */
    private function sanitizePageContent(string $html): string
    {
        if (trim($html) === '') {
            return '';
        }

        // 1. Extract iframes before central sanitizer removes them, validate each one
        $safeIframes = [];
        $placeholder = '%%%IFRAME_%d%%%';
        $idx = 0;

        $html = preg_replace_callback('/<iframe\b([^>]*)>/i', function ($m) use (&$safeIframes, &$idx, $placeholder) {
            $attrs = $m[1];
            $clean = '';

            // Only allow https:// sources
            if (preg_match('/\bsrc\s*=\s*"([^"]+)"/i', $attrs, $src)) {
                $url = trim($src[1]);
                if (preg_match('/^https:\/\//i', $url)) {
                    $clean .= ' src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"';
                }
            }

            // Allowlist safe display attributes only
            foreach (['width', 'height', 'title'] as $attr) {
                if (preg_match('/\b' . $attr . '\s*=\s*"([^"]*?)"/i', $attrs, $m2)) {
                    $clean .= ' ' . $attr . '="' . htmlspecialchars($m2[1], ENT_QUOTES, 'UTF-8') . '"';
                }
            }

            if ($clean === '') {
                // No valid src — discard the iframe entirely
                return '';
            }

            // sandbox WITHOUT allow-same-origin so iframe JS cannot access parent cookies/DOM
            $key = sprintf($placeholder, $idx++);
            $safeIframes[$key] = '<iframe' . $clean
                . ' sandbox="allow-scripts allow-forms allow-popups"'
                . ' referrerpolicy="no-referrer"'
                . ' loading="lazy">';

            return $key;
        }, $html) ?? $html;

        // 2. Run the centralized sanitizer (strips scripts, on* handlers, dangerous schemes, etc.)
        $html = HtmlSanitizer::sanitize($html);

        // 3. Restore validated iframes
        foreach ($safeIframes as $key => $iframeTag) {
            $html = str_replace($key, $iframeTag, $html);
        }

        return $html;
    }

    public function index()
    {
        $pages = (new Page())->getAll();

        include ROOT_PATH . '/admin/templates/header.php';
        include ROOT_PATH . '/admin/templates/pages/index.php';
        include ROOT_PATH . '/admin/templates/footer.php';
    }

    public function create()
    {
        include ROOT_PATH . '/admin/templates/header.php';
        include ROOT_PATH . '/admin/templates/pages/form.php';
        include ROOT_PATH . '/admin/templates/footer.php';
    }

    public function store()
    {
        Csrf::check();

        $data = [
            'title'            => trim((string)($_POST['title'] ?? '')),
            'slug'             => trim((string)($_POST['slug'] ?? '')),
            'content'          => $this->sanitizePageContent((string)($_POST['content'] ?? '')),
            'status'           => in_array(($_POST['status'] ?? ''), ['published', 'draft'], true)
                                    ? $_POST['status']
                                    : 'draft',
            'meta_title'       => trim((string)($_POST['meta_title'] ?? '')),
            'meta_description' => trim((string)($_POST['meta_description'] ?? '')),
            'show_in_menu'     => isset($_POST['show_in_menu']) ? 1 : 0,
        ];

        (new Page())->create($data);
        header('Location: /admin/pages');
        exit;
    }

    public function edit($id)
    {
        $page = (new Page())->find($id);

        include ROOT_PATH . '/admin/templates/header.php';
        include ROOT_PATH . '/admin/templates/pages/form.php';
        include ROOT_PATH . '/admin/templates/footer.php';
    }

    public function update($id)
    {
        Csrf::check();

        $data = [
            'title'            => trim((string)($_POST['title'] ?? '')),
            'slug'             => trim((string)($_POST['slug'] ?? '')),
            'content'          => $this->sanitizePageContent((string)($_POST['content'] ?? '')),
            'status'           => in_array(($_POST['status'] ?? ''), ['published', 'draft'], true)
                                    ? $_POST['status']
                                    : 'draft',
            'meta_title'       => trim((string)($_POST['meta_title'] ?? '')),
            'meta_description' => trim((string)($_POST['meta_description'] ?? '')),
            'show_in_menu'     => isset($_POST['show_in_menu']) ? 1 : 0,
        ];

        (new Page())->update((int)$id, $data);
        header('Location: /admin/pages');
        exit;
    }

    public function delete($id)
    {
        $pageModel = new Page();
        $id = (int) $id;

        if ($id <= 0) {
            header('Location: /admin/pages');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            Csrf::check();
            $pageModel->delete($id);
            header('Location: /admin/pages');
            exit;
        }

        $page = $pageModel->find($id);

        include ROOT_PATH . '/admin/templates/header.php';
        include ROOT_PATH . '/admin/templates/pages/delete_confirm.php';
        include ROOT_PATH . '/admin/templates/footer.php';
    }
}
