<?php
/**
 * ==============================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==============================
 * @file         : ai-shortcodes.php
 * @location     : shortcodes/
 * @type         : Shortcode Handler
 * @scope        : Global
 * @allowed      : Shortcode registration and handling only
 * @reusability  : Global
 * @notes        : Main IGNY8 shortcode for content personalization
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register shortcode [igny8]
 */
add_shortcode('igny8', 'igny8_shortcode_handler');

/**
 * Main Shortcode Handler Function
 */
function igny8_shortcode_handler($atts) {
    // Normalize 'form-fields' → 'form_fields'
    if (isset($atts['form-fields'])) {
        $atts['form_fields'] = $atts['form-fields'];
        unset($atts['form-fields']);
    }
    
    // Enable nested shortcodes in all attribute values
    foreach ($atts as $key => $value) {
        $atts[$key] = do_shortcode($value);
    }

    // Store normalized field list
    $form_fields_value = $atts['form_fields'] ?? '';

    // Generate inline JavaScript for personalization functionality
    $ajax_url = admin_url('admin-ajax.php');
    $nonce = wp_create_nonce('igny8_ajax_nonce');

    // Fetch context values
    $post_id = get_queried_object_id();
    
    // Debug: Log PHP variables
    error_log('IGNY8 Debug - PHP Variables:');
    error_log('ajax_url: ' . $ajax_url);
    error_log('nonce: ' . $nonce);
    error_log('post_id: ' . $post_id);
    
    // Check if Content Engine is enabled
    $content_engine_status = get_option('igny8_content_engine_global_status', 'enabled');
    $post_type = get_post_type();
    $enabled_post_types = get_option('igny8_content_engine_enabled_post_types', []);
    
    if ($content_engine_status === 'enabled' && in_array($post_type, $enabled_post_types)) {
        $teaser = esc_html(get_option('igny8_content_engine_teaser_text', 'Want to read this as if it was written exclusively about you?'));
        $display_mode = get_option('igny8_content_engine_display_mode', 'button');
    } else {
        $teaser = esc_html(get_option('igny8_teaser_text', 'Want to read this as if it was written exclusively about you?'));
        $display_mode = 'button';
    }

    // Start output buffering
    ob_start();
    ?>
    
    <?php if ($display_mode === 'auto'): ?>
        <!-- Auto Mode: Generate content immediately -->
        <div id="igny8-auto-content" 
             data-ajax-url="<?php echo $ajax_url; ?>"
             data-post-id="<?php echo $post_id; ?>"
             data-form-fields="<?php echo esc_attr($form_fields_value); ?>"
             <?php
             foreach ($atts as $key => $val) {
                 if (!in_array($key, ['form_fields', 'form-fields'])) {
                     echo ' data-' . esc_attr($key) . '="' . esc_attr($val) . '"';
                 }
             }
             ?>
        >
            <p class="igny8-teaser"><?php echo $teaser; ?></p>
            <div class="igny8-loading">Generating personalized content...</div>
            <div id="igny8-generated-content"></div>
        </div>
    <?php elseif ($display_mode === 'inline'): ?>
        <!-- Inline Mode: Show personalization form directly -->
        <div id="igny8-inline-form">
            <p class="igny8-teaser"><?php echo $teaser; ?></p>
            <div id="igny8-form-container"></div>
            <div id="igny8-generated-content"></div>
        </div>
    <?php else: ?>
        <!-- Button Mode: Show teaser text + personalization button (default) -->
        <div id="igny8-trigger">
            <p class="igny8-teaser"><?php echo $teaser; ?></p>
            <button class="button" id="igny8-launch"
                data-ajax-url="<?php echo $ajax_url; ?>"
                data-post-id="<?php echo $post_id; ?>"
                data-form-fields="<?php echo esc_attr($form_fields_value); ?>"
                <?php
                foreach ($atts as $key => $val) {
                    if (!in_array($key, ['form_fields', 'form-fields'])) {
                        echo ' data-' . esc_attr($key) . '="' . esc_attr($val) . '"';
                    }
                }
                ?>
            >Personalize</button>
        </div>
    <?php endif; ?>
    
    <!-- Inject admin-defined context (hidden) -->
    <?php
    if ($content_engine_status === 'enabled' && in_array($post_type, $enabled_post_types)) {
        $context_raw = get_option('igny8_content_engine_context_source', '');
    } else {
        $context_raw = get_option('igny8_context_source', '');
    }

    if (!empty($context_raw)) {
        echo '<div id="igny8-context-source" style="display:none;">' . esc_html($context_raw) . '</div>';
    }
    ?>
    
    <script>
    // Inject JavaScript variables
    window.igny8_ajax_url = '<?php echo $ajax_url; ?>';
    window.igny8_nonce = '<?php echo $nonce; ?>';
    window.igny8_post_id = <?php echo $post_id; ?>;
    window.igny8_form_fields = '<?php echo esc_js($form_fields_value); ?>';
    
    // Debug: Log JavaScript variables
    console.log('IGNY8 Debug - JavaScript Variables:');
    console.log('ajax_url:', window.igny8_ajax_url);
    console.log('nonce:', window.igny8_nonce);
    console.log('post_id:', window.igny8_post_id);
    console.log('form_fields:', window.igny8_form_fields);
    </script>
    
    <?php
    return ob_get_clean();
}
