<?php
/**
 * Event Layout Settings Page
 * Admin interface for managing event layout configurations
 */
if (!defined('ABSPATH')) exit;

class EM_Free_Layout_Settings {
    
    public function __construct() {
        // We don't need the separate meta box since we're integrating into existing tabs
        // We also don't need a separate save hook - we'll integrate with existing save system
        add_action('wp_ajax_em_preview_layout', array($this, 'ajax_preview_layout'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('admin_footer', array($this, 'output_component_data'));
    }
    
    /**
     * Add layout meta box to event edit page
     */
    public function add_layout_meta_box() {
        add_meta_box(
            'em-layout-settings',
            __('Event Layout Configuration', 'event-monster'),
            array($this, 'render_layout_meta_box'),
            'awl_event_monster', // Correct post type for Event Monster
            'normal',
            'high'
        );
    }
    
    /**
     * Render layout meta box content
     */
    public function render_layout_meta_box($post) {
        // Get current settings
        $event_settings = get_post_meta($post->ID, 'awl_em_settings_' . $post->ID, true);
        if (!is_array($event_settings)) {
            $event_settings = array();
        }
        
        // Add nonce field
        wp_nonce_field('EM_Free_Layout_Settings', 'em_layout_nonce');
        
        // Include layout builder
        $event_id = $post->ID;
        include EM_FREE_PLUGIN_DIR . 'templates/admin/layout-builder.php';
        
        // Add component data for JavaScript
        $this->output_component_data();
    }
    
    /**
     * Output component data for JavaScript
     */
    public function output_component_data() {
        global $post_type;

        // Only output on event edit pages
        if (!isset($post_type) || $post_type !== 'awl_event_monster') {
            return;
        }
        include_once EM_FREE_PLUGIN_DIR . 'templates/frontend/layout-config.php';
        
        $available_components = array(
            'cancellation' => array(
                'name' => __('Event Cancellation', 'event-monster'),
                'description' => __('Cancellation notice and information', 'event-monster'),
                'icon' => 'dashicons-dismiss',
                'category' => 'system'
            ),
            'messages' => array(
                'name' => __('Event Messages', 'event-monster'),
                'description' => __('Important messages and announcements', 'event-monster'),
                'icon' => 'dashicons-megaphone',
                'category' => 'system'
            ),
            'header' => array(
                'name' => __('Event Header', 'event-monster'),
                'description' => __('Event title, banner image, and basic info', 'event-monster'),
                'icon' => 'dashicons-format-image',
                'category' => 'content'
            ),
            'countdown' => array(
                'name' => __('Countdown Timer', 'event-monster'),
                'description' => __('Live countdown to event start', 'event-monster'),
                'icon' => 'dashicons-clock',
                'category' => 'interactive'
            ),
            'content' => array(
                'name' => __('Event Content', 'event-monster'),
                'description' => __('Main event description and details', 'event-monster'),
                'icon' => 'dashicons-text-page',
                'category' => 'content'
            ),
            'details' => array(
                'name' => __('Event Details', 'event-monster'),
                'description' => __('Date, time, location, and venue info', 'event-monster'),
                'icon' => 'dashicons-calendar-alt',
                'category' => 'information'
            ),
            'map' => array(
                'name' => __('Location Map', 'event-monster'),
                'description' => __('Interactive Google Maps integration', 'event-monster'),
                'icon' => 'dashicons-location',
                'category' => 'information'
            ),
            'gallery' => array(
                'name' => __('Event Gallery', 'event-monster'),
                'description' => __('Photo gallery and media showcase', 'event-monster'),
                'icon' => 'dashicons-format-gallery',
                'category' => 'media'
            ),
            'schedule' => array(
                'name' => __('Event Schedule', 'event-monster'),
                'description' => __('Timeline and agenda', 'event-monster'),
                'icon' => 'dashicons-schedule',
                'category' => 'information'
            ),
            'speakers' => array(
                'name' => __('Speakers', 'event-monster'),
                'description' => __('Speaker profiles and information', 'event-monster'),
                'icon' => 'dashicons-groups',
                'category' => 'people'
            ),
            'organizers' => array(
                'name' => __('Organizers', 'event-monster'),
                'description' => __('Event organizer contact information', 'event-monster'),
                'icon' => 'dashicons-businessman',
                'category' => 'people'
            ),
            'sponsors' => array(
                'name' => __('Sponsors', 'event-monster'),
                'description' => __('Sponsor logos and information', 'event-monster'),
                'icon' => 'dashicons-awards',
                'category' => 'people'
            ),
            'registration' => array(
                'name' => __('Registration', 'event-monster'),
                'description' => __('Registration form and booking', 'event-monster'),
                'icon' => 'dashicons-forms',
                'category' => 'interactive'
            )
        );
        
        echo '<script type="text/javascript">';
        echo 'window.emComponents = ' . json_encode($available_components) . ';';
        echo '</script>';
    }
    
    /**
     * Save layout settings
     */
    public function save_layout_settings($post_id) {
        // Check nonce
        if (!isset($_POST['em_layout_nonce']) || !wp_verify_nonce($_POST['em_layout_nonce'], 'EM_Free_Layout_Settings')) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Get existing settings
        $event_settings = get_post_meta($post_id, 'awl_em_settings_' . $post_id, true);
        if (!is_array($event_settings)) {
            $event_settings = array();
        }
        
        // Update layout settings
        if (isset($_POST['em_layout_preference'])) {
            $event_settings['em_layout_preference'] = sanitize_text_field($_POST['em_layout_preference']);
        }
        
        if (isset($_POST['em_custom_layout'])) {
            $custom_layout = json_decode(stripslashes($_POST['em_custom_layout']), true);
            if (is_array($custom_layout)) {
                // Validate custom layout
                include_once EM_FREE_PLUGIN_DIR . 'templates/frontend/layout-config.php';
                if (em_validate_layout_config_free($custom_layout)) {
                    $event_settings['em_custom_layout'] = $custom_layout;
                }
            }
        }
        
        // Save updated settings
        update_post_meta($post_id, 'awl_em_settings_' . $post_id, $event_settings);
        
        // Clear any cached layout data
        delete_transient('em_layout_cache_' . $post_id);
    }
    
    /**
     * AJAX handler for layout preview
     */
    public function ajax_preview_layout() {
        // Verify nonce
        check_ajax_referer('em_layout_builder', 'nonce');

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_die(__('You do not have permission to preview layouts.', 'event-monster'));
        }
        
        $event_id = intval($_GET['event_id'] ?? 0);
        $layout = sanitize_text_field($_GET['layout'] ?? 'default');
        
        if (!$event_id) {
            wp_die(__('Invalid event ID.', 'event-monster'));
        }
        
        // Get event data
        $event_post = get_post($event_id);
        $event_settings = get_post_meta($event_id, 'awl_em_settings_' . $event_id, true);
        
        if (!$event_post) {
            wp_die(__('Event not found.', 'event-monster'));
        }
        
        // Temporarily set layout preference for preview
        if (!is_array($event_settings)) {
            $event_settings = array();
        }
        $event_settings['em_layout_preference'] = $layout;
        
        // Output preview page
        $this->render_preview_page($event_id, $event_post, $event_settings);
        exit;
    }
    
    /**
     * Render preview page
     */
    private function render_preview_page($event_id, $event_post, $event_settings) {
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo('charset'); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title><?php echo esc_html($event_post->post_title); ?> - Layout Preview</title>
            <style>
                body { 
                    margin: 0; 
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    background: #f0f0f0;
                }
                .preview-header {
                    background: #0073aa;
                    color: white;
                    padding: 15px 20px;
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    z-index: 1000;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                }
                .preview-content {
                    margin-top: 60px;
                    padding: 20px;
                }
                .preview-notice {
                    background: #fff3cd;
                    border: 1px solid #ffeaa7;
                    color: #856404;
                    padding: 10px 15px;
                    border-radius: 4px;
                    margin-bottom: 20px;
                }
            </style>
        </head>
        <body>
            <div class="preview-header">
                <h1 style="margin: 0; font-size: 18px;">
                    <?php _e('Layout Preview', 'event-monster'); ?> - <?php echo esc_html($event_post->post_title); ?>
                </h1>
            </div>
            
            <div class="preview-content">
                <div class="preview-notice">
                    <strong><?php _e('Preview Mode', 'event-monster'); ?>:</strong>
                    <?php _e('This is how your event will look with the selected layout configuration.', 'event-monster'); ?>
                </div>
                
                <?php
                // Include the main template with preview settings
                include EM_FREE_PLUGIN_DIR . 'templates/frontend/single-event-template.php';
                ?>
            </div>
            
            <script>
                // Add some preview-specific JavaScript if needed
                console.log('Event Monster Layout Preview loaded');
            </script>
        </body>
        </html>
        <?php
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        global $post_type;

        // Only load on event edit pages
        if ($hook === 'post.php' || $hook === 'post-new.php') {
            if ($post_type === 'awl_event_monster') { // Correct post type for Event Monster
                
                // Enqueue jQuery UI for drag and drop
                wp_enqueue_script('jquery-ui-draggable');
                wp_enqueue_script('jquery-ui-droppable');
                wp_enqueue_script('jquery-ui-sortable');
                
                // Enqueue layout builder script
                wp_enqueue_script(
                    'em-layout-builder',
                    EM_FREE_PLUGIN_URL . 'assets/js/layout-builder.js',
                    array('jquery', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-sortable'),
                    '1.0.0',
                    true
                );
                
                // Localize script
                wp_localize_script('em-layout-builder', 'emLayoutBuilder', array(
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('em_layout_builder'),
                    'strings' => array(
                        'confirmDelete' => __('Are you sure you want to delete this section?', 'event-monster'),
                        'confirmClear' => __('Are you sure you want to clear the entire layout?', 'event-monster'),
                        'confirmReset' => __('Are you sure you want to reset to default layout?', 'event-monster'),
                        'layoutSaved' => __('Layout saved successfully!', 'event-monster'),
                        'layoutReset' => __('Layout reset to default', 'event-monster')
                    )
                ));
            }
        }
    }
}

// Initialize the layout settings
new EM_Free_Layout_Settings();
?>
