<?php
/**
 * LLMS.txt file generator
 */
if (!defined('ABSPATH')) {
    exit;
}

class CCSPLLMS_Generator {
    
    private $content = '';
    private $stats = array();
    
    public function generate_file() {
        $this->content = '';
        $this->stats = array('posts' => 0, 'pages' => 0, 'total' => 0);
        
        // Start building content
        $this->add_header();
        $this->add_content_sections();
        $this->add_footer();
        
        // Save to file and cache
        $this->save_file();
        $this->cache_content();
        
        // Log generation
        $this->log_generation();
        
        return true;
    }
    
    private function add_header() {
        $site_title = get_option('ccspllms_site_title') ?: get_bloginfo('name');
        $site_tagline = get_option('ccspllms_site_tagline') ?: get_bloginfo('description');
        
        $this->content .= "# {$site_title}\n\n";
        if ($site_tagline) {
            $this->content .= "> {$site_tagline}\n\n";
        }
    }
    
    private function add_content_sections() {
            $post_types = get_option('ccspllms_post_types', array('post', 'page'));

            // Ensure $post_types is always an array
            if (!is_array($post_types)) {
                if (empty($post_types)) {
                    $post_types = array();
                } else {
                    $post_types = explode(',', $post_types);
                    $post_types = array_map('trim', $post_types);
                }
            }

            foreach ($post_types as $post_type) {
                if (!empty($post_type)) {
                    $this->add_post_type_section($post_type);
                }
            }
        }

    
    private function add_post_type_section($post_type) {
        $post_type_obj = get_post_type_object($post_type);
        $label = $post_type_obj->labels->name;
        
        $posts = $this->get_posts_for_type($post_type);
        
        if (empty($posts)) {
            return;
        }
        
        $this->content .= "## {$label}\n";
        
        foreach ($posts as $post) {
            $this->add_post_entry($post);
            $this->stats[$post_type] = ($this->stats[$post_type] ?? 0) + 1;
            $this->stats['total']++;
        }
        
        $this->content .= "\n";
    }
    
    private function get_posts_for_type($post_type) {
        $args = array(
            'post_type' => $post_type,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => '_ccspllms_excluded',
                    'value' => '0',
                    'compare' => '='
                ),
                array(
                    'key' => '_ccspllms_excluded',
                    'compare' => 'NOT EXISTS'
                )
            )
        );
        
        return get_posts($args);
    }
    
    private function add_post_entry($post) {
        $title = $post->post_title;
        $url = $this->get_post_url($post);
        $description = $this->get_post_description($post);
        
        $this->content .= "- [{$title}]({$url}): {$description}\n";
    }
    
    private function get_post_url($post) {
        if (get_option('ccspllms_use_canonical', 1)) {
            // Try to get canonical URL from SEO plugins
            $canonical = $this->get_canonical_url($post->ID);
            if ($canonical) {
                return $canonical;
            }
        }
        
        return get_permalink($post->ID);
    }
    
    private function get_canonical_url($post_id) {
        // Yoast SEO
        if (function_exists('wpseo_get_canonical')) {
            return wpseo_get_canonical($post_id);
        }
        
        // RankMath
        if (function_exists('rank_math_get_canonical_url')) {
            return rank_math_get_canonical_url($post_id);
        }
        
        // All in One SEO
        if (function_exists('aioseo_get_canonical_url')) {
            return aioseo_get_canonical_url($post_id);
        }
        
        return false;
    }
    
    private function get_post_description($post) {
        // Check for custom content first
        $custom_content = get_post_meta($post->ID, '_ccspllms_custom_content', true);
        if (!empty($custom_content)) {
            return $this->truncate_text($custom_content);
        }
        
        $priority = get_option('ccspllms_excerpt_priority', 'excerpt_meta_content');
        $word_limit = get_option('ccspllms_word_limit', 50);
        
        switch ($priority) {
            case 'excerpt_meta_content':
                return $this->get_excerpt_meta_content($post, $word_limit);
            case 'meta_excerpt_content':
                return $this->get_meta_excerpt_content($post, $word_limit);
            case 'content_excerpt_meta':
                return $this->get_content_excerpt_meta($post, $word_limit);
            default:
                return $this->get_excerpt_meta_content($post, $word_limit);
        }
    }
    
    private function get_excerpt_meta_content($post, $word_limit) {
        // Try excerpt first
        if (!empty($post->post_excerpt)) {
            return $this->truncate_text($post->post_excerpt, $word_limit);
        }
        
        // Try meta description
        $meta_desc = $this->get_meta_description($post->ID);
        if (!empty($meta_desc)) {
            return $this->truncate_text($meta_desc, $word_limit);
        }
        
        // Fall back to content
        return $this->get_content_excerpt($post->post_content, $word_limit);
    }
    
    private function get_meta_excerpt_content($post, $word_limit) {
        // Try meta description first
        $meta_desc = $this->get_meta_description($post->ID);
        if (!empty($meta_desc)) {
            return $this->truncate_text($meta_desc, $word_limit);
        }
        
        // Try excerpt
        if (!empty($post->post_excerpt)) {
            return $this->truncate_text($post->post_excerpt, $word_limit);
        }
        
        // Fall back to content
        return $this->get_content_excerpt($post->post_content, $word_limit);
    }
    
    private function get_content_excerpt_meta($post, $word_limit) {
        // Try content first
        $content_excerpt = $this->get_content_excerpt($post->post_content, $word_limit);
        if (!empty($content_excerpt)) {
            return $content_excerpt;
        }
        
        // Try excerpt
        if (!empty($post->post_excerpt)) {
            return $this->truncate_text($post->post_excerpt, $word_limit);
        }
        
        // Fall back to meta description
        $meta_desc = $this->get_meta_description($post->ID);
        return $this->truncate_text($meta_desc ?: 'No description available', $word_limit);
    }
    
    private function get_meta_description($post_id) {
        // Yoast SEO
        $yoast_desc = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
        if (!empty($yoast_desc)) {
            return $yoast_desc;
        }
        
        // RankMath
        $rankmath_desc = get_post_meta($post_id, 'rank_math_description', true);
        if (!empty($rankmath_desc)) {
            return $rankmath_desc;
        }
        
        // All in One SEO
        $aioseo_desc = get_post_meta($post_id, '_aioseo_description', true);
        if (!empty($aioseo_desc)) {
            return $aioseo_desc;
        }
        
        return '';
    }
    
    private function get_content_excerpt($content, $word_limit) {
        $content = wp_strip_all_tags($content);
        $content = preg_replace('/\s+/', ' ', $content);
        return $this->truncate_text($content, $word_limit);
    }
    
    private function truncate_text($text, $word_limit = 50) {
        $words = explode(' ', $text);
        if (count($words) > $word_limit) {
            $words = array_slice($words, 0, $word_limit);
            return implode(' ', $words) . '...';
        }
        return $text;
    }
    
    private function add_footer() {
        $this->content .= "\n[comment]: # (Generated by CLOUDCUSP on " . current_time('Y-m-d H:i:s') . ")\n";
    }
    
    private function save_file() {
        $upload_dir = wp_upload_dir();
        $file_path = ABSPATH . 'llms.txt';
        
        file_put_contents($file_path, $this->content);
        
        // Also save backup in uploads directory
        $backup_path = $upload_dir['basedir'] . '/ccspllms-backup.txt';
        file_put_contents($backup_path, $this->content);
    }
    
    private function cache_content() {
        set_transient('ccspllms_cached_content', $this->content, DAY_IN_SECONDS);
        update_option('ccspllms_last_generated', current_time('mysql'));
        update_option('ccspllms_file_stats', $this->stats);
    }
    
    public function get_cached_content() {
        return get_transient('ccspllms_cached_content');
    }
    
    public function get_file_size() {
        $file_path = ABSPATH . 'llms.txt';
        if (file_exists($file_path)) {
            return size_format(filesize($file_path));
        }
        return '0 B';
    }
    
/**
 * Log a generation event into the database.
 *
 * @return void
 */
    private function log_generation() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'ccspllms_generation_log';

        // Sanitize/validate values before insert.
        $generated_at = current_time( 'mysql' );
        $posts_count  = isset( $this->stats['total'] ) ? absint( $this->stats['total'] ) : 0;
        $file_size    = isset( $this->content ) ? strlen( (string) $this->content ) : 0;
        $trigger_type = 'manual'; // Could be dynamic later.

        $inserted = $wpdb->insert(
            $table_name,
            array(
                'generated_at' => $generated_at,
                'posts_count'  => $posts_count,
                'file_size'    => $file_size,
                'trigger_type' => sanitize_text_field( $trigger_type ),
            ),
            array( '%s', '%d', '%d', '%s' )
        );

        // Handle DB insert errors.
        if ( false === $inserted ) {
            error_log(
                sprintf(
                    '[CCSP LLms.txt Generator]: Failed to log generation. DB error: %s | Data: posts=%d, size=%d, trigger=%s',
                    $wpdb->last_error,
                    $posts_count,
                    $file_size,
                    $trigger_type
                )
            );
        }
    }

}