<?php
/**
 * RG Promo Code Block & Shortcode
 *
 * Registers the rg/promo-code Gutenberg block and [rg_promo_code] shortcode.
 * Displays a promo code box with copy functionality.
 * Code can be manually entered or mapped from an ACF field.
 */

// Register the Gutenberg block
add_action('init', function() {
    $registry = WP_Block_Type_Registry::get_instance();
    if ($registry->is_registered('rg/promo-code')) {
        return;
    }

    wp_register_script(
        'rg-promo-code-editor',
        get_stylesheet_directory_uri() . '/blocks/rg-promo-code/editor.js',
        array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-data'),
        filemtime(get_stylesheet_directory() . '/blocks/rg-promo-code/editor.js')
    );

    register_block_type('rg/promo-code', array(
        'editor_script'   => 'rg-promo-code-editor',
        'render_callback' => 'rg_render_promo_code_block',
        'attributes'      => array(
            'source' => array(
                'type'    => 'string',
                'default' => 'manual',
            ),
            'manualCode' => array(
                'type'    => 'string',
                'default' => '',
            ),
            'acfFieldName' => array(
                'type'    => 'string',
                'default' => 'promo_code',
            ),
            'label' => array(
                'type'    => 'string',
                'default' => 'Code',
            ),
            'size' => array(
                'type'    => 'string',
                'default' => 'default',
            ),
        ),
    ));
});

/**
 * Enqueue frontend styles and scripts for the promo code block.
 */
add_action('wp_enqueue_scripts', function() {
    wp_register_style('rg-promo-code-style', false);
    wp_enqueue_style('rg-promo-code-style');

    $css = '
        /* RG Promo Code Block - Default Size */
        .rg-promo-code-box {
            display: flex;
            align-items: center;
            gap: 0;
            background: #FAFAF7;
            border: 1px dashed rgba(196,163,90,0.55);
            border-radius: 2px;
            overflow: hidden;
        }
        .rg-promo-code-box .promo-label {
            font-family: "Inter", sans-serif;
            font-size: 9px;
            font-weight: 700;
            letter-spacing: 0.18em;
            text-transform: uppercase;
            color: white;
            background: #1B2A4A;
            padding: 12px 16px;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .rg-promo-code-box .promo-code {
            font-family: "Cormorant Garamond", serif;
            font-size: 20px;
            font-weight: 400;
            letter-spacing: 0.1em;
            color: #1B2A4A;
            padding: 12px 18px;
            flex: 1;
        }
        .rg-promo-code-box .promo-copy-btn {
            font-family: "Inter", sans-serif;
            font-size: 9.5px;
            font-weight: 600;
            letter-spacing: 0.1em;
            text-transform: uppercase;
            color: #C4A35A;
            background: none;
            border: none;
            border-left: 1px dashed rgba(196,163,90,0.55);
            padding: 12px 16px;
            cursor: pointer;
            white-space: nowrap;
            transition: color 0.2s;
        }
        .rg-promo-code-box .promo-copy-btn:hover {
            color: #1B2A4A;
        }

        /* Mini Size (for cards) */
        .rg-promo-code-box--mini {
            border-color: rgba(196,163,90,0.4);
        }
        .rg-promo-code-box--mini .promo-label {
            font-size: 8px;
            padding: 8px 10px;
        }
        .rg-promo-code-box--mini .promo-code {
            font-size: 15px;
            padding: 8px 12px;
        }
        .rg-promo-code-box--mini .promo-copy-btn {
            font-size: 8.5px;
            padding: 8px 10px;
        }

        /* Copied state */
        .rg-promo-code-box .promo-copy-btn.copied {
            color: #27AE60;
        }
    ';

    wp_add_inline_style('rg-promo-code-style', $css);
});

/**
 * Enqueue frontend script for copy functionality.
 */
add_action('wp_footer', function() {
    // Only output if we haven't already
    static $script_output = false;
    if ($script_output) {
        return;
    }
    $script_output = true;
    ?>
    <script>
    (function() {
        function rgCopyPromoCode(codeEl, btn) {
            var code = codeEl.textContent.trim();
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(code).then(function() {
                    var orig = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.classList.add('copied');
                    setTimeout(function() {
                        btn.textContent = orig;
                        btn.classList.remove('copied');
                    }, 2000);
                }).catch(function() {
                    fallbackCopy(code, btn);
                });
            } else {
                fallbackCopy(code, btn);
            }
        }

        function fallbackCopy(text, btn) {
            var textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.left = '-9999px';
            document.body.appendChild(textarea);
            textarea.select();
            try {
                document.execCommand('copy');
                var orig = btn.textContent;
                btn.textContent = 'Copied!';
                btn.classList.add('copied');
                setTimeout(function() {
                    btn.textContent = orig;
                    btn.classList.remove('copied');
                }, 2000);
            } catch (e) {
                btn.textContent = 'Error';
            }
            document.body.removeChild(textarea);
        }

        // Attach event listeners to all promo copy buttons
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.rg-promo-code-box .promo-copy-btn').forEach(function(btn) {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    var box = btn.closest('.rg-promo-code-box');
                    var codeEl = box.querySelector('.promo-code');
                    if (codeEl) {
                        rgCopyPromoCode(codeEl, btn);
                    }
                });
            });
        });
    })();
    </script>
    <?php
});

/**
 * Server-side render callback for rg/promo-code block.
 */
function rg_render_promo_code_block($attributes, $content = '', $block = null) {
    $source = isset($attributes['source']) ? $attributes['source'] : 'manual';
    $manual_code = isset($attributes['manualCode']) ? trim($attributes['manualCode']) : '';
    $acf_field = isset($attributes['acfFieldName']) ? trim($attributes['acfFieldName']) : 'promo_code';
    $label = isset($attributes['label']) ? trim($attributes['label']) : 'Code';
    $size = isset($attributes['size']) ? $attributes['size'] : 'default';
    $post_id = isset($attributes['postId']) ? intval($attributes['postId']) : null;
    $hide_empty = isset($attributes['hideEmpty']) ? $attributes['hideEmpty'] : true;

    // Determine the promo code value
    $promo_code = '';

    if ($source === 'manual') {
        $promo_code = $manual_code;
    } elseif ($source === 'acf' && function_exists('get_field')) {
        // Priority order for getting ACF field:
        // 1. Specified post_id
        // 2. Block context postId (for Gutenberg query loops)
        // 3. Current post (get_the_ID() - works in WP query loops)

        if ($post_id) {
            $promo_code = get_field($acf_field, $post_id);
        }

        // Try block context (Gutenberg query loop)
        if (empty($promo_code) && $block && isset($block->context['postId'])) {
            $promo_code = get_field($acf_field, $block->context['postId']);
        }

        // Try current post in loop (WP_Query, Kadence, etc.)
        if (empty($promo_code)) {
            $current_id = get_the_ID();
            if ($current_id) {
                $promo_code = get_field($acf_field, $current_id);
            }
        }
    }

    // If no code and hide_empty is true, don't render anything
    if (empty($promo_code)) {
        if ($hide_empty) {
            return '';
        }
        // For debugging: show placeholder when hide_empty is false
        return '<!-- rg_promo_code: field "' . esc_attr($acf_field) . '" is empty -->';
    }

    // Sanitize values
    $promo_code = esc_html($promo_code);
    $label = esc_html($label);

    // Size class
    $size_class = $size === 'mini' ? ' rg-promo-code-box--mini' : '';

    // Generate unique ID for this instance
    $unique_id = 'rg-promo-' . wp_unique_id();

    return sprintf(
        '<div class="rg-promo-code-box%s">
            <span class="promo-label">%s</span>
            <span class="promo-code" id="%s">%s</span>
            <button type="button" class="promo-copy-btn" aria-label="Copy promo code">Copy</button>
        </div>',
        $size_class,
        $label,
        $unique_id,
        $promo_code
    );
}

/**
 * Register [rg_promo_code] shortcode
 *
 * Usage:
 *   [rg_promo_code code="SUMMER25"]
 *   [rg_promo_code field="promo_code"]
 *   [rg_promo_code field="promo_code" post_id="123"]
 *   [rg_promo_code code="SAVE10" label="Discount" size="mini"]
 *
 * In query loops (Kadence, WP Query Loop, etc.), omit post_id to use current post:
 *   [rg_promo_code field="promo_code"]
 *
 * Hide behavior:
 *   - By default, hides completely when promo code is empty
 *   - Use hide_empty="no" to show placeholder when empty (for debugging)
 */
add_shortcode('rg_promo_code', function($atts) {
    $atts = shortcode_atts(array(
        'code'       => '',        // Manual promo code
        'field'      => '',        // ACF field name
        'post_id'    => '',        // Post ID for ACF field (optional, uses current post in loop if empty)
        'label'      => 'Code',    // Label text
        'size'       => 'default', // 'default' or 'mini'
        'hide_empty' => 'yes',     // Hide when empty? 'yes' or 'no'
    ), $atts, 'rg_promo_code');

    // Determine source based on attributes
    $source = !empty($atts['field']) ? 'acf' : 'manual';

    // Get post ID - use provided, or get current post in loop
    $post_id = null;
    if (!empty($atts['post_id'])) {
        $post_id = intval($atts['post_id']);
    } elseif ($source === 'acf') {
        // In a query loop, get_the_ID() returns the current post
        $post_id = get_the_ID();
    }

    // Build attributes array for render function
    $attributes = array(
        'source'       => $source,
        'manualCode'   => $atts['code'],
        'acfFieldName' => $atts['field'],
        'label'        => $atts['label'],
        'size'         => $atts['size'],
        'postId'       => $post_id,
        'hideEmpty'    => strtolower($atts['hide_empty']) !== 'no',
    );

    return rg_render_promo_code_block($attributes);
});

/**
 * Add Settings Page: Dashboard -> Settings -> Promo Code
 */
add_action('admin_menu', function() {
    add_options_page(
        'Promo Code Usage',           // Page title
        'Promo Code',                 // Menu title
        'edit_posts',                 // Capability
        'rg-promo-code',              // Menu slug
        'rg_promo_code_settings_page' // Callback
    );
});

/**
 * Render the settings/documentation page
 */
function rg_promo_code_settings_page() {
    ?>
    <div class="wrap">
        <h1>RG Promo Code - Usage Guide</h1>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px;">
            <h2>Gutenberg Block</h2>
            <p>In the block editor, search for <strong>"RG Promo Code"</strong> or <strong>"promo"</strong> to add the block.</p>

            <h3>Block Settings</h3>
            <table class="widefat" style="margin-top: 10px;">
                <thead>
                    <tr>
                        <th>Setting</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Code Source</strong></td>
                        <td>Choose between "Manual Entry" (type the code) or "ACF Field" (pull from a custom field)</td>
                    </tr>
                    <tr>
                        <td><strong>Promo Code</strong></td>
                        <td>The promo code text (when using Manual Entry)</td>
                    </tr>
                    <tr>
                        <td><strong>ACF Field Name</strong></td>
                        <td>The ACF field name to pull the code from (when using ACF Field)</td>
                    </tr>
                    <tr>
                        <td><strong>Label</strong></td>
                        <td>The label text shown before the code (default: "Code")</td>
                    </tr>
                    <tr>
                        <td><strong>Size</strong></td>
                        <td>"Default" for standard size, "Mini" for compact card layouts</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px;">
            <h2>Shortcode Usage</h2>
            <p>Use the <code>[rg_promo_code]</code> shortcode in posts, pages, widgets, or theme files.</p>

            <h3>Shortcode Attributes</h3>
            <table class="widefat" style="margin-top: 10px;">
                <thead>
                    <tr>
                        <th>Attribute</th>
                        <th>Description</th>
                        <th>Default</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><code>code</code></td>
                        <td>Manual promo code value</td>
                        <td><em>(empty)</em></td>
                    </tr>
                    <tr>
                        <td><code>field</code></td>
                        <td>ACF field name to pull the code from</td>
                        <td><em>(empty)</em></td>
                    </tr>
                    <tr>
                        <td><code>post_id</code></td>
                        <td>Specific post ID to get the ACF field from. <strong>In query loops, leave empty to use current post.</strong></td>
                        <td>Current post in loop</td>
                    </tr>
                    <tr>
                        <td><code>label</code></td>
                        <td>Label text before the code</td>
                        <td>Code</td>
                    </tr>
                    <tr>
                        <td><code>size</code></td>
                        <td>Size variant: "default" or "mini"</td>
                        <td>default</td>
                    </tr>
                    <tr>
                        <td><code>hide_empty</code></td>
                        <td>Hide the block when promo code is empty? "yes" or "no"</td>
                        <td>yes</td>
                    </tr>
                </tbody>
            </table>

            <h3 style="margin-top: 20px;">Examples</h3>

            <h4>1. Manual Code</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code code="SUMMER25"]</code></pre>

            <h4>2. Manual Code with Custom Label</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code code="SAVE10" label="Discount"]</code></pre>

            <h4>3. Mini Size (for cards)</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code code="FAMPACK" size="mini"]</code></pre>

            <h4>4. From ACF Field (current post)</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code field="promo_code"]</code></pre>

            <h4>5. From ACF Field (specific post)</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code field="promo_code" post_id="123"]</code></pre>

            <h4>6. ACF Field with Mini Size</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code field="offer_code" label="Use Code" size="mini"]</code></pre>

            <h4>7. Debug Mode (show HTML comment when empty)</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code field="promo_code" hide_empty="no"]</code></pre>
        </div>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px; background: #fff8e5; border-left: 4px solid #dba617;">
            <h2 style="margin-top: 0;">Usage in Query Loops</h2>
            <p>When using the shortcode inside a <strong>Kadence Query Loop</strong>, <strong>WP Query Loop</strong>, or any post loop, <strong>do NOT specify post_id</strong>. The shortcode will automatically use the current post in the loop.</p>

            <h4>Example: In Kadence Query Loop (Offer cards)</h4>
            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>[rg_promo_code field="promo_code" size="mini"]</code></pre>

            <p style="margin-top: 15px;"><strong>How it works:</strong></p>
            <ul style="margin-left: 20px;">
                <li>For each post in the loop, the shortcode checks the <code>promo_code</code> ACF field</li>
                <li>If the field has a value → displays the promo code box</li>
                <li>If the field is empty → hides completely (nothing rendered)</li>
            </ul>

            <p style="margin-top: 15px;"><strong>Supported loops:</strong></p>
            <ul style="margin-left: 20px;">
                <li>Kadence Query Loop block</li>
                <li>WordPress Query Loop block</li>
                <li>Custom WP_Query loops in theme files</li>
                <li>Elementor loops</li>
                <li>Any loop using standard WordPress post globals</li>
            </ul>
        </div>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px;">
            <h2>PHP Usage (in Theme Files)</h2>
            <p>You can also use the shortcode in your theme PHP files:</p>

            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>&lt;?php echo do_shortcode('[rg_promo_code code="SUMMER25"]'); ?&gt;</code></pre>

            <p style="margin-top: 15px;">Or with ACF field:</p>

            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>&lt;?php echo do_shortcode('[rg_promo_code field="promo_code"]'); ?&gt;</code></pre>
        </div>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px;">
            <h2>Output HTML</h2>
            <p>The promo code box outputs the following HTML structure:</p>

            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>&lt;div class="rg-promo-code-box"&gt;
    &lt;span class="promo-label"&gt;Code&lt;/span&gt;
    &lt;span class="promo-code"&gt;SUMMER25&lt;/span&gt;
    &lt;button class="promo-copy-btn"&gt;Copy&lt;/button&gt;
&lt;/div&gt;</code></pre>

            <p style="margin-top: 15px;">For mini size, add the class <code>rg-promo-code-box--mini</code>:</p>

            <pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>&lt;div class="rg-promo-code-box rg-promo-code-box--mini"&gt;
    ...
&lt;/div&gt;</code></pre>
        </div>

        <div class="card" style="max-width: 800px; padding: 20px; margin-top: 20px; background: #f0f6fc; border-left: 4px solid #0073aa;">
            <h2 style="margin-top: 0;">ACF Field Setup</h2>
            <p>To use the ACF field option, create a text field in ACF with your desired field name (e.g., <code>promo_code</code>).</p>
            <p>The field can be added to any post type (Posts, Pages, Custom Post Types).</p>
            <p><strong>Note:</strong> If the ACF field is empty or doesn't exist, the promo code box will not be displayed.</p>
        </div>
    </div>
    <?php
}
