<?php
/**
 * BW Advanced Tabordion Block
 * 
 * A flexible accordion/tab hybrid block with left menu navigation and rich content area
 */

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register the block
 */
function bw_register_advanced_tabordion_block() {
    // Register block script
    wp_register_script(
        'bw-advanced-tabordion-block-editor',
        get_stylesheet_directory_uri() . '/blocks/bw-advanced-tabordion/block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-block-editor', 'wp-server-side-render', 'lodash'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-advanced-tabordion/block.js')
    );

    // Register block editor style
    wp_register_style(
        'bw-advanced-tabordion-block-editor',
        get_stylesheet_directory_uri() . '/blocks/bw-advanced-tabordion/editor.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-advanced-tabordion/editor.css')
    );

    // Register frontend style
    wp_register_style(
        'bw-advanced-tabordion-block',
        get_stylesheet_directory_uri() . '/blocks/bw-advanced-tabordion/style.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-advanced-tabordion/style.css')
    );

    // Register frontend script
    wp_register_script(
        'bw-advanced-tabordion-frontend',
        get_stylesheet_directory_uri() . '/blocks/bw-advanced-tabordion/frontend.js',
        array('jquery'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-advanced-tabordion/frontend.js'),
        true
    );

    // Register the block
    register_block_type('bw/advanced-tabordion', array(
        'editor_script' => 'bw-advanced-tabordion-block-editor',
        'editor_style' => 'bw-advanced-tabordion-block-editor',
        'style' => 'bw-advanced-tabordion-block',
        'script' => 'bw-advanced-tabordion-frontend',
        'render_callback' => 'bw_advanced_tabordion_block_render',
        'supports' => array(
            'html' => false,
            'anchor' => true,
            'align' => array('wide', 'full'),
            'customClassName' => true,
            'inserter' => true,
            'multiple' => true,
            // This is important - it tells WP we use innerBlocks
            'innerBlocks' => true,
        ),
        'attributes' => array(
            'uniqueId' => array(
                'type' => 'string',
                'default' => '',
            ),
            'tabs' => array(
                'type' => 'array',
                'default' => array(),
                'items' => array(
                    'type' => 'object',
                ),
            ),
            'activeTab' => array(
                'type' => 'number',
                'default' => 0,
            ),
            'menuWidth' => array(
                'type' => 'number',
                'default' => 25,
            ),
            'contentWidth' => array(
                'type' => 'number',
                'default' => 75,
            ),
            'tabBackground' => array(
                'type' => 'string',
                'default' => '#f7f7f7',
            ),
            'activeTabBackground' => array(
                'type' => 'string',
                'default' => '#ffffff',
            ),
            'tabColor' => array(
                'type' => 'string',
                'default' => '#333333',
            ),
            'activeTabColor' => array(
                'type' => 'string',
                'default' => '#333333',
            ),
            'tabBorder' => array(
                'type' => 'string',
                'default' => '#dddddd',
            ),
            'contentBorder' => array(
                'type' => 'string',
                'default' => '#dddddd',
            ),
            'contentBackground' => array(
                'type' => 'string',
                'default' => '#ffffff',
            ),
            'className' => array(
                'type' => 'string',
                'default' => '',
            ),
        ),
    ));
}
add_action('init', 'bw_register_advanced_tabordion_block');

/**
 * Render the block on frontend
 */
function bw_advanced_tabordion_block_render($attributes, $content, $block) {
    // Extract attributes with defaults
    $unique_id = isset($attributes['uniqueId']) ? $attributes['uniqueId'] : 'tabordion-' . wp_rand(10000, 99999);
    $tabs = isset($attributes['tabs']) ? $attributes['tabs'] : array();
    $active_tab = isset($attributes['activeTab']) ? intval($attributes['activeTab']) : 0;
    $menu_width = isset($attributes['menuWidth']) ? intval($attributes['menuWidth']) : 25;
    $content_width = isset($attributes['contentWidth']) ? intval($attributes['contentWidth']) : 75;
    $tab_background = isset($attributes['tabBackground']) ? $attributes['tabBackground'] : 'transparent';
    $active_tab_background = isset($attributes['activeTabBackground']) ? $attributes['activeTabBackground'] : 'transparent';
    $tab_color = isset($attributes['tabColor']) ? $attributes['tabColor'] : '#333333';
    $active_tab_color = isset($attributes['activeTabColor']) ? $attributes['activeTabColor'] : '#333333';
    $tab_border = isset($attributes['tabBorder']) ? $attributes['tabBorder'] : '#dddddd';
    $content_border = isset($attributes['contentBorder']) ? $attributes['contentBorder'] : '#dddddd';
    $content_background = isset($attributes['contentBackground']) ? $attributes['contentBackground'] : 'transparent';
    $class_name = isset($attributes['className']) ? $attributes['className'] : '';

    // If no tabs, return early
    if (empty($tabs)) {
        return '';
    }

    // Start output buffer
    ob_start();

    // Build custom styles
    $styles = "
        /* Tabordion custom styling */
        #{$unique_id} .bw-tabordion-menu {
            width: {$menu_width}%;
        }
        #{$unique_id} .bw-tabordion-content-wrapper {
            width: {$content_width}%;
        }
        #{$unique_id} .bw-tabordion-tab {
            background-color: {$tab_background};
            color: {$tab_color};
            border-color: {$tab_border};
        }
        #{$unique_id} .bw-tabordion-tab.active {
            background-color: {$active_tab_background};
            color: {$active_tab_color};
        }
        #{$unique_id} .bw-tabordion-content {
            background-color: {$content_background};
            border-color: {$content_border};
        }
    ";

    // Get content from inner blocks
    $content_html = do_blocks($content);

    // Output HTML and CSS
    ?>
    <style id="<?php echo esc_attr($unique_id); ?>-styles">
        <?php echo $styles; ?>
    </style>
    
    <div id="<?php echo esc_attr($unique_id); ?>" class="bw-advanced-tabordion <?php echo esc_attr($class_name); ?>">
        <div class="bw-tabordion-container">
            <!-- Tabs menu (left side) -->
            <div class="bw-tabordion-menu">
                <ul class="bw-tabordion-tabs">
                    <?php 
                    // Loop through tabs to build menu
                    foreach ($tabs as $index => $tab) {
                        // Skip if tab is marked as not to be shown in menu
                        if (isset($tab['hideFromMenu']) && $tab['hideFromMenu']) {
                            continue;
                        }
                        
                        $tab_type = isset($tab['tabType']) ? $tab['tabType'] : 'normal';
                        $tab_title = isset($tab['title']) ? $tab['title'] : 'Tab ' . ($index + 1);
                        $tab_url = isset($tab['customUrl']) ? $tab['customUrl'] : '#';
                        $is_active = ($index === $active_tab) ? 'active' : '';
                        $is_child = ($tab_type === 'child') ? 'child-tab' : '';
                        $is_placeholder = ($tab_type === 'placeholder') ? 'placeholder-tab' : '';
                        $parent_id = isset($tab['parentId']) ? $tab['parentId'] : '';
                        $parent_attr = !empty($parent_id) ? 'data-parent="' . esc_attr($parent_id) . '"' : '';
                        
                        // Create section ID from title (for URL parameters)
                        $section_id = '';
                        if (isset($tab['sectionId']) && !empty($tab['sectionId'])) {
                            // Use explicitly set section ID if available
                            $section_id = sanitize_title($tab['sectionId']);
                        } else {
                            // Generate from title
                            $section_id = sanitize_title($tab_title);
                        }
                        
                        // Special handling based on tab type
                        if ($tab_type === 'normal' || $tab_type === 'child' || $tab_type === 'parent') {
                            // Normal, parent, and child tabs get normal tab behavior
                            $is_parent = ($tab_type === 'parent') ? 'parent-tab' : '';
                            ?>
                            <li class="bw-tabordion-tab <?php echo esc_attr($is_active); ?> <?php echo esc_attr($is_child); ?> <?php echo esc_attr($is_parent); ?>" 
                                data-tab="<?php echo esc_attr($index); ?>"
                                data-type="<?php echo esc_attr($tab_type); ?>"
                                data-section="<?php echo esc_attr($section_id); ?>"
                                <?php echo $parent_attr; ?>>
                                <a href="javascript:void(0);" data-target="<?php echo esc_attr($index); ?>">
                                    <?php echo esc_html($tab_title); ?>
                                </a>
                            </li>
                            <?php
                        } elseif ($tab_type === 'placeholder') {
                            // Placeholder tabs get placeholder styling
                            ?>
                            <li class="bw-tabordion-tab <?php echo esc_attr($is_placeholder); ?>"
                                data-tab="placeholder"
                                data-type="placeholder"
                                data-section="<?php echo esc_attr($section_id); ?>"
                                <?php echo $parent_attr; ?>>
                                <?php if (!empty($tab_url) && $tab_url !== '#'): ?>
                                    <?php
                                    // Determine if URL is external
                                    $is_external = false;
                                    $open_in_new_tab = isset($tab['openInNewTab']) ? $tab['openInNewTab'] : false;
                                    
                                    // Check if URL is external (starts with http/https and not containing site URL)
                                    if (preg_match('/^https?:\/\//i', $tab_url)) {
                                        $site_url = get_site_url();
                                        $is_external = (strpos($tab_url, $site_url) !== 0);
                                    }
                                    
                                    // Check if it's a PDF file
                                    $is_pdf = (strtolower(substr($tab_url, -4)) === '.pdf');
                                    
                                    // Always open in new tab if external or PDF, or if specifically set
                                    $target = ($is_external || $is_pdf || $open_in_new_tab) ? 'target="_blank"' : '';
                                    $link_class = $is_external ? 'external-link' : 'internal-link';
                                    ?>
                                    <a href="<?php echo esc_url($tab_url); ?>" class="<?php echo esc_attr($link_class); ?>" <?php echo $target; ?>>
                                        <?php echo esc_html($tab_title); ?>
                                    </a>
                                <?php else: ?>
                                    <span><?php echo esc_html($tab_title); ?></span>
                                <?php endif; ?>
                            </li>
                            <?php
                        }
                    }
                    ?>
                </ul>
            </div>
            
            <!-- Content area (right side) -->
            <div class="bw-tabordion-content-wrapper">
                <?php 
                // Loop through tabs again to create content panels
                foreach ($tabs as $index => $tab) {
                    // Skip placeholder tabs (they have no content)
                    if (isset($tab['tabType']) && $tab['tabType'] === 'placeholder') {
                        continue;
                    }
                    
                    $tab_type = isset($tab['tabType']) ? $tab['tabType'] : 'normal';
                    $is_active = ($index === $active_tab) ? 'active' : '';
                    ?>
                    <div id="<?php echo esc_attr($unique_id . '-tab-' . $index); ?>"
                         class="bw-tabordion-content <?php echo esc_attr($is_active); ?>"
                         data-tab="<?php echo esc_attr($index); ?>">
                        <div class="bw-tabordion-innerblocks">
                            <?php 
                            // Render the structured tab content
                            $tab_content = '';
                            
                            // Check if we have tabContent structure
                            if (!empty($tab['tabContent'])) {
                                $tabContent = $tab['tabContent'];
                                
                                ob_start();
                                ?>
                                <div class="tab-structured-layout">
                                    <!-- Background Image Column (60%) -->
                                    <div class="tab-bg-column">
                                        <?php if (!empty($tabContent['backgroundImage'])): ?>
                                            <img src="<?php echo esc_url($tabContent['backgroundImage']); ?>" 
                                                alt="" 
                                                class="tab-background-image" />
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Content Column (40%) -->
                                    <div class="tab-text-column">
                                        <?php if (!empty($tabContent['subtitle'])): ?>
                                            <div class="tab-subtitle">
                                                <?php if (isset($tabContent['hasIcon']) && $tabContent['hasIcon'] && !empty($tabContent['iconImage'])): ?>
                                                    <div class="tab-icon">
                                                        <img src="<?php echo esc_url($tabContent['iconImage']); ?>" 
                                                             alt="" 
                                                             class="tab-icon-image" />
                                                    </div>
                                                <?php endif; ?>
                                                <p class="subtitle-text"><?php echo wp_kses_post($tabContent['subtitle']); ?></p>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($tabContent['heading'])): ?>
                                            <h2 class="tab-heading"><?php echo wp_kses_post($tabContent['heading']); ?></h2>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($tabContent['paragraph'])): ?>
                                            <div class="tab-paragraph">
                                                <?php 
                                                    // For HTML content, we need to make sure it's not encoded
                                                    // First decode any stored HTML entities
                                                    $paragraph_content = html_entity_decode($tabContent['paragraph']); 
                                                    
                                                    // Then apply minimal filtering for security but preserve HTML
                                                    // Note: Using a less restrictive filter to allow more HTML
                                                    echo wp_kses_post($paragraph_content);
                                                ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php
                                $tab_content = ob_get_clean();
                            }
                            // Fallback for old content format
                            elseif (!empty($tab['content'])) {
                                $content_to_render = stripslashes($tab['content']);
                                $tab_content = wpautop($content_to_render);
                            }
                            // Empty tab
                            else {
                                $tab_content = '<p><em>' . __('No content yet. Edit this block to add content to this tab.', 'kadence-child') . '</em></p>';
                            }
                            
                            echo $tab_content;
                            ?>
                        </div>
                    </div>
                    <?php
                }
                ?>
            </div>
        </div>
    </div>
    <?php

    // Return the buffered content
    return ob_get_clean();
}

/**
 * Add custom category for our blocks if needed
 */
function bw_block_categories_tabordion($categories, $post) {
    return array_merge(
        $categories,
        array(
            array(
                'slug' => 'bw-blocks',
                'title' => __('BW Blocks', 'kadence-child'),
            ),
        )
    );
}
add_filter('block_categories_all', 'bw_block_categories_tabordion', 10, 2);