<?php
// In includes/class-event-monster-admin.php
// Event Monster Free Version - Limited Features

class Event_Monster_Free_Admin
{
    private $plugin_name;
    private $version;
    private $option_name;
    private $options;

    public function __construct($plugin_name, $version)
    {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->option_name = 'awl_em_common_settings';
        $this->options = get_option($this->option_name, array());

        $this->load_dependencies();

        add_action('admin_menu', array($this, 'add_plugin_admin_menu'));
        add_action('admin_footer-post.php', array($this, 'add_modal_containers'));
        add_action('admin_footer-post-new.php', array($this, 'add_modal_containers'));
        add_action('admin_init', array($this, 'handle_settings_form_submission'));
        // Add AJAX handlers
        add_action('wp_ajax_em_save_settings', array($this, 'ajax_save_settings'));
    }




    // Load only the dependencies needed for Starter version
    private function load_dependencies()
    {
        // Starter version only needs visitors list table
        require_once plugin_dir_path(__FILE__) . 'admin/class-event-monster-visitors-list-table.php';
        // Premium features removed: Tickets, Coupons, Payments list tables
    }


    public function display_visitors_page()
    {
        global $wpdb;

        // --- Prepare all data for the template ---
        $page_title = __('Visitors / Attendees', 'event-monster-premium');
        $page_slug = 'em-visitors-page';

        $columns = array(

            'number' => '#',
            'name' => __('Name', 'event-monster-premium'),
            'email' => __('Email', 'event-monster-premium'),
            'phone' => __('Phone', 'event-monster-premium'),
            'event' => __('Event', 'event-monster-premium'),
            'status' => __('Status', 'event-monster-premium'),
            'actions' => __('Controls', 'event-monster-premium'),
            'cb' => '',
        );

        // Fetch data...
        $attendees_table = $wpdb->prefix . 'em_attendees';
        $bookings_table = $wpdb->prefix . 'em_bookings';
        $table_data = $wpdb->get_results($wpdb->prepare(
            "SELECT a.id, a.first_name, a.last_name, a.email, a.phone, a.event_id, b.status
         FROM %i AS a LEFT JOIN %i AS b ON a.id = b.attendees_id ORDER BY a.id DESC",
            $attendees_table,
            $bookings_table
        ));
        foreach ($table_data as $key => $row) {
            $table_data[$key]->name = $row->first_name . ' ' . $row->last_name;
            $table_data[$key]->event = get_the_title($row->event_id);
        }

        $all_events = $wpdb->get_results("SELECT ID, post_title FROM `{$wpdb->prefix}posts` WHERE `post_type` = 'awl_event_monster' AND `post_status` = 'publish'");
        $row_actions_template = EM_FREE_PLUGIN_DIR . 'templates/admin/table-actions/visitors-actions.php';

        // --- Load the template ---
        // Now the $page_slug variable exists and will be passed to the template.
        echo '<div class="wrap" id="em-visitors-page-wrapper">';
        require(EM_FREE_PLUGIN_DIR . 'templates/admin/custom-table-template.php');
        echo '</div>';

        echo '<div class="modal" id="modal-view-visitor"></div>';
    }


    // Premium features (Payments, Coupons, Tickets) removed from Starter version
    // These are available in Event Monster Pro

    public function add_plugin_admin_menu()
    {
        // Event Monster Starter - Limited menu pages (no Tickets, Coupons, Payments)
        add_submenu_page('edit.php?post_type=awl_event_monster', __('Visitors', 'event-monster-starter'), __('Visitors / Attendee', 'event-monster-starter'), 'manage_options', 'em-visitors-page', array($this, 'display_visitors_page'));

        // Pro Menus (Upsells)
        $pro_badge = ' <span style="color: #46b450; font-weight: bold; font-size: 9px; margin-left: 4px; vertical-align: middle;">PRO</span>';
        
        add_submenu_page('edit.php?post_type=awl_event_monster', __('Tickets', 'event-monster-starter'), __('Tickets', 'event-monster-starter') . $pro_badge, 'manage_options', 'em-upgrade-page-tickets', array($this, 'display_upgrade_page'));
        add_submenu_page('edit.php?post_type=awl_event_monster', __('Coupons', 'event-monster-starter'), __('Coupons', 'event-monster-starter') . $pro_badge, 'manage_options', 'em-upgrade-page-coupons', array($this, 'display_upgrade_page'));
        add_submenu_page('edit.php?post_type=awl_event_monster', __('Payments', 'event-monster-starter'), __('Payments', 'event-monster-starter') . $pro_badge, 'manage_options', 'em-upgrade-page-payments', array($this, 'display_upgrade_page'));

        add_submenu_page('edit.php?post_type=awl_event_monster', __('Settings', 'event-monster-starter'), __('Settings', 'event-monster-starter'), 'manage_options', 'em-setting-page', array($this, 'display_settings_page'));

        add_submenu_page('edit.php?post_type=awl_event_monster', __('Demo Data', 'event-monster-starter'), __('Demo Data', 'event-monster-starter') . $pro_badge, 'manage_options', 'em-upgrade-page-demo', array($this, 'display_upgrade_page'));
        // Premium features page - shows upgrade prompt
        add_submenu_page('edit.php?post_type=awl_event_monster', __('Go Premium', 'event-monster-starter'), __('🚀 Go Premium', 'event-monster-starter'), 'manage_options', 'em-upgrade-page', array($this, 'display_upgrade_page'));
    }

    /**
     * Display upgrade to premium page
     */
    public function display_upgrade_page()
    {
        ?>
        <div class="wrap">
            <div style="max-width: 800px; margin: 40px auto; text-align: center; background: #fff; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <h1 style="font-size: 32px; color: #1e40af; margin-bottom: 20px;">🚀 Upgrade to Event Monster Pro</h1>
                <p style="font-size: 18px; color: #666; margin-bottom: 30px;">Unlock powerful features to supercharge your event management!</p>

                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; text-align: left; margin-bottom: 30px;">
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #3b82f6;">
                        <h3 style="margin: 0 0 10px; color: #1e40af;">💳 Payment Gateways</h3>
                        <p style="margin: 0; color: #666;">Accept payments via PayPal, Stripe, Razorpay & Square</p>
                    </div>
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #10b981;">
                        <h3 style="margin: 0 0 10px; color: #059669;">🎟️ Tickets & Coupons</h3>
                        <p style="margin: 0; color: #666;">Create multiple ticket types and discount coupons</p>
                    </div>
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #f59e0b;">
                        <h3 style="margin: 0 0 10px; color: #d97706;">📧 Email Templates</h3>
                        <p style="margin: 0; color: #666;">Custom email templates with SMTP support</p>
                    </div>
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #8b5cf6;">
                        <h3 style="margin: 0 0 10px; color: #7c3aed;">👥 Speakers & Sponsors</h3>
                        <p style="margin: 0; color: #666;">Showcase event speakers and sponsors</p>
                    </div>
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #ec4899;">
                        <h3 style="margin: 0 0 10px; color: #db2777;">🖼️ Event Gallery</h3>
                        <p style="margin: 0; color: #666;">Beautiful image galleries for your events</p>
                    </div>
                    <div style="padding: 20px; background: #f8fafc; border-radius: 8px; border-left: 4px solid #06b6d4;">
                        <h3 style="margin: 0 0 10px; color: #0891b2;">⏰ Reminder Emails</h3>
                        <p style="margin: 0; color: #666;">Automatic event reminder notifications</p>
                    </div>
                </div>

                <a href="https://awplife.com/wordpress-plugins/event-monster-wordpress-plugin/" target="_blank" style="display: inline-block; padding: 15px 40px; background: linear-gradient(135deg, #3b82f6, #1e40af); color: #fff; text-decoration: none; border-radius: 8px; font-size: 18px; font-weight: bold; transition: transform 0.2s;">
                    Get Event Monster Pro Now →
                </a>
                <p style="margin-top: 15px; color: #999; font-size: 14px;">30-day money-back guarantee • Lifetime updates • Priority support</p>
            </div>
        </div>
        <?php
    }
    // In includes/class-event-monster-admin.php

    /**
     * Display the modern settings page
     */
    public function display_settings_page()
    {
        // Include the modern settings template directly
        include EM_FREE_PLUGIN_DIR . 'templates/admin/settings.php';
    }


    /**
     * Adds the empty modal containers needed by JavaScript to the admin footer.
     * This is only loaded on the pages where they are needed.
     */
    public function add_modal_containers()
    {
        global $post;
        // Only add our containers on the event edit screen.
        if (is_object($post) && $post->post_type === 'awl_event_monster') {
            // This is the placeholder for the "Get Shortcode" modal - initially hidden
            echo '<div class="modal em-hidden" id="modal-shortcode-manager"></div>';
        }
    }

    /**
     * Handle the settings form submission
     */
    public function handle_settings_form_submission()
    {
        if (isset($_POST['em_setting_action']) && $_POST['em_setting_action'] === 'save_emsetting') {
            if (wp_verify_nonce($_POST['security'], 'em_save_nonce')) {
                // Get all the posted data and sanitize it
                $new_settings = array();

                // List of expected settings fields
                $fields = array(
                    'em_currency_code',
                    'em_currency_symbol',
                    'email_carrier',
                    'em_smtp_host',
                    'em_smtp_port',
                    'em_smtp_username',
                    'em_smtp_password',
                    'em_payment_email_id',
                    'em_payment_mode',
                    'em_paypal_client_id',
                    'em_paypal_secret_key',
                    'em_paypal_sandbox_client_id',
                    'em_paypal_sandbox_secret_key',
                    'em_notification_client',
                    'em_notification_admin',
                    'em_custom_css',
                    'em_form_heading_one',
                    'em_form_sucsess_msg_field',
                    'em_reminder',
                    'em_reminder_email',
                    'em_reminder_before_days',
                    'em_reminder_sub',
                    'em_reminder_msg',
                    'email_tem_head',
                    'logo_name',
                    'em_upload_image',
                    'cover_back_color',
                    'header_footer_back_color',
                    'header_footer_font_color',
                    'email_heading',
                    'email_greeting',
                    'email_confirmation_message',
                    'email_closing_message_1',
                    'email_closing_message_2',
                    'em_form_sub_heading',
                    'em_form_first_name_field',
                    'em_form_last_name_field',
                    'em_form_email_field',
                    'em_form_phone_field'
                );

                foreach ($fields as $field) {
                    if (isset($_POST[$field])) {
                        if ($field === 'em_custom_css' || $field === 'em_reminder_msg' || $field === 'instructions_type' || $field === 'email_confirmation_message' || $field === 'email_closing_message_1' || $field === 'email_closing_message_2') {
                            $new_settings[$field] = sanitize_textarea_field($_POST[$field]);
                        } elseif (in_array($field, array('em_smtp_from_email', 'em_payment_email_id', 'footer_email', 'em_reminder_email', 'em_form_email_field'))) {
                            $new_settings[$field] = sanitize_email($_POST[$field]);
                        } elseif (in_array($field, array('em_upload_image', 'footer_website'))) {
                            $new_settings[$field] = esc_url_raw($_POST[$field]);
                        } else {
                            $new_settings[$field] = sanitize_text_field($_POST[$field]);
                        }
                    }
                }

                // Handle checkboxes (they won't be in $_POST if unchecked)
                $checkbox_fields = array('em_notification_client', 'em_notification_admin');
                foreach ($checkbox_fields as $checkbox) {
                    $new_settings[$checkbox] = isset($_POST[$checkbox]) ? 'on' : 'off';
                }

                // Merge with existing options and save
                $existing_settings = get_option('awl_em_common_settings', array());
                $updated_settings = array_merge($existing_settings, $new_settings);
                update_option('awl_em_common_settings', $updated_settings);

                // Add success message
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-success is-dismissible"><p>' . __('Settings saved successfully!', 'event-monster') . '</p></div>';
                });
            }
        }
    }
    /**
     * AJAX handler for saving settings
     */
    public function ajax_save_settings()
    {
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('You do not have permission to save settings', 'event-monster')));
            return;
        }

        // Verify nonce
        if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'em_save_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed', 'event-monster')));
            return;
        }

        // Get all the posted data and sanitize it
        $new_settings = array();

        // Free version settings fields — no payment gateway keys
        $fields = array(
            'em_currency_code',
            'em_currency_symbol',
            'email_carrier',
            'em_smtp_host',
            'em_smtp_port',
            'em_smtp_username',
            'em_smtp_password',
            'em_smtp_encryption',
            'em_smtp_from_email',
            'em_smtp_from_name',
            'em_custom_css',
            'em_form_heading_one',
            'em_form_sucsess_msg_field',
            'em_form_sub_heading',
            'em_form_first_name_field',
            'em_form_last_name_field',
            'em_form_email_field',
            'em_form_phone_field',
            'email_tem_head',
            'logo_name',
            'em_upload_image',
            'cover_back_color',
            'header_footer_back_color',
            'header_footer_font_color',
            'email_heading',
            'email_greeting',
            'email_confirmation_message',
            'email_closing_message_1',
            'email_closing_message_2',
            'imp_instructions',
            'instructions_type',
            'footer_email',
            'footer_phone',
            'footer_website',
            'em_reminder_email',
            'em_reminder_before_days',
            'em_reminder_sub',
            'em_reminder_msg',
        );

        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                if ($field === 'em_custom_css' || $field === 'em_reminder_msg' || $field === 'instructions_type' || $field === 'email_confirmation_message' || $field === 'email_closing_message_1' || $field === 'email_closing_message_2') {
                    $new_settings[$field] = sanitize_textarea_field($_POST[$field]);
                } elseif (in_array($field, array('em_smtp_from_email', 'em_payment_email_id', 'footer_email', 'em_reminder_email'))) {
                    // Only sanitize actual email fields, not fields that just contain the word 'email'
                    $new_settings[$field] = sanitize_email($_POST[$field]);
                } elseif (in_array($field, array('em_upload_image', 'footer_website'))) {
                    // Sanitize URL fields
                    $new_settings[$field] = esc_url_raw($_POST[$field]);
                } else {
                    $new_settings[$field] = sanitize_text_field($_POST[$field]);
                }
            }
        }

        // Handle checkboxes (they won't be in $_POST if unchecked)
        $checkbox_fields = array('em_notification_client', 'em_notification_admin', 'em_reminder');
        foreach ($checkbox_fields as $checkbox) {
            $new_settings[$checkbox] = isset($_POST[$checkbox]) ? 'on' : 'off';
        }

        // Payment gateway toggles removed (Pro-only feature)

        // If no settings were processed, return an error
        if (empty($new_settings)) {
            wp_send_json_error(array('message' => __('No settings data received', 'event-monster')));
            return;
        }

        // Merge with existing options and save
        $existing_settings = get_option('awl_em_common_settings', array());
        $updated_settings = array_merge($existing_settings, $new_settings);

        // Try to save the settings
        $save_result = update_option('awl_em_common_settings', $updated_settings);

        // For update_option, false means no change was needed (data was the same)
        // So we should check if the data was actually saved
        $saved_settings = get_option('awl_em_common_settings', array());

        // Check if our new settings are in the saved data
        $settings_saved = true;
        foreach ($new_settings as $key => $value) {
            if (!isset($saved_settings[$key]) || $saved_settings[$key] !== $value) {
                $settings_saved = false;
                break;
            }
        }

        if ($settings_saved) {
            wp_send_json_success(array('message' => __('Settings saved successfully!', 'event-monster')));
        } else {
            wp_send_json_error(array('message' => __('Settings were not saved properly', 'event-monster')));
        }
    }
}
