<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Trendly_AI_Post_Post_Generator {
    private $api;

    public function __construct() {
        $this->api = new Trendly_AI_Post_API_Handler();
    }

    public function generate_and_publish_from_trends() : void {
        $opts = get_option( 'trendly_ai_post_options', [] );
        $region = $opts['region'] ?? 'IN';
        $length = $opts['default_length'] ?? 'medium';
        $img_count = intval( $opts['default_image_count'] ?? ( $opts['image_count'] ?? 1 ) );
        if ( $img_count < 1 ) { $img_count = 1; }
        if ( $img_count > 4 ) { $img_count = 4; }
        $topics = $this->api->fetch_trending_topics( $region, 10 );
        if ( empty( $topics ) ) return;

        // Avoid duplicates by checking if a post with similar title exists
        $dup = new Trendly_AI_Post_Duplicate();

        foreach ( $topics as $topic ) {
            if ( $dup->title_exists( $topic ) ) {
                continue;
            }
            $this->generate_single_post( $topic, $length, 'publish', $img_count );
            // Only 1 post per run for now
            break;
        }
    }

    public function generate_single_post( string $topic, string $length = 'medium', string $status = 'draft', int $image_count = 1 ) : int {
        $data = $this->api->generate_content_with_gemini( $topic, $length );
        $title = $data['title'] ?? $topic;
        $content = $data['content'] ?? '';
        $meta_desc = $data['meta_description'] ?? '';

        // Insert post
        $opts = get_option( 'trendly_ai_post_options', [] );
        $postarr = [
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => $status,
            'post_author'  => intval( $opts['default_author'] ?? get_current_user_id() ),
            'post_category'=> [ intval( $opts['default_category'] ?? 0 ) ],
        ];
        $post_id = wp_insert_post( wp_slash( $postarr ), true );
        if ( is_wp_error( $post_id ) ) {
            return 0;
        }

        if ( ! empty( $meta_desc ) ) {
            update_post_meta( $post_id, '_trendly_meta_description', sanitize_text_field( $meta_desc ) );
        }

        // Images
        $images = $this->api->fetch_images_from_pexels( $topic, max(1, $image_count) );
        if ( ! empty( $images ) ) {
            $this->attach_images_to_post( $post_id, $images );

            $attached_ids = get_post_meta( $post_id, '_trendly_image' );
            if ( ! empty( $attached_ids ) ) {
                // Insert up to the requested number of images at RANDOM paragraph positions
                $current = get_post_field( 'post_content', $post_id );
                $max_insert = min( max(1, $image_count), count( $attached_ids ) );
                // Split content into tokens preserving </p>
                $tokens = preg_split( '/(<\/p>)/i', $current, -1, PREG_SPLIT_DELIM_CAPTURE );
                $para_indices = [];
                for ( $i = 0; $i < count( $tokens ); $i++ ) {
                    if ( isset($tokens[$i]) && preg_match('/<\/p>/i', $tokens[$i]) ) {
                        $para_indices[] = $i; // index of closing </p> token
                    }
                }
                if ( empty( $para_indices ) ) {
                    // If no paragraphs, prepend first image only
                    $img_id  = intval( $attached_ids[0] );
                    $img_url = wp_get_attachment_image_url( $img_id, 'large' );
                    if ( $img_url ) {
                        $insertion = "\n<p><img src=\"" . esc_url( $img_url ) . "\" alt=\"" . esc_attr( $title ) . "\" /></p>\n";
                        $current = $insertion . $current;
                        wp_update_post( [ 'ID' => $post_id, 'post_content' => $current ] );
                    }
                } else {
                    // Choose random unique paragraph positions to insert after
                    $available = range( 0, count($para_indices)-1 );
                    shuffle( $available );
                    $chosen = array_slice( $available, 0, min( $max_insert, count($available) ) );
                    sort( $chosen );
                    $img_i = 0;
                    $built = '';
                    $para_counter = -1;
                    for ( $i = 0; $i < count( $tokens ); $i++ ) {
                        $built .= $tokens[$i];
                        if ( preg_match('/<\/p>/i', $tokens[$i]) ) {
                            $para_counter++;
                            if ( in_array( $para_counter, $chosen, true ) && $img_i < $max_insert ) {
                                $img_id  = intval( $attached_ids[$img_i] );
                                $img_url = wp_get_attachment_image_url( $img_id, 'large' );
                                if ( $img_url ) {
                                    $built .= "\n<p><img src=\"" . esc_url( $img_url ) . "\" alt=\"" . esc_attr( $title ) . "\" /></p>\n";
                                }
                                $img_i++;
                            }
                        }
                    }
                    wp_update_post( [ 'ID' => $post_id, 'post_content' => $built ] );
                }
            }
        }

        return intval( $post_id );
    }

    private function attach_images_to_post( int $post_id, array $image_urls ) : void {
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

        $featured_set = false;
        foreach ( $image_urls as $url ) {
            $tmp = download_url( $url );
            if ( is_wp_error( $tmp ) ) continue;
            $file_array = [
                'name' => basename( (string) wp_parse_url( $url, PHP_URL_PATH ) ),
                'tmp_name' => $tmp,
            ];
            $id = media_handle_sideload( $file_array, $post_id );
            if ( is_wp_error( $id ) ) {
                if ( ! empty( $file_array['tmp_name'] ) ) {
                    wp_delete_file( $file_array['tmp_name'] );
                }
                continue;
            }
            // Set alt text for SEO
            $post_title = get_the_title( $post_id );
            if ( $post_title ) {
                update_post_meta( $id, '_wp_attachment_image_alt', wp_strip_all_tags( $post_title ) );
            }
            if ( ! $featured_set ) {
                set_post_thumbnail( $post_id, $id );
                $featured_set = true;
            }
            // Add to gallery
            add_post_meta( $post_id, '_trendly_image', $id );
        }
    }
}
