<?php
/**
 * Launchmind Shortcodes
 * 
 * Provides shortcodes for displaying Launchmind blog content:
 * - [launchmind_blog] - Display blog post list
 * - [launchmind_post slug="x"] - Display single post
 */

if (!defined('ABSPATH')) {
    exit;
}

class Launchmind_Shortcodes {
    
    /**
     * Initialize shortcodes
     */
    public static function init() {
        add_shortcode('launchmind_blog', array(__CLASS__, 'render_blog_list'));
        add_shortcode('launchmind_post', array(__CLASS__, 'render_single_post'));
        add_shortcode('launchmind_test', array(__CLASS__, 'render_test'));
    }
    
    /**
     * Simple test shortcode to verify plugin is working
     */
    public static function render_test($atts) {
        $output = '<div style="background:#d4edda;border:2px solid #28a745;padding:20px;margin:20px 0;border-radius:8px;font-family:sans-serif;">';
        $output .= '<strong style="font-size:18px;">✅ Launchmind Plugin is Working!</strong><br><br>';
        $output .= 'Version: ' . LAUNCHMIND_BLOG_VERSION . '<br>';
        $output .= 'PHP: ' . PHP_VERSION . '<br>';
        $output .= 'API Key: ' . (Launchmind_Blog_Connector::get_option('api_key') ? '✅ Set (' . substr(Launchmind_Blog_Connector::get_option('api_key'), 0, 15) . '...)' : '❌ Not set') . '<br>';
        $output .= 'Site ID: ' . (Launchmind_Blog_Connector::get_option('site_id') ? '✅ Set' : '⚠️ Not set') . '<br>';
        
        // Test API call
        $posts = Launchmind_API::get_posts(array('limit' => 1));
        if (is_wp_error($posts)) {
            $output .= 'API Test: ❌ Error - ' . $posts->get_error_message() . '<br>';
        } elseif (empty($posts)) {
            $output .= 'API Test: ⚠️ No posts found<br>';
        } else {
            $output .= 'API Test: ✅ Success - Found ' . count($posts) . ' post(s)<br>';
        }
        
        $output .= '</div>';
        return $output;
    }
    
    /**
     * Render blog list shortcode
     * 
     * Usage: [launchmind_blog limit="10" lang="en" columns="2" show_excerpt="true"]
     * 
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render_blog_list($atts) {
        // Auto-detect language from WordPress locale (defaults to NL for .nl sites)
        $default_lang = substr(get_locale(), 0, 2);
        
        $atts = shortcode_atts(array(
            'limit' => 12,
            'offset' => 0,
            'lang' => $default_lang, // Auto NL for Dutch sites
            'columns' => 3, // 3 columns default, cleaner look
            'show_excerpt' => 'true',
            'show_image' => 'true',
            'show_date' => 'true',
            'show_author' => 'true',
            'show_tags' => 'false',
            'show_intro' => 'true', // Show intro text above blog
            'class' => '',
            'base_url' => '', // Base URL for post links
            'theme' => '', // empty = backward compatible (no auto dark mode), 'auto' = enable auto dark mode, 'dark'/'light' = force mode
            'accent_color' => '', // Custom accent color: teal, blue, gold, #hexcode
            'debug' => 'false', // Debug mode
        ), $atts, 'launchmind_blog');
        
        // Convert string booleans
        $show_excerpt = filter_var($atts['show_excerpt'], FILTER_VALIDATE_BOOLEAN);
        $show_image = filter_var($atts['show_image'], FILTER_VALIDATE_BOOLEAN);
        $show_date = filter_var($atts['show_date'], FILTER_VALIDATE_BOOLEAN);
        $show_author = filter_var($atts['show_author'], FILTER_VALIDATE_BOOLEAN);
        $show_tags = filter_var($atts['show_tags'], FILTER_VALIDATE_BOOLEAN);
        $show_intro = filter_var($atts['show_intro'], FILTER_VALIDATE_BOOLEAN);
        $debug = filter_var($atts['debug'], FILTER_VALIDATE_BOOLEAN);
        
        // Debug output for admins
        $debug_output = '';
        if ($debug && current_user_can('manage_options')) {
            $api_key = Launchmind_Blog_Connector::get_option('api_key', '');
            $site_id = Launchmind_Blog_Connector::get_option('site_id', '');
            $debug_output .= '<div style="background:#fff3cd;border:1px solid #ffc107;padding:15px;margin:10px 0;font-family:monospace;font-size:12px;">';
            $debug_output .= '<strong>🔧 Launchmind Debug:</strong><br>';
            $debug_output .= 'API Key: ' . (empty($api_key) ? '❌ NOT SET' : '✅ ' . substr($api_key, 0, 20) . '...') . '<br>';
            $debug_output .= 'Site ID: ' . (empty($site_id) ? '⚠️ Not set' : '✅ ' . $site_id) . '<br>';
            $debug_output .= 'Lang: ' . esc_html($atts['lang'] ?: 'auto (' . substr(get_locale(), 0, 2) . ')') . '<br>';
        }
        
        // Get posts from API
        $posts = Launchmind_API::get_posts(array(
            'limit' => intval($atts['limit']),
            'offset' => intval($atts['offset']),
            'lang' => !empty($atts['lang']) ? $atts['lang'] : null,
        ));
        
        if (is_wp_error($posts)) {
            if ($debug && current_user_can('manage_options')) {
                $debug_output .= 'API Error: ❌ ' . esc_html($posts->get_error_message()) . '<br>';
                $debug_output .= '</div>';
                return $debug_output;
            }
            if (current_user_can('manage_options')) {
                return '<div class="launchmind-error">' . esc_html($posts->get_error_message()) . '</div>';
            }
            return '<div class="launchmind-error">' . esc_html__('Unable to load blog posts.', 'launchmind-blog') . '</div>';
        }
        
        if ($debug && current_user_can('manage_options')) {
            $debug_output .= 'Posts found: ' . count($posts) . '<br>';
            $debug_output .= '</div>';
        }
        
        if (empty($posts)) {
            return $debug_output . '<div class="launchmind-empty">' . esc_html__('No blog posts found.', 'launchmind-blog') . '</div>';
        }
        
        // Determine base URL for post links
        $base_url = !empty($atts['base_url']) ? trailingslashit($atts['base_url']) : '';
        
        // Start output buffering
        ob_start();
        
        $columns = max(1, min(4, intval($atts['columns'])));
        $extra_class = !empty($atts['class']) ? ' ' . esc_attr($atts['class']) : '';
        
        // Theme class for dark/light mode
        // IMPORTANT: Only add theme class if explicitly set. Default (empty/auto) = no class = backward compatible
        $theme_class = '';
        if ($atts['theme'] === 'dark') {
            $theme_class = ' lm-dark';
        } elseif ($atts['theme'] === 'light') {
            $theme_class = ' lm-light';
        } elseif ($atts['theme'] === 'auto') {
            // Only add auto class if explicitly set to "auto"
            $theme_class = ' lm-theme-auto';
        }
        // If theme is empty or not set, no class is added = backward compatible (no auto dark mode)
        
        // Accent color class or inline style
        $accent_style = '';
        $accent_class = '';
        if (!empty($atts['accent_color'])) {
            $color = sanitize_text_field($atts['accent_color']);
            // Check if it's a preset name or hex color
            if (in_array($color, array('teal', 'blue', 'purple', 'red', 'orange', 'gold', 'green'))) {
                $accent_class = ' lm-accent-' . $color;
            } elseif (preg_match('/^#[a-fA-F0-9]{3,6}$/', $color)) {
                $accent_style = ' style="--lm-accent: ' . esc_attr($color) . ';"';
            }
        }
        
        // Get site name for intro text
        $site_name = get_bloginfo('name');
        
        ?>
        <?php if ($show_intro) : ?>
        <div class="launchmind-blog-intro<?php echo esc_attr($theme_class . $accent_class); ?>"<?php echo $accent_style; ?>>
            <p>
                <?php 
                printf(
                    /* translators: %s: site name */
                    esc_html__('Welkom op de blog van %s. Hier delen we de laatste inzichten, tips en verhalen. Ontdek onze nieuwste artikelen hieronder.', 'launchmind-blog'),
                    '<strong class="launchmind-site-name">' . esc_html($site_name) . '</strong>'
                );
                ?>
            </p>
        </div>
        <?php endif; ?>
        <div class="launchmind-blog-list launchmind-columns-<?php echo esc_attr( $columns ); ?><?php echo esc_attr( $theme_class . $accent_class ); ?><?php echo esc_attr( $extra_class ); ?>"<?php echo $accent_style; ?>>
            <?php foreach ($posts as $post) : ?>
                <article class="launchmind-post-card">
                    <?php if ($show_image && !empty($post['coverImage'])) : ?>
                        <div class="launchmind-post-image">
                            <a href="<?php echo esc_url($base_url . $post['slug']); ?>">
                                <img src="<?php echo esc_url($post['coverImage']); ?>" alt="<?php echo esc_attr($post['title']); ?>" loading="lazy">
                            </a>
                        </div>
                    <?php endif; ?>
                    
                    <div class="launchmind-post-content">
                        <h3 class="launchmind-post-title">
                            <a href="<?php echo esc_url($base_url . $post['slug']); ?>">
                                <?php echo esc_html($post['title']); ?>
                            </a>
                        </h3>
                        
                        <?php if ($show_date || $show_author) : ?>
                            <div class="launchmind-post-meta">
                                <?php if ($show_date && !empty($post['publishedAt'])) : ?>
                                    <span class="launchmind-post-date">
                                        <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($post['publishedAt']))); ?>
                                    </span>
                                <?php endif; ?>
                                
                                <?php if ($show_author && !empty($post['author'])) : ?>
                                    <span class="launchmind-post-author">
                                        <?php echo esc_html($post['author']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($show_excerpt && !empty($post['excerpt'])) : ?>
                            <div class="launchmind-post-excerpt">
                                <?php echo wp_kses_post($post['excerpt']); ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($show_tags && !empty($post['tags'])) : ?>
                            <div class="launchmind-post-tags">
                                <?php foreach (array_slice($post['tags'], 0, 5) as $tag) : ?>
                                    <span class="launchmind-tag"><?php echo esc_html($tag); ?></span>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <a href="<?php echo esc_url($base_url . $post['slug']); ?>" class="launchmind-read-more">
                            <?php esc_html_e('Read more', 'launchmind-blog'); ?>
                        </a>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
        <?php
        
        // Return debug output + blog content
        return $debug_output . ob_get_clean();
    }
    
    /**
     * Render single post shortcode
     * 
     * Usage: [launchmind_post slug="my-post-slug" lang="en"]
     * 
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public static function render_single_post($atts) {
        $atts = shortcode_atts(array(
            'slug' => '',
            'lang' => '',
            'show_title' => 'true',
            'show_image' => 'true',
            'show_date' => 'true',
            'show_author' => 'true',
            'show_tags' => 'true',
            'class' => '',
        ), $atts, 'launchmind_post');
        
        if (empty($atts['slug'])) {
            return '<div class="launchmind-error">' . esc_html__('Post slug is required.', 'launchmind-blog') . '</div>';
        }
        
        // Convert string booleans
        $show_title = filter_var($atts['show_title'], FILTER_VALIDATE_BOOLEAN);
        $show_image = filter_var($atts['show_image'], FILTER_VALIDATE_BOOLEAN);
        $show_date = filter_var($atts['show_date'], FILTER_VALIDATE_BOOLEAN);
        $show_author = filter_var($atts['show_author'], FILTER_VALIDATE_BOOLEAN);
        $show_tags = filter_var($atts['show_tags'], FILTER_VALIDATE_BOOLEAN);
        
        // Get post from API
        $lang = !empty($atts['lang']) ? $atts['lang'] : null;
        $post = Launchmind_API::get_post($atts['slug'], $lang);
        
        if (is_wp_error($post)) {
            if (current_user_can('manage_options')) {
                return '<div class="launchmind-error">' . esc_html($post->get_error_message()) . '</div>';
            }
            return '<div class="launchmind-error">' . esc_html__('Post not found.', 'launchmind-blog') . '</div>';
        }
        
        if (empty($post)) {
            return '<div class="launchmind-error">' . esc_html__('Post not found.', 'launchmind-blog') . '</div>';
        }
        
        // Start output buffering
        ob_start();
        
        $extra_class = !empty($atts['class']) ? ' ' . esc_attr($atts['class']) : '';
        
        ?>
        <article class="launchmind-post-single<?php echo esc_attr( $extra_class ); ?>">
            <?php if ($show_title) : ?>
                <h1 class="launchmind-post-title"><?php echo esc_html($post['title']); ?></h1>
            <?php endif; ?>
            
            <?php if ($show_date || $show_author) : ?>
                <div class="launchmind-post-meta">
                    <?php if ($show_date && !empty($post['publishedAt'])) : ?>
                        <span class="launchmind-post-date">
                            <time datetime="<?php echo esc_attr($post['publishedAt']); ?>">
                                <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($post['publishedAt']))); ?>
                            </time>
                        </span>
                    <?php endif; ?>
                    
                    <?php if ($show_author && !empty($post['author'])) : ?>
                        <span class="launchmind-post-author">
                            <?php 
                            printf(
                                /* translators: %s: author name */
                                esc_html__('By %s', 'launchmind-blog'),
                                esc_html($post['author'])
                            ); 
                            ?>
                        </span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($show_image && !empty($post['coverImage'])) : ?>
                <div class="launchmind-post-featured-image">
                    <img src="<?php echo esc_url($post['coverImage']); ?>" alt="<?php echo esc_attr($post['title']); ?>">
                </div>
            <?php endif; ?>
            
            <div class="launchmind-post-body">
                <?php echo wp_kses_post($post['html']); ?>
            </div>
            
            <?php if ($show_tags && !empty($post['tags'])) : ?>
                <div class="launchmind-post-tags">
                    <span class="launchmind-tags-label"><?php esc_html_e('Tags:', 'launchmind-blog'); ?></span>
                    <?php foreach ($post['tags'] as $tag) : ?>
                        <span class="launchmind-tag"><?php echo esc_html($tag); ?></span>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </article>
        <?php
        
        return ob_get_clean();
    }
}

