<?php
/**
 * AI Auto Tool - Web Stories Generator
 * 
 * Automatically converts WordPress posts into Google Web Stories (AMP Stories).
 * Web Stories are a visual storytelling format that provides a full-screen,
 * immersive experience optimized for mobile devices.
 * 
 * Features:
 * - Automatic story generation from posts
 * - Custom rewrite rules (/aiwebstories/)
 * - AMP-compliant story pages
 * - RSS feed for stories
 * - Google Analytics integration
 * - Social sharing support
 * - Custom audio and publisher logo
 * 
 * @package AI_Auto_Tool
 * @subpackage Web_Stories
 * @since 1.0.0
 * 
 * Story URLs:
 * - List: domain.com/aiwebstories/
 * - Single: domain.com/aiwebstories/post-slug/
 * - Feed: domain.com/aiwebstories/feed/
 * 
 * @link https://amp.dev/documentation/guides-and-tutorials/start/visual_story/
 * @link https://developers.google.com/search/docs/advanced/appearance/enable-web-stories
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

if (!class_exists('AIautotool_Web_Stories')) {
class AIautotool_Web_Stories extends rendersetting {
    
    /**
     * Feature active status
     * @var bool
     */
    public $active = false;
    
    /**
     * Active option name in database
     * @var string
     */
    public $active_option_name = 'Aiautotool_webstories_active';
    
    /**
     * URL slug for stories
     * @var string
     */
    public $slugname = '';
    
    /**
     * Settings array
     * @var array
     */
    public $setting;
    
    /**
     * Settings option name
     * @var string
     */
    public $namesetting = 'aiautotool_config_webstories_settings';
    
    /**
     * Rewrite rules flushed flag
     * @var string
     */
    public $aiautotool_rewriter_flushed = 'aiautotool_rewriter_flushed';
    
    /**
     * Feature icon
     * @var string
     */
    public $icon = '<i class="fa-solid fa-book-open"></i>';
    
    /**
     * Client instance (reserved for future use)
     * @var mixed
     */
    private $client = null;
    
    /**
     * Notices array
     * @var array
     */
    public $notices = [];
    
    /**
     * Stories per page limit
     * @var int
     */
    public $limit = 50;
    
    /**
     * Plan limit
     * @var mixed
     */
    private $plan_limit_aiautotool;
    
    /**
     * Plan name
     * @var string
     */
    public $name_plan;
    
    /**
     * Configuration array
     * @var array
     */
    public $config = array();
    
    /**
     * Notice message
     * @var string
     */
    public $notice;

    /**
     * Constructor
     * 
     * Initializes the Web Stories feature:
     * - Loads settings from database
     * - Sets default logo if not configured
     * - Checks if feature is active
     * - Registers AJAX handlers
     * 
     * @since 1.0.0
     */
    public function __construct() {
        $this->name_plan = __('Webstories', 'ai-auto-tool');
        $this->setting = get_option($this->namesetting, array());
        
        // Set default logo if not configured
        if (!isset($this->setting['logo'])) {
            // Use local plugin logo as fallback instead of external URL
            $this->setting['logo'] = defined('AIAUTOTOOL_URI') 
                ? AIAUTOTOOL_URI . 'images/logo.svg' 
                : plugins_url('../../images/logo.svg', __FILE__);
        }

        $this->active = get_option($this->active_option_name, false);
        
        // Initialize if active
        if ($this->active == 'true') {
            $this->init();
        }
        
        // Register AJAX handlers
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
    }

    /**
     * AJAX callback to update active option
     * 
     * Handles the activation/deactivation of the feature.
     * Verifies nonce for security.
     * 
     * @since 1.0.0
     * @return void Dies after output
     */
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, null, 'no');
            
            // Flush rewrite rules on activation
            if ($active === 'true') {
                delete_option($this->aiautotool_rewriter_flushed);
            }
            
            echo $active;
        }

        wp_die();
    }

    /**
     * Initialize the feature
     * 
     * Registers all necessary hooks:
     * - Custom rewrite rules
     * - Query vars
     * - Template include
     * - Settings registration
     * 
     * @since 1.0.0
     * @return void
     */
    public function init() {
        // Hook into WordPress to register the custom URL
        add_action('init', array($this, 'add_custom_rewrite_rule'));

        // Hook into WordPress to add custom rewrite rules
        add_filter('query_vars', array($this, 'custom_rewrite_query_vars'));

        // Hook into WordPress to handle the custom template
        add_filter('template_include', array($this, 'custom_rewrite_rule_template'));
        
        // Register settings
        register_setting('aiautotool_webstories_config_group', $this->namesetting, array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_webstories_setting'),
        ));
    }
    
    /**
     * Sanitize webstories setting
     * 
     * @param mixed $value Input value
     * @return array Sanitized array
     */
    public function sanitize_webstories_setting($value) {
        if (!is_array($value)) {
            return array();
        }
        return map_deep($value, 'sanitize_text_field');
    }

    /**
     * Render settings page
     * 
     * Displays the configuration interface for:
     * - Publisher logo (96x96px)
     * - Background audio files (MP3)
     * - Story link in posts option
     * - Google Analytics ID
     * 
     * @since 1.0.0
     * @return void
     */
    public function render_setting() {
        ?>
        <div id="tab-webstorie-setting" class="tab-content" style="display:none;">
            <h2><?php echo $this->icon; ?> <?php esc_html_e('Website Stories Configuration', 'ai-auto-tool'); ?></h2>
            
            <!-- Preview Links -->
            <div class="aiautotool-info-box" style="background: #e7f3ff; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #2196f3;">
                <h3 style="margin-top: 0;">
                    <i class="fa-solid fa-info-circle"></i>
                    <?php esc_html_e('Web Stories URLs', 'ai-auto-tool'); ?>
                </h3>
                <p class="ft-note">
                    <i class="fa-solid fa-list"></i>
                    <strong><?php esc_html_e('Stories List', 'ai-auto-tool'); ?>:</strong> 
                    <a href="<?php echo esc_url(get_home_url()); ?>/aiwebstories/" target="_blank">
                        <?php echo esc_url(get_home_url()); ?>/aiwebstories/
                    </a>
                </p>
                <p class="ft-note">
                    <i class="fa-solid fa-rss"></i>
                    <strong><?php esc_html_e('Stories RSS Feed', 'ai-auto-tool'); ?>:</strong> 
                    <a href="<?php echo esc_url(get_home_url()); ?>/aiwebstories/feed/" target="_blank">
                        <?php echo esc_url(get_home_url()); ?>/aiwebstories/feed/
                    </a>
                </p>
                <p class="ft-note" style="margin-bottom: 0;">
                    <i class="fa-solid fa-lightbulb"></i>
                    <?php esc_html_e('Stories are automatically generated from posts with featured images.', 'ai-auto-tool'); ?>
                </p>
            </div>

            <form method="post" action="options.php">
                <?php settings_fields('aiautotool_webstories_config_group'); ?>
                
                <!-- Publisher Logo -->
                <div class="aiautotool-setting-section" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3>
                        <i class="fa-solid fa-image"></i>
                        <?php esc_html_e('Publisher Logo', 'ai-auto-tool'); ?>
                    </h3>
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Upload your publisher logo. Required size: 96x96 pixels (square).', 'ai-auto-tool'); ?>
                    </p>
                    <p class="ft-note">
                        <i class="fa-solid fa-check-circle" style="color: #4caf50;"></i>
                        <?php esc_html_e('This logo will appear in story metadata and Google Search.', 'ai-auto-tool'); ?>
                    </p>
                    <div style="display:flex; gap: 10px; align-items: center;">
                        <input id="ft-add3" 
                               class="ft-input-big" 
                               name="<?php echo esc_attr($this->namesetting); ?>[logo]" 
                               type="text" 
                               value="<?php echo esc_attr($this->setting['logo']); ?>" 
                               placeholder="<?php esc_html_e('https://example.com/logo.png', 'ai-auto-tool'); ?>"
                               style="flex: 1;">
                        <button class="ft-selec button" data-input-id="ft-add3" type="button">
                            <i class="fa-solid fa-upload"></i> <?php esc_html_e('Upload', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                    <?php if (!empty($this->setting['logo'])): ?>
                    <div style="margin-top: 10px;">
                        <img src="<?php echo esc_url($this->setting['logo']); ?>" 
                             alt="Publisher Logo Preview" 
                             style="max-width: 96px; max-height: 96px; border: 1px solid #ddd; padding: 4px; border-radius: 4px;">
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Background Audio -->
                <div class="aiautotool-setting-section" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3>
                        <i class="fa-solid fa-music"></i>
                        <?php esc_html_e('Background Audio (Optional)', 'ai-auto-tool'); ?>
                    </h3>
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Add background music to your stories. Upload MP3 files for better user experience.', 'ai-auto-tool'); ?>
                    </p>

                    <!-- MP3 File 1 -->
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">
                            <?php esc_html_e('Audio Track 1', 'ai-auto-tool'); ?>
                        </label>
                        <div style="display:flex; gap: 10px;">
                            <input id="ft-mp31" 
                                   class="ft-input-big" 
                                   name="<?php echo esc_attr($this->namesetting); ?>[mp31]" 
                                   type="text" 
                                   value="<?php echo !empty($this->setting['mp31']) ? esc_attr($this->setting['mp31']) : ''; ?>" 
                                   placeholder="<?php esc_html_e('https://example.com/audio1.mp3', 'ai-auto-tool'); ?>"
                                   style="flex: 1;">
                            <button class="ft-selec button" data-input-id="ft-mp31" type="button">
                                <i class="fa-solid fa-upload"></i> <?php esc_html_e('Upload', 'ai-auto-tool'); ?>
                            </button>
                        </div>
                    </div>

                    <!-- MP3 File 2 -->
                    <div>
                        <label style="display: block; margin-bottom: 5px; font-weight: 600;">
                            <?php esc_html_e('Audio Track 2', 'ai-auto-tool'); ?>
                        </label>
                        <div style="display:flex; gap: 10px;">
                            <input id="ft-mp32" 
                                   class="ft-input-big" 
                                   name="<?php echo esc_attr($this->namesetting); ?>[mp32]" 
                                   type="text" 
                                   value="<?php echo !empty($this->setting['mp32']) ? esc_attr($this->setting['mp32']) : ''; ?>" 
                                   placeholder="<?php esc_html_e('https://example.com/audio2.mp3', 'ai-auto-tool'); ?>"
                                   style="flex: 1;">
                            <button class="ft-selec button" data-input-id="ft-mp32" type="button">
                                <i class="fa-solid fa-upload"></i> <?php esc_html_e('Upload', 'ai-auto-tool'); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Story Options -->
                <div class="aiautotool-setting-section" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3>
                        <i class="fa-solid fa-cog"></i>
                        <?php esc_html_e('Story Options', 'ai-auto-tool'); ?>
                    </h3>
                    
                    <div style="margin-bottom: 15px;">
                        <label class="ft-label-right">
                            <?php esc_html_e('Add Story Link to Posts', 'ai-auto-tool'); ?>
                        </label>
                        <p class="ft-note">
                            <i class="fa-solid fa-info-circle"></i>
                            <?php esc_html_e('If enabled, a link to the web story will be added to each post.', 'ai-auto-tool'); ?>
                        </p>
                        <label class="nut-switch">
                            <input type="checkbox" 
                                   name="<?php echo esc_attr($this->namesetting); ?>[addstorietopost]" 
                                   value="1" 
                                   <?php checked(isset($this->setting['addstorietopost']) && $this->setting['addstorietopost'] == 1); ?> />
                            <span class="slider"></span>
                        </label>
                    </div>
                </div>

                <!-- Google Analytics -->
                <div class="aiautotool-setting-section" style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <h3>
                        <i class="fa-brands fa-google"></i>
                        <?php esc_html_e('Google Analytics', 'ai-auto-tool'); ?>
                    </h3>
                    <p class="ft-note">
                        <i class="fa-solid fa-chart-line"></i>
                        <?php esc_html_e('Track your web stories with Google Analytics 4.', 'ai-auto-tool'); ?>
                    </p>
                    <p class="ft-note">
                        <i class="fa-solid fa-lightbulb"></i>
                        <?php esc_html_e('Enter your Google Analytics Measurement ID (format: G-XXXXXXXXXX)', 'ai-auto-tool'); ?>
                    </p>
                    <input class="ft-input-big" 
                           placeholder="<?php esc_attr_e('G-XXXXXXXXXX', 'ai-auto-tool'); ?>" 
                           name="<?php echo esc_attr($this->namesetting); ?>[analytic]" 
                           type="text" 
                           value="<?php echo !empty($this->setting['analytic']) ? esc_attr($this->setting['analytic']) : ''; ?>"/>
                </div>

                <?php submit_button(__('Save All Settings', 'ai-auto-tool'), 'ft-submit'); ?>
            </form>

            <!-- Usage Instructions -->
            <div class="aiautotool-instructions" style="background: #fff3cd; padding: 20px; border-radius: 8px; border-left: 4px solid #ffc107; margin-top: 20px;">
                <h3 style="margin-top: 0;">
                    <i class="fa-solid fa-book-reader"></i>
                    <?php esc_html_e('How to Use Web Stories', 'ai-auto-tool'); ?>
                </h3>
                <ol style="line-height: 1.8;">
                    <li><?php esc_html_e('Create posts with featured images (required for stories)', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Stories are automatically generated from post content', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Visit /aiwebstories/ to see your stories list', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Each post slug becomes a story at /aiwebstories/post-slug/', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Share your stories feed at /aiwebstories/feed/', 'ai-auto-tool'); ?></li>
                    <li><?php esc_html_e('Stories are mobile-optimized and AMP-compliant', 'ai-auto-tool'); ?></li>
                </ol>
                <p style="margin-bottom: 0;">
                    <strong><?php esc_html_e('Note:', 'ai-auto-tool'); ?></strong>
                    <?php esc_html_e('Web Stories work best with high-quality images (minimum 720px wide) and short, concise paragraphs.', 'ai-auto-tool'); ?>
                </p>
            </div>
        </div>
        <?php
    }

    /**
     * Render tab setting button
     * 
     * Adds a tab in the admin settings page when feature is active.
     * 
     * @since 1.0.0
     * @return void
     */
    public function render_tab_setting() {
        if ($this->active == 'true') {
            echo '<button href="#tab-webstorie-setting" class="nav-tab sotab">' . 
                 $this->icon . ' ' . 
                 esc_html__('Web Stories', 'ai-auto-tool') . 
                 '</button>';
        }
    }
    
    /**
     * Render feature box
     * 
     * Displays the feature card in the main plugin dashboard.
     * Loads description from feature-descriptions.php
     * 
     * @since 1.0.0
     * @return void
     */
    public function render_feature() {
        // Load feature descriptions
        require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
        
        $autoToolBox = new AutoToolBox(
            $this->icon . " " . esc_html__('Web Stories Generator', 'ai-auto-tool'),
            AiAutoTool_Feature_Descriptions::get('webstories'),
            "https://doc.aiautotool.com/features/webstories",
            $this->active_option_name,
            $this->active,
            defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__)
        );

        echo $autoToolBox->generateHTML();
    }

    /**
     * Custom rewrite rule handler
     * 
     * Displays the stories listing page with pagination.
     * Shows posts with featured images in a grid layout.
     * 
     * Output:
     * - Bootstrap-styled grid
     * - Post thumbnails and titles
     * - Pagination
     * - Links to individual stories
     * 
     * @since 1.0.0
     * @return void
     */
    public function custom_rewrite_rule_handler() {
        ?>
<!DOCTYPE html>
<html lang="<?php echo esc_attr(get_locale()); ?>">
<head>    
    <meta charset="utf-8">   
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <title><?php echo esc_html(get_bloginfo('name')); ?> - <?php esc_html_e('Web Stories', 'ai-auto-tool'); ?></title>
    <meta name="description" content="<?php echo esc_attr(get_bloginfo('description')); ?>">
    <link href="<?php echo esc_url((defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(dirname(__FILE__))))) . 'js/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">   
    <link rel="canonical" href="<?php echo esc_url(home_url('/aiwebstories/')); ?>">  
    <style type="text/css">
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: #f5f5f5;
        }
        .page-numbers.dots {
            display: none;
        }
        .page-numbers.current {
            background-color: #007bff;
            color: #fff;
            border-color: #007bff;
        }
        .page-numbers {
            display: inline-block;
            margin: 0 4px;
            padding: 8px 12px;
            color: #007bff;
            border: 1px solid #007bff;
            border-radius: 4px;
            text-decoration: none;
            transition: background-color 0.3s, color 0.3s, border-color 0.3s;
        }
        .page-numbers:hover {
            background-color: #f8f9fa;
            color: #007bff;
            border-color: #007bff;
        }
        .prev, .next {
            margin: 0 4px;
            padding: 8px 12px;
            color: #007bff;
            border: 1px solid #007bff;
            border-radius: 4px;
            text-decoration: none;
            transition: background-color 0.3s, color 0.3s, border-color 0.3s;
        }
        .prev:hover, .next:hover {
            background-color: #f8f9fa;
            color: #007bff;
            border-color: #007bff;
        }
        .card {
            transition: transform 0.2s, box-shadow 0.2s;
            height: 100%;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .card-img-top {
            height: 200px;
            object-fit: cover;
        }
        .header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 3rem 0;
            margin-bottom: 2rem;
        }
    </style>
</head>  
<body>    
    <div class="header-section">
        <div class="container">
            <div class="text-center">
                <h1 class="display-4 mb-3">
                    <i class="fa-solid fa-book-open"></i>
                    <?php esc_html_e('Web Stories', 'ai-auto-tool'); ?>
                </h1>
                <p class="lead">
                    <?php echo '<a href="' . esc_url(get_home_url()) . '" style="color: white; text-decoration: none;">' . 
                         esc_html(get_bloginfo('name')) . '</a>'; ?>
                </p>
            </div>
        </div>
    </div>

    <div class="container">      
        <div class="row justify-content-center">
            <?php 
            // Query posts with featured images
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $args = array(
                'post_type'      => 'post',
                'post_status'    => 'publish',
                'posts_per_page' => 30,
                'orderby'        => 'date',
                'order'          => 'DESC',
                'meta_query'     => array(
                    array(
                        'key'     => '_thumbnail_id',
                        'compare' => 'EXISTS',
                    ),
                ),
                'paged'          => $paged,
            );

            $query = new WP_Query($args);

            if ($query->have_posts()) {
                while ($query->have_posts()) {
                    $query->the_post();

                    $post_title = get_the_title();
                    $post_name = get_post_field('post_name', get_the_ID());
                    $post_thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium');
                    
                    ?>
                    <div class="col-6 col-sm-4 col-md-3 mb-4">
                        <div class="card h-100 shadow-sm">
                            <a href="<?php echo esc_url($this->gen_url_storiepost($post_name)); ?>" class="text-decoration-none">  
                                <img loading="lazy" 
                                     src="<?php echo esc_url($post_thumbnail_url); ?>" 
                                     class="card-img-top" 
                                     alt="<?php echo esc_attr($post_title); ?>" 
                                     width="320" 
                                     height="200">
                            </a>
                            <div class="card-body">
                                <h2 class="card-title h6">
                                    <a href="<?php echo esc_url($this->gen_url_storiepost($post_name)); ?>" class="text-dark text-decoration-none">
                                        <?php echo esc_html($post_title); ?>
                                    </a>
                                </h2>
                            </div>
                        </div>
                    </div>
                    <?php
                }
                wp_reset_postdata();
            } else {
                echo '<div class="col-12"><div class="alert alert-info">' . 
                     esc_html__('No stories found. Create posts with featured images to generate stories.', 'ai-auto-tool') . 
                     '</div></div>';
            }
            ?>
        </div>

        <!-- Pagination -->
        <?php if ($query->max_num_pages > 1): ?>
        <nav aria-label="<?php esc_attr_e('Page navigation', 'ai-auto-tool'); ?>" class="mt-4 mb-5">
            <ul class="pagination justify-content-center">
                <?php
                echo paginate_links(array(
                    'total'     => $query->max_num_pages,
                    'current'   => max(1, get_query_var('paged')),
                    'prev_text' => '«',
                    'next_text' => '»',
                    'type'      => 'list',
                ));
                ?>
            </ul>
        </nav>
        <?php endif; ?>

        <!-- Footer -->
        <div class="text-center mt-5 mb-4">
            <div style="overflow: auto; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px;" class="py-5">
                <span class="lead text-white"><?php esc_html_e('AI Auto Tool - Web Stories', 'ai-auto-tool'); ?></span><br>
                <a target="_blank" href="https://aiautotool.com">
                    <img loading="lazy" 
                         style="max-height: 80px; margin-top: 1rem" 
                         alt="<?php esc_attr_e('Powered by aiautotool.com', 'ai-auto-tool'); ?>" 
                         src="<?php echo esc_url($this->setting['logo']); ?>">
                </a>
            </div>
        </div>
    </div>
</body>
</html>
<?php
    }

    /**
     * Generate story URL
     * 
     * Creates the full URL for a story based on post slug.
     * 
     * @since 1.0.0
     * @param string $postname Post slug
     * @return string Full story URL
     */
    public function gen_url_storiepost($postname) {
        $current_domain = home_url('/');
        $full_url = trailingslashit($current_domain) . 'aiwebstories/' . $postname . '/';
        return esc_url($full_url);
    }

    /**
     * Add custom rewrite rules
     * 
     * Registers URL patterns for:
     * - /aiwebstories/ (list page)
     * - /aiwebstories/page/2/ (pagination)
     * - /aiwebstories/feed/ (RSS feed)
     * - /aiwebstories/post-slug/ (single story)
     * 
     * Flushes rewrite rules on first activation.
     * 
     * @since 1.0.0
     * @return void
     */
    public function add_custom_rewrite_rule() {
        // Stories list
        add_rewrite_rule('^aiwebstories$', 'index.php?custom_aiwebstories=1', 'top');
        
        // Pagination
        add_rewrite_rule(
            '^aiwebstories/page/([0-9]+)/?$',
            'index.php?custom_aiwebstories=1&paged=$matches[1]',
            'top'
        );

        // RSS feed
        add_rewrite_rule(
            '^aiwebstories/feed$', 
            'index.php?custom_aiwebstories=1&aiwebstories_feed=1', 
            'top'
        );
        
        // Single story
        add_rewrite_rule(
            '^aiwebstories/([^/]+)/?$',
            'index.php?custom_aiwebstories=1&postname=$matches[1]',
            'top'
        );
        
        // Flush rewrite rules on first activation
        if (!get_option($this->aiautotool_rewriter_flushed)) {
            flush_rewrite_rules(false);
            update_option($this->aiautotool_rewriter_flushed, 1);
        }
    }

    /**
     * Register custom query vars
     * 
     * Adds custom query variables for stories routing:
     * - custom_aiwebstories
     * - postname
     * - aiwebstories_feed
     * 
     * @since 1.0.0
     * @param array $query_vars Existing query vars
     * @return array Modified query vars
     */
    public function custom_rewrite_query_vars($query_vars) {
        $query_vars[] = 'custom_aiwebstories';
        $query_vars[] = 'postname';
        $query_vars[] = 'aiwebstories_feed';
        return $query_vars;
    }
    
    /**
     * Custom template router
     * 
     * Routes requests to appropriate handlers:
     * - Feed requests → custom_feed_template()
     * - Single story → display_theme_for_postname()
     * - List page → custom_rewrite_rule_handler()
     * 
     * @since 1.0.0
     * @param string $template Default template path
     * @return string Template path
     */
    public function custom_rewrite_rule_template($template) {
        if (get_query_var('custom_aiwebstories')) {
            
            if (get_query_var('aiwebstories_feed')) {
                // RSS feed
                $this->custom_feed_template();
                exit;
            } else {
                $postname = get_query_var('postname');

                if ($postname) {
                    // Single story
                    $this->display_theme_for_postname($postname);
                    exit;
                } else {
                    // Stories list
                    $this->custom_rewrite_rule_handler();
                    exit;
                }
            }
        }
        return $template;
    }

    /**
     * Display single story
     * 
     * Generates an AMP-compliant Web Story from a post.
     * 
     * Process:
     * 1. Fetch post by slug
     * 2. Extract images from content
     * 3. Split content into paragraphs
     * 4. Generate AMP story pages
     * 5. Add structured data (Schema.org)
     * 6. Include social sharing
     * 
     * @since 1.0.0
     * @param string $postname Post slug
     * @return void Outputs HTML and exits
     */
    public function display_theme_for_postname($postname) {
        $page = get_page_by_path($postname, OBJECT, 'post');
        
        if (!$page) {
            // Post not found
            status_header(404);
            echo '<html><body><h1>' . esc_html__('Story not found', 'ai-auto-tool') . '</h1>';
            echo '<p><a href="' . esc_url(home_url('/aiwebstories/')) . '">' . 
                 esc_html__('View all stories', 'ai-auto-tool') . '</a></p></body></html>';
            exit;
        }

        // Get post data
        $post_id = $page->ID;
        $post_title = get_the_title($post_id);
        $post_url = get_permalink($post_id);
        $post_content = get_the_content(null, false, $post_id);
        $url_thumb = get_the_post_thumbnail_url($post_id, 'large');
        $post_date = get_post_time('Y-m-d\TH:i:sP', true, $post_id); 
        $post_author = get_the_author_meta('display_name', get_post_field('post_author', $post_id));

        // Extract images from content
        $image_urls = array();
        $dom = new DOMDocument();
        libxml_use_internal_errors(true); 
        $dom->loadHTML(mb_convert_encoding($post_content, 'HTML-ENTITIES', 'UTF-8'));
        libxml_clear_errors();

        $images = $dom->getElementsByTagName('img');
        foreach ($images as $image) {
            $src = $image->getAttribute('src');
            if ($src && filter_var($src, FILTER_VALIDATE_URL)) {
                $image_urls[] = $src;
            }
        }
        
        // Fallback to featured image
        if (empty($url_thumb) && !empty($image_urls)) {
            $url_thumb = $image_urls[0];
        }
        
        // Split content into paragraphs
        $contenttext = strip_tags($post_content);
        $paragraphs = array_filter(explode('.', $contenttext), function($p) {
            return !empty(trim($p));
        });
        
        // Prepare structured data
        $article_body_content = implode("\n", $paragraphs);
        $article_body_unicode = json_encode($article_body_content, JSON_UNESCAPED_UNICODE);

        ?><!DOCTYPE html>
<html amp lang="<?php echo esc_attr(str_replace('_', '-', get_locale())); ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large"/>
    <title><?php echo esc_html($post_title); ?></title>
    <meta name="description" content="<?php echo esc_attr(wp_trim_words($contenttext, 20)); ?>">
    <meta name="theme-color" content="#667eea">
    
    <!-- Open Graph -->
    <meta property="og:title" content="<?php echo esc_attr($post_title); ?>">
    <meta property="og:description" content="<?php echo esc_attr(wp_trim_words($contenttext, 20)); ?>">
    <meta property="og:image" content="<?php echo esc_url($url_thumb); ?>">
    <meta property="og:url" content="<?php echo esc_url($this->gen_url_storiepost($postname)); ?>">
    <meta property="og:type" content="article">
    <meta property="og:site_name" content="<?php echo esc_attr(get_bloginfo('name')); ?>">
    <meta property="og:locale" content="<?php echo esc_attr(get_locale()); ?>">
    
    <!-- Twitter Card -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:title" content="<?php echo esc_attr($post_title); ?>">
    <meta property="twitter:description" content="<?php echo esc_attr(wp_trim_words($contenttext, 20)); ?>">
    <meta property="twitter:image" content="<?php echo esc_url($url_thumb); ?>">
    <meta property="twitter:url" content="<?php echo esc_url($this->gen_url_storiepost($postname)); ?>">
    <meta property="twitter:site" content="@<?php echo esc_attr(get_bloginfo('name')); ?>">
    
    <!-- Schema.org -->
    <meta itemprop="name" content="<?php echo esc_attr($post_title); ?>">
    <meta itemprop="description" content="<?php echo esc_attr(wp_trim_words($contenttext, 20)); ?>">
    <meta itemprop="image" content="<?php echo esc_url($url_thumb); ?>">
    
    <link rel="canonical" href="<?php echo esc_url($this->gen_url_storiepost($postname)); ?>">
    <link rel="icon" href="<?php echo esc_url($this->setting['logo']); ?>">
    
    <!-- AMP Boilerplate -->
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
    <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    
    <!-- Custom Styles -->
    <style amp-custom>
        .amphtml-cap span,amp-img:after{display:block;position:absolute;left:0}
        amp-story-page{background:#000}
        amp-img img{width:100%;height:auto;margin:0;object-fit:cover}
        amp-img:after{background:linear-gradient(180deg,#fff0,#000);content:"";height:36%;pointer-events:none;bottom:0;width:100%}
        .amphtml-cap{position:relative;width:100%;height:100%}
        .amphtml-cap span{padding:15px;right:0;bottom:80px;color:#fff;font-size:24px;line-height:1.2;text-shadow:0 2px 4px rgba(0,0,0,0.8)}
        /* Dynamic gradient colors for pages */
        <?php
        $gradient_colors = array(
            '#ff5722', '#009688', '#795548', '#4caf50', '#2196f3', 
            '#ff9800', '#cddc39', '#00bcd4', '#e91e63', '#ffc107',
            '#9c27b0', '#03a9f4', '#607d8b', '#3f51b5', '#8bc34a',
            '#673ab7', '#ffeb3b', '#9e9e9e', '#f44336'
        );
        for ($i = 0; $i < 60; $i++) {
            $color = $gradient_colors[$i % count($gradient_colors)];
            echo "#page-{$i} amp-img:after{height:54%;background:linear-gradient(180deg,#fff0,{$color})}";
        }
        ?>
        .blur{background:#ffffffbb;backdrop-filter:blur(10px);height:100vh;width:100vw;position:absolute;top:0;left:0}
    </style>
    
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-story" src="https://cdn.ampproject.org/v0/amp-story-1.0.js"></script>
    <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
    
    <!-- Structured Data -->
    <script type="application/ld+json">
    <?php
    echo json_encode(array(
        '@context' => 'https://schema.org',
        '@type' => 'Article',
        'mainEntityOfPage' => array(
            '@type' => 'WebPage',
            'url' => esc_url($post_url),
            'name' => esc_html($post_title),
        ),
        'headline' => esc_html($post_title),
        'datePublished' => $post_date,
        'dateModified' => $post_date,
        'author' => array(
            '@type' => 'Person',
            'name' => esc_html($post_author),
            'url' => get_author_posts_url(get_the_author_meta('ID', $post_id)),
        ),
        'publisher' => array(
            '@type' => 'Organization',
            'name' => get_bloginfo('name'),
            'logo' => array(
                '@type' => 'ImageObject',
                'url' => esc_url($this->setting['logo']),
            ),
        ),
        'description' => wp_trim_words($contenttext, 20),
        'image' => array(
            '@type' => 'ImageObject',
            'url' => esc_url($url_thumb),
        ),
        'articleBody' => strip_tags($article_body_unicode),
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    ?>
    </script>
</head>
<body>
    <amp-story standalone 
              title="<?php echo esc_attr($post_title); ?>" 
              publisher="<?php echo esc_attr($post_author); ?>" 
              publisher-logo-src="<?php echo esc_url($this->setting['logo']); ?>" 
              poster-portrait-src="<?php echo esc_url($url_thumb); ?>"
              <?php if (!empty($this->setting['mp31'])): ?>
              background-audio="<?php echo esc_url($this->setting['mp31']); ?>"
              <?php endif; ?>>
        
        <!-- Cover Page -->
        <amp-story-page id="cover" class="page">
            <amp-story-grid-layer template="vertical" class="blur">
                <amp-img src="<?php echo esc_url($url_thumb); ?>" 
                         width="720" 
                         height="1280" 
                         layout="responsive" 
                         object-fit="cover" 
                         style="border-radius: 1rem">
                </amp-img>
                <h1 style="color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.8);">
                    <?php echo esc_html($post_title); ?>
                </h1>
            </amp-story-grid-layer>
        </amp-story-page>
        
        <!-- Content Pages -->
        <?php 
        foreach ($paragraphs as $index => $paragraph) {
            $paragraph = trim($paragraph);
            if (empty($paragraph) || strlen($paragraph) < 10) {
                continue;
            }
            
            $img = $url_thumb;
            if (isset($image_urls[$index])) {
                $img = $image_urls[$index];
            }
            ?>
            <amp-story-page id="page-<?php echo esc_attr($index); ?>" auto-advance-after="7s">
                <amp-story-grid-layer template="vertical">
                    <amp-img layout="fill" 
                             src="<?php echo esc_url($img); ?>" 
                             alt="<?php echo esc_attr(wp_trim_words($paragraph, 5)); ?>">
                    </amp-img>
                </amp-story-grid-layer>
                <amp-story-grid-layer template="vertical" class="amphtml-cap">
                    <span><?php echo esc_html($paragraph); ?>.</span>
                </amp-story-grid-layer>
                <amp-story-page-outlink layout="nodisplay">
                    <a href="<?php echo esc_url($post_url); ?>" rel="nofollow">
                        <?php esc_html_e('Read more', 'ai-auto-tool'); ?>
                    </a>
                </amp-story-page-outlink>
            </amp-story-page>
            <?php
        }
        ?>
        
        <!-- Conclusion Page -->
        <amp-story-page id="conclusion" auto-advance-after="7s">
            <amp-story-grid-layer template="vertical">
                <amp-img layout="fill" 
                         src="<?php echo esc_url($url_thumb); ?>" 
                         alt="<?php echo esc_attr($post_title); ?>">
                </amp-img>
            </amp-story-grid-layer>
            <amp-story-grid-layer template="vertical" class="amphtml-cap">
                <span style="font-weight: 400; position: fixed; bottom: 2.5rem; width: 100%; left: 0; font-size: 1.2rem; display: inline-block;">
                    <?php esc_html_e('Visit our site and see all other available articles!', 'ai-auto-tool'); ?>
                </span>
            </amp-story-grid-layer>
            <amp-story-page-outlink layout="nodisplay" theme="custom" cta-accent-element="background" cta-accent-color="#fff">
                <a href="<?php echo esc_url($post_url); ?>" rel="nofollow">
                    <?php esc_html_e('Read more', 'ai-auto-tool'); ?>
                </a>
            </amp-story-page-outlink>
        </amp-story-page>

        <!-- Google Analytics -->
        <?php if (!empty($this->setting['analytic'])): ?>
        <amp-analytics type="gtag" data-credentials="include">
            <script type="application/json">
            {
                "vars": {
                    "gtag_id": "<?php echo esc_js($this->setting['analytic']); ?>",
                    "config": {
                        "<?php echo esc_js($this->setting['analytic']); ?>": {"groups": "default"}
                    }
                }
            }
            </script>
        </amp-analytics>
        <?php endif; ?>

        <!-- Social Sharing -->
        <amp-story-social-share layout="nodisplay">
            <script type="application/json">
            {
                "shareProviders": [
                    {"provider": "facebook"},
                    {"provider": "twitter"},
                    {"provider": "linkedin"},
                    {"provider": "email"},
                    {"provider": "system"}
                ]
            }
            </script>
        </amp-story-social-share>

    </amp-story>
</body>
</html>
<?php
    }

    /**
     * Generate RSS feed for stories
     * 
     * Creates an RSS 2.0 feed with all published stories.
     * Each item links to the story URL (not the original post).
     * 
     * @since 1.0.0
     * @return void Outputs XML and exits
     */
    public function custom_feed_template() {
        header('Content-Type: application/rss+xml; charset=' . get_option('blog_charset'), true);
        
        // Query posts with featured images
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => 50,
            'meta_query' => array(
                array(
                    'key' => '_thumbnail_id',
                    'compare' => 'EXISTS',
                ),
            ),
        );
        $query = new WP_Query($args);
        
        echo '<?xml version="1.0" encoding="' . esc_attr(get_option('blog_charset')) . '"?>';
        ?>
<rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
<channel>
    <title><?php bloginfo_rss('name'); ?> - <?php esc_html_e('Web Stories', 'ai-auto-tool'); ?></title>
    <atom:link href="<?php echo esc_url(home_url('/aiwebstories/feed/')); ?>" rel="self" type="application/rss+xml" />
    <link><?php bloginfo_rss('url'); ?></link>
    <description><?php bloginfo_rss("description"); ?></description>
    <lastBuildDate><?php echo esc_html(mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false)); ?></lastBuildDate>
    <language><?php echo esc_html(get_locale()); ?></language>
    <sy:updatePeriod><?php echo esc_html(apply_filters('rss_update_period', 'daily')); ?></sy:updatePeriod>
    <sy:updateFrequency><?php echo esc_html(apply_filters('rss_update_frequency', '1')); ?></sy:updateFrequency>
    <?php do_action('rss2_head'); ?>
    
    <?php
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $post_name = get_post_field('post_name', get_the_ID());
            $urllink = $this->gen_url_storiepost($post_name);
            $description = get_the_excerpt();
            $content = get_the_content();
            $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'large');
            ?>
    <item>
        <title><?php echo esc_html(get_the_title()); ?> - <?php esc_html_e('Web Story', 'ai-auto-tool'); ?></title>
        <link><?php echo esc_url($urllink); ?></link>
        <pubDate><?php echo esc_html(mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false)); ?></pubDate>
        <dc:creator><![CDATA[<?php the_author(); ?>]]></dc:creator>
        <guid isPermaLink="false"><?php echo esc_url($urllink); ?></guid>
        <description><![CDATA[<?php echo esc_html($description); ?>]]></description>
        <content:encoded><![CDATA[
            <?php if ($thumbnail_url): ?>
            <img src="<?php echo esc_url($thumbnail_url); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" style="max-width:100%;height:auto;"><br><br>
            <?php endif; ?>
            <?php echo wp_kses_post($content); ?>
            <p><a href="<?php echo esc_url($urllink); ?>"><?php esc_html_e('View Web Story', 'ai-auto-tool'); ?></a></p>
        ]]></content:encoded>
        <?php if ($thumbnail_url): ?>
        <enclosure url="<?php echo esc_url($thumbnail_url); ?>" type="image/jpeg" />
        <?php endif; ?>
        <slash:comments>0</slash:comments>
    </item>
            <?php
        }
        wp_reset_postdata();
    }
    ?>
</channel>
</rss>
<?php
        exit;
    }
}
} // End of class_exists check
