<?php
/**
 * Manages the meta boxes for the 'event' custom post type.
 * This class replaces the old event-settings.php file.
 *
 * @package    Event_Monster
 * @subpackage Event_Monster/includes
 */
class Event_Monster_Free_Metabox
{

    /**
     * Initialize the class and set its hooks.
     */
    public function __construct()
    {
        add_action('add_meta_boxes', array($this, 'add_event_meta_box'));
        add_action('save_post_awl_event_monster', array($this, 'save_event_meta_data'));
    }

    /**
     * Adds the meta box container to the 'event' post type editor screen.
     */
    public function add_event_meta_box()
    {
        add_meta_box(
            'em_event_details_metabox',                 // Unique ID
            __('Event Monster Setting Panel', 'event-monster-premium'), // Box title from your old code
            array($this, 'render_meta_box_content'),  // Content callback
            'awl_event_monster',                        // The slug of your custom post type
            'normal',                                   // Context
            'high'                                      // Priority
        );
    }

    /**
     * Renders the HTML content for the meta box.
     * The content of your old event-settings.php file is now here.
     *
     * @param WP_Post $post The post object.
     */
    public function render_meta_box_content($post)
    {
        // Add a nonce field for security. This is crucial.
        wp_nonce_field('em_save_event_details_nonce', 'em_save_nonce');

        // Get all saved settings for this event post.
        $Event_Monster_Free_settings = get_post_meta($post->ID, 'awl_em_settings_' . $post->ID, true);
        if (!is_array($Event_Monster_Free_settings))
            $Event_Monster_Free_settings = array();

        // We can now include the old file to render the HTML.
        // This is a temporary step. The ideal final state is to move the raw HTML from that file
        // directly into this function to avoid the include call.
        include(EM_FREE_PLUGIN_DIR . 'templates/admin/metabox-event-settings.php');

    }

    /**
     * Saves the meta box data when the post is saved.
     * This method REPLACES your old `_awl_em_save_settings` function.
     *
     * @param int $post_id The ID of the post being saved.
     */
    public function save_event_meta_data($post_id)
    {
        // 1. Check if our nonce is set and is valid.
        if (!isset($_POST['em_save_nonce']) || !wp_verify_nonce($_POST['em_save_nonce'], 'em_save_event_details_nonce')) {
            return;
        }

        // 2. If this is an autosave, our form has not been submitted, so we don't want to do anything.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // 3. Check the user's permissions.
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // 4. Sanitize and save the data.
        // Instead of saving the entire $_POST array, we should sanitize each expected value.
        // This is much more secure.

        $sanitized_settings = array();

        // Example for text fields
        $text_fields = ['em_start_date', 'em_end_date', 'em_start_time', 'em_end_time', 'em_venue'];
        foreach ($text_fields as $field) {
            if (isset($_POST[$field])) {
                $sanitized_settings[$field] = sanitize_text_field($_POST[$field]);
            }
        }

        // Handle array fields (organizers, speakers, sponsors, etc.)
        $array_fields = [
            'em_organizer_name' => 'sanitize_text_field',
            'em_organizer_speciality' => 'sanitize_text_field',
            'em_speaker_name' => 'sanitize_text_field',
            'em_speaker_speciality' => 'sanitize_text_field',
            'em_speaker_avatar' => 'esc_url_raw',
            'em-slide-spr-ids' => 'absint',
            'em-slide-spr-names' => 'sanitize_text_field',
            'em-slide-spr-links' => 'esc_url_raw'
        ];

        foreach ($array_fields as $field => $sanitize_function) {
            if (isset($_POST[$field]) && is_array($_POST[$field])) {
                $sanitized_settings[$field] = array_map($sanitize_function, $_POST[$field]);
            }
        }

        // Example for textarea fields (including venue)
        $textarea_fields = ['em_venue', 'em_event_details', 'em_cancellation_message'];
        foreach ($textarea_fields as $field) {
            if (isset($_POST[$field])) {
                $sanitized_settings[$field] = sanitize_textarea_field($_POST[$field]);
            }
        }

        // Example for arrays (like ticket details)
        if (isset($_POST['em_ticket_name']) && is_array($_POST['em_ticket_name'])) {
            $sanitized_settings['em_ticket_name'] = array_map('sanitize_text_field', $_POST['em_ticket_name']);
        }
        // ... repeat for em_ticket_price, em_ticket_quantity etc.

        // Registration fields
        $registration_fields = [
            'em_accept_registration', 
            'em_registration_type', 
            'em_external_link',
            'em_reg_btn_txt',
            'em_reg_btn_color',
            'em_reg_btn_align'
        ];

        foreach ($registration_fields as $field) {
            if (isset($_POST[$field])) {
                $sanitized_settings[$field] = sanitize_text_field($_POST[$field]);
            }
        }

        // Handle checkbox for registration (if not checked, it won't be in $_POST)
        $sanitized_settings['em_accept_registration'] = isset($_POST['em_accept_registration']) ? 'yes' : 'no';

        // Handle checkbox for coupon (if not checked, it won't be in $_POST)
        $sanitized_settings['em_enable_coupon'] = isset($_POST['em_enable_coupon']) ? 'yes' : 'no';

        // Handle layout settings
        if (isset($_POST['em_layout_preference'])) {
            $sanitized_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 (function_exists('em_validate_layout_config_free') && em_validate_layout_config_free($custom_layout)) {
                    $sanitized_settings['em_custom_layout'] = $custom_layout;
                }
            }
        }

        // Handle color scheme setting
        if (isset($_POST['em_color_scheme'])) {
            $color_scheme = sanitize_text_field($_POST['em_color_scheme']);
            if (in_array($color_scheme, ['light', 'dark', 'auto'])) {
                $sanitized_settings['em_color_scheme'] = $color_scheme;
            }
        }



        // Sanitize all POST data before saving (WP Guideline compliance)
        // Instead of saving raw $_POST, we sanitize each field.
        $all_post_data = array();

        // Text fields to sanitize
        $text_fields = array(
            'em_event_start_date', 'em_event_end_date',
            'em_event_start_time', 'em_event_end_time',
            'em_event_location', 'em_event_venue',
            'em_registration_label', 'em_registration_modal',
            'em_show_event_gallery', 'em_gallery_heading',
            'em_show_event_speakers', 'em_speakers_heading',
            'em_show_event_organizer', 'em_organizer_heading',
            'em_show_event_sponsors', 'em_sponsors_heading',
            'em_show_event_social', 'em_social_heading',
            'em_social_display_type', 'em_event_cancelled',
            'em_show_event_map', 'em_map_heading',
            'em_map_lat', 'em_map_lng', 'em_map_zoom',
            'em_show_schedule', 'em_schedule_heading',
            'em_layout_preference', 'em_color_scheme',
            'em_enable_coupon', 'em_show_registration',
            'logo_upd', 'em_upload_image', 'em_upload_video',
            'em_video_option', 'em_upload_icon',
            'em_countdown_bg_color', 'em_countdown_enabled', 'em_countdown_label_days',
            'em_countdown_label_hours', 'em_countdown_label_minutes', 'em_countdown_label_seconds',
            'em_countdown_progress_color', 'em_countdown_progress_thickness',
            'em_gal_thumb_size', 'em_general_message', 'em_general_message_bg_color',
            'em_general_message_border_color', 'em_general_message_text_color',
            'em_map_enabled', 'em_map_height', 'em_map_latitude', 'em_map_longitude',
            'em_map_type', 'em_primary_color', 'em_secondary_color', 'em_share_btn',
            'em_show_event_sponsor', 'em_show_general_message', 'em_show_organizer',
            'em_social_link_target', 'em_social_links_enabled', 'em_speaker_heading',
            'em_sponsor_heading', 'em_spr_link_tab', 'em_text_color', 'em_title_align',
            'em_title_color', 'em_title_size', 'em_tkt_select',
        );

        foreach ($text_fields as $field) {
            if (isset($_POST[$field])) {
                $all_post_data[$field] = sanitize_text_field(wp_unslash($_POST[$field]));
            }
        }

        // Custom CSS sanitization (strip all tags to prevent XSS and style breakouts)
        if (isset($_POST['em_custom_css'])) {
            $all_post_data['em_custom_css'] = wp_strip_all_tags(wp_unslash($_POST['em_custom_css']));
        }

        // Textarea fields (allow some HTML)
        $textarea_fields = array('em_event_description_extra');
        foreach ($textarea_fields as $field) {
            if (isset($_POST[$field])) {
                $all_post_data[$field] = wp_kses_post(wp_unslash($_POST[$field]));
            }
        }

        // Array fields (galleries, speakers, organizers, sponsors, tickets, etc.)
        $array_fields = array(
            'em_event_gallery', 'em_speaker_name', 'em_speaker_title',
            'em_speaker_avatar', 'em_organizer_name', 'em_organizer_phone',
            'em_organizer_email', 'em_organizer_website',
            'em_sponsor_name', 'em_sponsor_logo', 'em_sponsor_website',
            'em_tkt_name', 'em_tkt_price', 'em_tkt_quantity', 'em_tkt_max_range',
            'em_social_links', 'em_schedule_items',
        );

        foreach ($array_fields as $field) {
            if (isset($_POST[$field]) && is_array($_POST[$field])) {
                $all_post_data[$field] = map_deep(wp_unslash($_POST[$field]), 'sanitize_text_field');
            }
        }

        // Merge with the individually sanitized settings from above
        $all_post_data = array_merge($all_post_data, $sanitized_settings);

        // The name of the meta key where all settings for this post are stored.
        $meta_key = "awl_em_settings_" . $post_id;

        // Get old settings to check if cancellation status changed
        $old_settings = get_post_meta($post_id, $meta_key, true);
        $was_cancelled = isset($old_settings['em_event_cancelled']) && $old_settings['em_event_cancelled'] === 'yes';
        $is_now_cancelled = isset($all_post_data['em_event_cancelled']) && $all_post_data['em_event_cancelled'] === 'yes';

        update_post_meta($post_id, $meta_key, $all_post_data);

        // Send cancellation emails if event was just cancelled
        if (!$was_cancelled && $is_now_cancelled) {
            $this->send_cancellation_emails($post_id, $all_post_data);
        }
    }

    /**
     * Send cancellation emails to all registered attendees
     *
     * @param int $post_id The event post ID
     * @param array $event_settings The event settings array
     */
    private function send_cancellation_emails($post_id, $event_settings)
    {
        global $wpdb;

        // Get event title
        $event_title = get_the_title($post_id);

        // Get cancellation message from event settings
        $cancellation_message = isset($event_settings['em_cancellation_message']) ? $event_settings['em_cancellation_message'] : __('This event has been cancelled. We apologize for any inconvenience caused.', 'event-monster');

        // Get all attendees for this event
        $attendees_table = $wpdb->prefix . 'em_attendees';
        $attendees = $wpdb->get_results($wpdb->prepare(
            "SELECT DISTINCT email, first_name, last_name FROM $attendees_table WHERE event_id = %d",
            $post_id
        ));

        if (empty($attendees)) {
            return; // No attendees to notify
        }

        // Get email settings
        $em_common_settings = get_option('awl_em_common_settings');

        // Initialize email class
        require_once EM_FREE_PLUGIN_DIR . 'includes/class-event-monster-emails.php';
        $email_handler = new Event_Monster_Free_Emails();

        // Email subject
        $subject = sprintf(__('Event Cancelled: %s', 'event-monster'), $event_title);

        // Send email to each attendee
        foreach ($attendees as $attendee) {
            $attendee_name = trim($attendee->first_name . ' ' . $attendee->last_name);
            if (empty($attendee_name)) {
                $attendee_name = __('Valued Guest', 'event-monster');
            }

            // Build cancellation email content
            $message_body = '<h1 style="color: #DC2626; font-size: 24px; margin: 0 0 20px 0;">' . __('Event Cancelled', 'event-monster') . '</h1>';
            $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 20px 0;">' . sprintf(__('Dear %s,', 'event-monster'), '<strong>' . esc_html($attendee_name) . '</strong>') . '</p>';
            $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 20px 0;">' . sprintf(__('We regret to inform you that the following event has been cancelled:', 'event-monster')) . '</p>';

            // Event details box
            $message_body .= '<table width="100%" cellpadding="20" cellspacing="0" border="0" style="background-color: #FEF2F2; border: 2px solid #FCA5A5; border-radius: 8px; margin: 0 0 30px 0;">';
            $message_body .= '<tr><td>';
            $message_body .= '<h2 style="color: #DC2626; font-size: 20px; margin: 0 0 10px 0;">' . esc_html($event_title) . '</h2>';
            $message_body .= '<p style="color: #991B1B; font-size: 14px; margin: 0; font-weight: bold;">' . __('STATUS: CANCELLED', 'event-monster') . '</p>';
            $message_body .= '</td></tr></table>';

            // Cancellation message
            $message_body .= '<div style="background-color: #F9FAFB; padding: 20px; border-left: 4px solid #DC2626; margin: 0 0 30px 0;">';
            $message_body .= '<p style="color: #374151; font-size: 15px; line-height: 1.6; margin: 0;">' . wp_kses_post(wpautop($cancellation_message)) . '</p>';
            $message_body .= '</div>';

            // Closing message
            $message_body .= '<p style="color: #666666; font-size: 16px; line-height: 1.6; margin: 0 0 10px 0;">' . __('We apologize for any inconvenience this may cause.', 'event-monster') . '</p>';
            $message_body .= '<p style="color: #666666; font-size: 14px; line-height: 1.6; margin: 0;">' . __("If you have any questions, please don't hesitate to contact us.", 'event-monster') . '</p>';

            // Wrap in HTML email template
            $email_content = $email_handler->get_html_email_template($message_body);

            // Send the email
            $email_handler->send($attendee->email, $subject, $email_content);
        }
    }
}
