
<?php
/**
 * Layout Configuration System
 * Allows easy customization of component arrangements
 */
if (!defined('ABSPATH')) exit;

/**
 * Get the layout configuration based on settings or defaults
 */
function em_get_layout_configuration_free($event_settings = array()) {
    
    // Get layout preference from settings
    $layout_preference = $event_settings['em_layout_preference'] ?? 'default';
    
    // Define different layout configurations
    $layout_configs = array (
        
        // Default Layout - Updated with countdown and single schedule
        'default' => array(
            // 1. Banner & Title
            'single_header' => array(
                'cancellation', 'messages', 'header'
            ),

            // 2. Details Section (Date, Time, Location)
            'single_details' => array(
                'details'
            ),

            // 3. About Section
            'single_content' => array(
                'content'
            ),

            // 4. Event Gallery (Past Highlights)
            'single_gallery' => array(
                'gallery'
            ),

            // 5. Schedule Section (single column)
            'single_schedule' => array(
                'schedule'
            ),

            // 6. Combined Countdown & Map Section (two columns)
            'two_column_countdown_map' => array(
                array('countdown', 'map')
            ),

            // 7. Speakers & Organizers Section (two columns)
            'two_column_people' => array(
                array('speakers', 'organizers')
            ),

            // 8. Sponsors Section (Event Partners)
            'single_sponsors' => array(
                'sponsors'
            ),

            // 9. Social Icons Section
            'single_social' => array(
                'social'
            ),

            // 10. Registration CTA Section
            'single_end' => array(
                'registration'
            )
        ),

        // Full Width / Magazine Layout - Based on single-event-full-width.html
        'magazine' => array(
            // 1. Full Width Banner Header
            'single_header' => array(
                'cancellation', 'messages', 'header'
            ),

            // 2. Main Content Grid (2/3 main + 1/3 sidebar)
            'magazine_layout' => array(
                // Main content column (left side)
                'main_content' => array('content', 'schedule', 'speakers', 'gallery', 'organizers', 'sponsors', 'social'),
                // Sidebar column (right side)
                'sidebar' => array('registration', 'countdown', 'details', 'map')
            )
        ),
        
        // Custom Layout - User defined
        'custom' => array(
            // This will be populated from user settings
        )
    );
    
    // If custom layout, get from settings
    if ($layout_preference === 'custom' && isset($event_settings['em_custom_layout'])) {
        $layout_configs['custom'] = $event_settings['em_custom_layout'];
    }
    
    return $layout_configs[$layout_preference] ?? $layout_configs['default'];
}

/**
 * Get dynamic container class based on layout
 */
function em_get_container_class_free($layout_config = array()) {
    // Check if magazine layout - use wider container
    if (isset($layout_config['magazine_layout'])) {
        return 'em-container em-mx-auto em-max-w-7xl em-animate-fade-in-up';
    }

    // Check for other layout types that might need different widths
    $has_wide_sections = false;
    foreach ($layout_config as $section_type => $components) {
        if (in_array($section_type, ['two_column_wide', 'three_column', 'four_column'])) {
            $has_wide_sections = true;
            break;
        }
    }

    if ($has_wide_sections) {
        return 'em-container em-mx-auto em-max-w-5xl em-animate-fade-in-up';
    }

    // Default layout - standard width
    return 'em-container em-mx-auto em-max-w-3xl em-animate-fade-in-up';
}

/**
 * Get component file paths
 */
function em_get_component_files_free() {
    return array(
        'cancellation' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-cancellation.php',
        'messages' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-general-message.php',
        'header' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-header.php',
        'countdown' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-countdown.php',
        'content' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-content.php',
        'details' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-details.php',
        'map' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-map.php',
        'gallery' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-gallery.php',
        'schedule' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-schedule.php',
        'speakers' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-speakers.php',
        'organizers' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-organizers.php',
        'sponsors' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-sponsors.php',
        'social' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/event-social.php',
        'registration' => EM_FREE_PLUGIN_DIR . 'templates/frontend/components/registration.php'
    );
}

/**
 * Check if component file exists and include it
 */
function em_include_component_free($component_name, $component_files) {
    if (isset($component_files[$component_name]) && file_exists($component_files[$component_name])) {
        // Access global variables
        global $event_settings, $event_post, $event_id;

        // Auto-enable component if it's being rendered (override individual component settings)
        em_auto_enable_component_free($component_name, $event_settings);

        include $component_files[$component_name];
        return true;
    }
    return false;
}

/**
 * Auto-enable component settings when component is included in layout
 */
function em_auto_enable_component_free($component_name, &$event_settings) {
    $component_settings = array(
        'countdown' => 'em_countdown_enabled',
        'speakers' => 'em_speaker_name', // This component uses speaker data, not a simple enable/disable
        'schedule' => 'em_show_schedule',
        'map' => 'em_map_enabled',
        'organizers' => 'em_show_organizer',
        'sponsors' => 'em_show_event_sponsor',
        'gallery' => 'em_show_event_gallery',
        'social' => 'em_social_links_enabled',
        'registration' => 'em_accept_registration'
    );

    // Components that should respect user's enable/disable setting
    $respect_user_setting = array('social', 'registration', 'countdown', 'map');

    if (isset($component_settings[$component_name])) {
        $setting_key = $component_settings[$component_name];

        // Handle different component types
        if ($component_name === 'speakers') {
            // For speakers, ensure there's data to display
            if (empty($event_settings[$setting_key]) || empty(array_filter($event_settings[$setting_key]))) {
                // Don't force enable if no speaker data exists
                return;
            }
        } elseif (in_array($component_name, $respect_user_setting)) {
            // For components that should respect user settings, don't force enable
            // The component itself will check if it's enabled and return early if not
            return;
        } else {
            // For other components, force enable
            $event_settings[$setting_key] = 'yes';
        }
    }

    // Provide default data for components that need it
    em_provide_default_component_data_free($component_name, $event_settings);
}

/**
 * Provide default data for components that require data to display
 */
function em_provide_default_component_data_free($component_name, &$event_settings) {
    switch ($component_name) {
        case 'speakers':
            if (empty($event_settings['em_speaker_name']) || empty(array_filter($event_settings['em_speaker_name']))) {
                $event_settings['em_speaker_name'] = array('John Doe', 'Jane Smith');
                $event_settings['em_speaker_speciality'] = array('Marketing Expert', 'Digital Strategy');
            }
            break;

        case 'schedule':
            if (empty($event_settings['em_schedule_items'])) {
                $event_settings['em_schedule_items'] = array(
                    array(
                        'time' => '09:00',
                        'title' => 'Registration & Welcome',
                        'description' => 'Check-in and networking with fellow attendees',
                        'speaker' => '',
                        'location' => 'Main Hall'
                    ),
                    array(
                        'time' => '10:00',
                        'title' => 'Opening Keynote',
                        'description' => 'Welcome address and event overview',
                        'speaker' => 'Event Host',
                        'location' => 'Main Stage'
                    )
                );
            }
            break;

        case 'organizers':
            if (empty($event_settings['em_organizer_name']) || empty(array_filter($event_settings['em_organizer_name']))) {
                $event_settings['em_organizer_name'] = array('Event Team');
                $event_settings['em_organizer_phone'] = array('+1234567890');
                $event_settings['em_organizer_email'] = array('info@event.com');
            }
            break;

        case 'gallery':
            if (empty($event_settings['em-slide-ids']) || empty(array_filter($event_settings['em-slide-ids']))) {
                // Provide placeholder image IDs or URLs
                $event_settings['em-slide-ids'] = array('placeholder1', 'placeholder2', 'placeholder3', 'placeholder4');
            }
            break;

        case 'countdown':
            if (empty($event_settings['em_start_date'])) {
                // Set a future date for countdown
                $event_settings['em_start_date'] = date('Y-m-d', strtotime('+30 days'));
                $event_settings['em_start_time'] = '10:00';
            }
            break;
    }
}

/**
 * Render layout section
 */
function em_render_layout_section_free($section_type, $components, $component_files) {

    switch ($section_type) {
        case 'single':
        case 'single_header':
        case 'single_content':
        case 'single_details':
        case 'single_gallery':
        case 'single_schedule':
        case 'single_sponsors':
        case 'single_full':
        case 'single_end':
            if (is_array($components)) {
                // Capture component output to check if any content was rendered
                ob_start();
                foreach ($components as $component_name) {
                    if (em_include_component_free($component_name, $component_files)) {
                        // Component included successfully
                    }
                }
                $section_html = trim(ob_get_clean());

                // Only wrap and output if there's actual content
                if (!empty($section_html)) {
                    echo '<div class="em-component-single">';
                    echo $section_html;
                    echo '</div>';
                }
            }
            break;

        case 'two_column_equal':
        case 'two_column_equal_2':
        case 'two_column_schedule_map':
        case 'two_column_countdown_map':
        case 'two_column_people':
            if (is_array($components)) {
                foreach ($components as $row) {
                    if (is_array($row)) {
                        // Capture each component's output; skip empty components to avoid blank columns
                        $cols_html = [];
                        foreach ($row as $component_name) {
                            ob_start();
                            em_include_component_free($component_name, $component_files);
                            $html = trim(ob_get_clean());
                            $cols_html[] = $html;
                        }
                        // Build columns only for non-empty outputs
                        $rendered_cols = array_filter($cols_html, function($h){ return $h !== ''; });
                        $num_cols = count($rendered_cols);

                        if ($num_cols > 0) {
                            // Dynamic column adjustment based on content availability
                            if ($num_cols === 1) {
                                // Only one component has content - render as single full-width column
                                echo '<div class="em-component-single">';
                                foreach ($cols_html as $html) {
                                    if ($html !== '') {
                                        echo $html;
                                    }
                                }
                                echo '</div>';
                            } else {
                                // Multiple components have content - render as two-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-1 lg:em-grid-cols-2 em-gap-0">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            }
                        }
                    }
                }
            }
            break;
            
        case 'two_column_wide':
            if (is_array($components)) {
                foreach ($components as $row) {
                    if (is_array($row)) {
                        // Capture each component's output first
                        $outputs = [];
                        foreach ($row as $component_name) {
                            ob_start();
                            em_include_component_free($component_name, $component_files);
                            $html = trim(ob_get_clean());
                            $outputs[] = $html;
                        }
                        // Remove empty components (e.g., countdown hidden due to past date)
                        $rendered = array_values(array_filter($outputs, function($h){ return $h !== ''; }));
                        $num_cols = count($rendered);

                        if ($num_cols > 0) {
                            if ($num_cols === 1) {
                                // Only one component - render as single full-width column
                                echo '<div class="em-component-single">';
                                echo $rendered[0];
                                echo '</div>';
                            } else {
                                // Multiple components - render as wide layout
                                echo '<div class="em-component-row em-grid em-grid-cols-2 lg:em-grid-cols-3 em-gap-6">';
                                foreach ($rendered as $idx => $html) {
                                    $col_class = ($idx === 0) ? 'em-component-col lg:em-col-span-2' : 'em-component-col';
                                    echo '<div class="' . $col_class . '">' . $html . '</div>';
                                }
                                echo '</div>';
                            }
                        }
                    }
                }
            }
            break;
            
        case 'three_column':
            if (is_array($components)) {
                foreach ($components as $row) {
                    if (is_array($row)) {
                        // Capture each component's output; skip empty components
                        $cols_html = [];
                        foreach ($row as $component_name) {
                            ob_start();
                            em_include_component_free($component_name, $component_files);
                            $html = trim(ob_get_clean());
                            $cols_html[] = $html;
                        }
                        // Build columns only for non-empty outputs
                        $rendered_cols = array_filter($cols_html, function($h){ return $h !== ''; });
                        $num_cols = count($rendered_cols);

                        if ($num_cols > 0) {
                            if ($num_cols === 1) {
                                // Only one component - render as single full-width column
                                echo '<div class="em-component-single">';
                                foreach ($cols_html as $html) {
                                    if ($html !== '') {
                                        echo $html;
                                    }
                                }
                                echo '</div>';
                            } elseif ($num_cols === 2) {
                                // Two components - render as two-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-1 lg:em-grid-cols-2 em-gap-6">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            } else {
                                // Three or more components - render as three-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-1 md:em-grid-cols-2 lg:em-grid-cols-3 em-gap-6">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            }
                        }
                    }
                }
            }
            break;
            
        case 'four_column':
            if (is_array($components)) {
                foreach ($components as $row) {
                    if (is_array($row)) {
                        // Capture each component's output; skip empty components
                        $cols_html = [];
                        foreach ($row as $component_name) {
                            ob_start();
                            em_include_component_free($component_name, $component_files);
                            $html = trim(ob_get_clean());
                            $cols_html[] = $html;
                        }
                        // Build columns only for non-empty outputs
                        $rendered_cols = array_filter($cols_html, function($h){ return $h !== ''; });
                        $num_cols = count($rendered_cols);

                        if ($num_cols > 0) {
                            if ($num_cols === 1) {
                                // Only one component - render as single full-width column
                                echo '<div class="em-component-single">';
                                foreach ($cols_html as $html) {
                                    if ($html !== '') {
                                        echo $html;
                                    }
                                }
                                echo '</div>';
                            } elseif ($num_cols === 2) {
                                // Two components - render as two-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-1 lg:em-grid-cols-2 em-gap-6">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            } elseif ($num_cols === 3) {
                                // Three components - render as three-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-1 md:em-grid-cols-2 lg:em-grid-cols-3 em-gap-6">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            } else {
                                // Four or more components - render as four-column grid
                                echo '<div class="em-component-row em-grid em-grid-cols-2 md:em-grid-cols-3 lg:em-grid-cols-4 em-gap-6">';
                                foreach ($cols_html as $html) {
                                    if ($html === '') { continue; }
                                    echo '<div class="em-component-col">' . $html . '</div>';
                                }
                                echo '</div>';
                            }
                        }
                    }
                }
            }
            break;

        case 'magazine_layout':
            // Magazine layout - Full width with proper grid system
            // First, close any existing container and start fresh
            echo '</div>'; // Close the default layout container

            // Full width magazine container
            echo '<div class="" style="">';

            // Use the container class function for magazine layout
            $magazine_config = array('magazine_layout' => true);
            $container_class = em_get_container_class_free($magazine_config);
            echo '<div class="' . $container_class . '">';

            // Responsive padding
            echo '<style>';
            echo '@media (min-width: 640px) { .em-magazine-container { padding: 1.5rem; } }';
            echo '@media (min-width: 1024px) { .em-magazine-container { padding: 2rem; } }';
            echo '</style>';

            // Main Layout - Flexbox approach for reliable side-by-side layout
            echo '<div class="em-magazine-layout-wrapper" style="display: flex; flex-direction: column; gap: 1rem; margin-top: 2rem;">';

            // Add responsive flexbox CSS
            echo '<style>';
            echo '.em-magazine-layout-wrapper { display: flex !important; flex-direction: column !important; gap: 1rem !important; }';
            echo '@media (min-width: 1024px) {';
            echo '  .em-magazine-layout-wrapper { flex-direction: row !important; align-items: flex-start !important; }';
            echo '  .em-magazine-main { flex: 2 !important; }';
            echo '  .em-magazine-sidebar { flex: 1 !important; min-width: 300px !important; }';
            echo '}';
            echo '</style>';

            // Main content column (2/3 width using flex: 2)
            // Capture main content output
            ob_start();
            if (isset($components['main_content']) && is_array($components['main_content'])) {
                foreach ($components['main_content'] as $component_name) {
                    if (em_include_component_free($component_name, $component_files)) {
                        // Component included successfully
                    }
                }
            }
            $main_content_html = trim(ob_get_clean());

            // Only output main content wrapper if there's content
            if (!empty($main_content_html)) {
                echo '<main class="em-magazine-main">';
                echo $main_content_html;
                echo '</main>';
            }

            // Sidebar column (1/3 width using flex: 1)
            // Capture sidebar output
            ob_start();
            if (isset($components['sidebar']) && is_array($components['sidebar'])) {
                foreach ($components['sidebar'] as $component_name) {
                    if (em_include_component_free($component_name, $component_files)) {
                        // Component included successfully
                    }
                }
            }
            $sidebar_html = trim(ob_get_clean());

            // Only output sidebar wrapper if there's content
            if (!empty($sidebar_html)) {
                echo '<aside class="em-magazine-sidebar em-animate-fade-in em-animate-delay-200">';
                echo $sidebar_html;
                echo '</aside>';
            }

            echo '</div>'; // Close flexbox wrapper
            echo '</div>'; // Close magazine container
            echo '</div>'; // Close full width wrapper

            // Start a new container for any remaining content
            echo '<div class="em-layout-content em-w-full">';
            break;
    }
}

/**
 * Get layout preview for admin
 */
function em_get_layout_preview_free($layout_name) {
    $previews = array(
        'default' => 'Traditional single-column layout with details + map in two columns',
        'magazine' => 'Full-width magazine layout with main content area and sidebar',
        'custom' => 'User-defined custom layout arrangement'
    );

    return $previews[$layout_name] ?? 'Custom layout configuration';
}

/**
 * Validate layout configuration
 */
function em_validate_layout_config_free($config) {
    $valid_sections = array('single', 'single_header', 'single_content', 'single_full', 'single_end', 'two_column_equal', 'two_column_equal_2', 'two_column_wide', 'three_column', 'four_column', 'magazine_layout');
    $valid_components = array_keys(em_get_component_files_free());
    
    foreach ($config as $section_type => $components) {
        if (!in_array($section_type, $valid_sections)) {
            return false;
        }
        
        if (in_array($section_type, array('single', 'single_header', 'single_content', 'single_full', 'single_end'))) {
            foreach ($components as $component) {
                if (!in_array($component, $valid_components)) {
                    return false;
                }
            }
        } else {
            foreach ($components as $row) {
                if (!is_array($row)) {
                    return false;
                }
                foreach ($row as $component) {
                    if (!in_array($component, $valid_components)) {
                        return false;
                    }
                }
            }
        }
    }
    
    return true;
}
?>

