<?php
// File: modules/create-custom-html-page.php

defined('ABSPATH') || exit;

// Shared key validation across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/create-raw-html-page', [
        'methods'             => WP_REST_Server::CREATABLE,
        'callback'            => 'myaio_sac_create_raw_html_page',
        'permission_callback' => 'myaio_sac_rest_permission_check',
        'args'                => [
            'slug' => [
                'type'              => 'string',
                'required'          => true,
                'sanitize_callback' => 'sanitize_title',
                'validate_callback' => function ($value) {
                    return is_string($value) && trim($value) !== '';
                },
            ],
            'title' => [
                'type'              => 'string',
                'required'          => true,
                'sanitize_callback' => 'sanitize_text_field',
                'validate_callback' => function ($value) {
                    return is_string($value) && trim($value) !== '';
                },
            ],
            'html' => [
                'type'              => 'string',
                'required'          => true,
                // no sanitize_callback here to preserve raw input;
                // we will sanitize before saving (wp_kses_post by default).
                'validate_callback' => function ($value) {
                    return is_string($value) && trim($value) !== '';
                },
            ],
        ],
    ]);
});

if (!function_exists('myaio_sac_create_raw_html_page')) {
    function myaio_sac_create_raw_html_page(WP_REST_Request $request) {
        $slug  = sanitize_title((string) $request->get_param('slug'));
        $title = sanitize_text_field((string) $request->get_param('title'));
        $html  = (string) $request->get_param('html');

        // Preserve same behavior: if slug exists -> 409 with same message
        $existing = get_page_by_path($slug, OBJECT, 'page');
        if ($existing) {
            return new WP_REST_Response(['error' => 'Page with this slug already exists.'], 409);
        }

        /**
         * By default, store "safe raw HTML" (WordPress-allowed HTML).
         * If you absolutely need full raw HTML, you can opt-in via filter:
         * add_filter('myaio_sac_allow_unsafe_raw_html', '__return_true');
         */
        $allow_unsafe = (bool) apply_filters('myaio_sac_allow_unsafe_raw_html', false, $request);

        $html_to_store = $allow_unsafe ? $html : wp_kses_post($html);

        $page_id = wp_insert_post([
            'post_title'   => $title,
            'post_name'    => $slug,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => '<!-- placeholder -->',
            'meta_input'   => [
                '_custom_raw_html' => $html_to_store,
            ],
        ], true);

        // Preserve same output: 500 with same message
        if (is_wp_error($page_id) || empty($page_id)) {
            return new WP_REST_Response(['error' => 'Failed to create page.'], 500);
        }

        // Preserve same output: 201 + same keys
        return new WP_REST_Response([
            'success' => true,
            'page_id' => (int) $page_id,
            'url'     => get_permalink($page_id),
        ], 201);
    }
}
