<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Module_Pages extends SBPAI_Module_Base {
    public function generate() {
        $title = SBPAI_Service_AI::generate_text( 'Generate a page title' );
        
        $content = "<!-- wp:paragraph --><p>" . SBPAI_Service_AI::generate_text('Page intro') . "</p><!-- /wp:paragraph -->\n\n";
        $content .= "<!-- wp:heading --><h2>" . SBPAI_Service_AI::generate_text('heading') . "</h2><!-- /wp:heading -->\n\n";
        $content .= "<!-- wp:paragraph --><p>" . SBPAI_Service_AI::generate_text('Page body') . "</p><!-- /wp:paragraph -->\n\n";

        $content = apply_filters( 'sbpai_generated_content', $content );

        $parent = 0;
        if ( wp_rand( 1, 2 ) === 1 ) {
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin dummy-page parent lookup.
            $parents = get_pages( array( 'meta_key' => '_sbpai_post', 'meta_value' => '1', 'number' => 20 ) );
            if ( ! empty( $parents ) ) {
                $parent = $parents[array_rand( $parents )]->ID;
            }
        }

        $post_id = wp_insert_post( array(
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_parent'  => $parent
        ) );

        if ( ! is_wp_error( $post_id ) ) {
            $this->track_dummy( $post_id, 'post' );
            return $post_id;
        }
        return false;
    }
}
