<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Module_Posts extends SBPAI_Module_Base {

    public function generate() {
        $post_type = isset( $this->args['post_type'] ) ? $this->args['post_type'] : 'post';
        $status    = isset( $this->args['status'] ) ? $this->args['status'] : 'publish';
        $author    = isset( $this->args['author'] ) ? $this->args['author'] : 'random';
        $source    = isset( $this->args['source'] ) ? $this->args['source'] : 'hybrid';
        $builder   = isset( $this->args['builder'] ) ? $this->args['builder'] : 'gutenberg';
        $date_from = isset( $this->args['date_from'] ) && !empty($this->args['date_from']) ? $this->args['date_from'] : '';
        $date_to   = isset( $this->args['date_to'] ) && !empty($this->args['date_to']) ? $this->args['date_to'] : '';
        $use_image    = isset( $this->args['image'] ) ? intval($this->args['image']) : 1;
        $use_terms    = isset( $this->args['terms'] ) ? intval($this->args['terms']) : 1;
        $use_comments = isset( $this->args['comments'] ) ? intval($this->args['comments']) : 0;

        $length_setting = isset( $this->args['length'] ) ? $this->args['length'] : 'medium';
        $p_count = 4;
        $ai_directive = '';

        if ( $length_setting === 'short' ) {
            $p_count = wp_rand( 1, 2 );
            $ai_directive = 'Keep the content very brief, short, and concise. Around 1-2 paragraphs.';
        } elseif ( $length_setting === 'long' ) {
            $p_count = wp_rand( 8, 14 );
            $ai_directive = 'Write a very long, comprehensive, in-depth guide spanning multiple detailed paragraphs.';
        } else {
            $p_count = wp_rand( 4, 6 ); // Medium
            $ai_directive = 'Write a standard length medium article of about 4-6 paragraphs.';
        }

        // Content Engine — title and content generated together for topical coherence
        if ( $source === 'ai' || $source === 'hybrid' ) {
            $pair    = SBPAI_Service_AI::generate_title_and_content( $post_type, $source, $ai_directive, $p_count );
            $title   = $pair['title'];
            $raw_txt = $pair['content'];
        } elseif ( $source === 'faker' ) {
            // Curated English library (niche-aware, no Latin lorem ipsum)
            $pair    = SBPAI_Service_AI::generate_title_and_content( $post_type, 'faker', $ai_directive, $p_count );
            $title   = $pair['title'];
            $raw_txt = $pair['content'];
        } else {
            $pair    = SBPAI_Service_AI::generate_title_and_content( $post_type, 'hybrid', $ai_directive, $p_count );
            $title   = $pair['title'];
            $raw_txt = $pair['content'];
        }

        $excerpt = $this->faker->sentence;

        // Author
        $author_id = 1;
        if ( $author === 'random' ) {
            $users = get_users( array( 'role__in' => array( 'administrator', 'editor', 'author' ), 'fields' => 'ids' ) );
            if ( ! empty( $users ) ) $author_id = $users[ array_rand( $users ) ];
        } elseif ( is_numeric( $author ) ) {
            $author_id = intval( $author );
        }

        // Date Handling
        $date = current_time('mysql');
        if ( $date_from && $date_to ) {
            $stamp_from = strtotime($date_from);
            $stamp_to = strtotime($date_to);
            if ( $stamp_to >= $stamp_from ) {
                $random_stamp = wp_rand( $stamp_from, $stamp_to );
                $date = gmdate( 'Y-m-d H:i:s', $random_stamp );
            }
        }

        $content = "<h2>{$title}</h2>\n<p>{$raw_txt}</p>";
        $this->transform_builder_content( $content, $builder, $title, $raw_txt );

        $post_data = array(
            'post_title'   => apply_filters( 'sbpai_post_title', $title ),
            'post_content' => apply_filters( 'sbpai_post_content', $content ),
            'post_excerpt' => $excerpt,
            'post_status'  => $status,
            'post_type'      => $post_type,
            'post_author'    => $author_id,
            'post_date'      => $date,
            'comment_status' => $use_comments ? 'open' : get_option('default_comment_status'),
        );

        $post_id = wp_insert_post( $post_data );

        if ( ! is_wp_error( $post_id ) ) {
            $this->track_dummy( $post_id, 'post' );
            
            $this->apply_builder_meta( $post_id, $builder, $raw_txt );
            
            if ( $use_terms ) {
                $this->assign_random_terms( $post_id, 'category' );
                $this->assign_random_terms( $post_id, 'post_tag' );
            }

            if ( $use_comments ) {
                $this->generate_random_comments( $post_id );
            }

            if ( $use_image ) {
                $img_keyword = get_option('sbpai_active_niche', 'General');
                $img = SBPAI_Service_Media::fetch_image( 1200, 600, $img_keyword );
                if ( $img ) set_post_thumbnail( $post_id, $img );
            }

            return $post_id;
        }
        return false;
    }

    private function transform_builder_content( &$content, $builder, $title, $raw_txt ) {
        if ( $builder === 'gutenberg' ) {
            $content = "<!-- wp:heading --><h2>{$title}</h2><!-- /wp:heading -->\n\n<!-- wp:paragraph --><p>{$raw_txt}</p><!-- /wp:paragraph -->";
        } elseif ( $builder === 'wpbakery' ) {
            $content = "[vc_row][vc_column][vc_column_text]<h2>{$title}</h2><p>{$raw_txt}</p>[/vc_column_text][/vc_column][/vc_row]";
        } elseif ( $builder === 'divi' ) {
            $content = "[et_pb_section][et_pb_row][et_pb_column type=\"4_4\"][et_pb_text]<h2>{$title}</h2><p>{$raw_txt}</p>[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]";
        }
    }

    private function apply_builder_meta( $post_id, $builder, $raw_txt ) {
        if ( $builder === 'elementor' ) {
            $elementor_data = array(
                array( 'id' => uniqid(), 'elType' => 'section', 'settings' => array(), 'elements' => array( array( 'id' => uniqid(), 'elType' => 'column', 'settings' => array('_column_size' => 100), 'elements' => array( array( 'id' => uniqid(), 'elType' => 'widget', 'widgetType' => 'text-editor', 'settings' => array('editor' => "<p>{$raw_txt}</p>") ) ) ) ) )
            );
            update_post_meta( $post_id, '_elementor_data', wp_slash( wp_json_encode( $elementor_data ) ) );
            update_post_meta( $post_id, '_elementor_edit_mode', 'builder' );

        } elseif ( $builder === 'bricks' ) {
            $bricks_data = array(
                array( 'id' => uniqid(), 'name' => 'section', 'settings' => array(), 'children' => array( array( 'id' => uniqid(), 'name' => 'container', 'settings' => array(), 'children' => array( array( 'id' => uniqid(), 'name' => 'text', 'settings' => array('text' => $raw_txt) ) ) ) ) )
            );
            update_post_meta( $post_id, '_bricks_page_content_2', $bricks_data );
        }
    }

    private function assign_random_terms( $post_id, $taxonomy ) {
        if ( ! taxonomy_exists( $taxonomy ) ) return;
        
        $terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false ) );
        if ( empty( $terms ) || count( $terms ) < 5 ) {
            $prefix = get_option('sbpai_active_niche', 'General');
            for ( $i = 0; $i < 5; $i++ ) {
                $term_name = ( $prefix !== 'General' ? $prefix . ' ' : '' ) . ucfirst( $this->faker->word );
                wp_insert_term( $term_name, $taxonomy );
            }
            $terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false ) );
        }
        
        if ( ! empty( $terms ) ) {
            shuffle( $terms );
            $selected = array_slice( $terms, 0, wp_rand( 1, 3 ) );
            $term_ids = array_map( function( $t ) { return $t->term_id; }, $selected );
            wp_set_post_terms( $post_id, $term_ids, $taxonomy );
        }
    }

    private function generate_random_comments( $post_id ) {
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin dummy-user lookup for comment authoring.
        $users = get_users( array( 'meta_key' => '_sbpai_user', 'meta_value' => '1', 'number' => 20 ) );

        $num_comments = wp_rand( 1, 5 ); // Guarantee at least 1 comment so the feature is visible

        for ( $i = 0; $i < $num_comments; $i++ ) {
            $time = current_time('mysql');
            
            if ( ! empty( $users ) ) {
                $user = $users[ array_rand( $users ) ];
                $author_name  = sanitize_text_field($user->display_name);
                $author_email = sanitize_email($user->user_email);
                $user_id      = $user->ID;
            } else {
                // Anonymous fallback if no dummy users exist
                $author_name  = $this->faker->name;
                $author_email = $this->faker->safeEmail;
                $user_id      = 0;
            }
            
            $data = array(
                'comment_post_ID'      => $post_id,
                'comment_author'       => $author_name,
                'comment_author_email' => $author_email,
                'comment_content'      => $this->faker->sentence( wp_rand(5, 20) ),
                'comment_type'         => 'comment',
                'comment_parent'       => 0,
                'user_id'              => $user_id,
                'comment_author_IP'    => $this->faker->ipv4,
                'comment_agent'        => $this->faker->userAgent,
                'comment_date'         => $time,
                'comment_approved'     => 1,
            );

            wp_insert_comment( $data );
        }
    }
}
