<?php
/**
 * Event Monster Updater Class
 * Handles plugin updates, migrations, and version tracking
 * 
 * @package Event_Monster
 * @since 2.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class Event_Monster_Free_Updater {

    /**
     * Option key for storing the database version
     */
    const DB_VERSION_OPTION = 'em_starter_db_version';

    /**
     * Option key for tracking if welcome notice was dismissed
     */
    const WELCOME_DISMISSED_OPTION = 'em_starter_welcome_dismissed';

    /**
     * Initialize the updater
     */
    public static function init() {
        add_action('admin_init', array(__CLASS__, 'check_version'));
        add_action('admin_notices', array(__CLASS__, 'show_update_notices'));
        add_action('wp_ajax_em_dismiss_welcome_notice', array(__CLASS__, 'dismiss_welcome_notice'));
    }

    /**
     * Check version and run updates if necessary
     */
    public static function check_version() {
        $current_db_version = get_option(self::DB_VERSION_OPTION, '1.0.0');
        
        if (version_compare($current_db_version, EM_FREE_VERSION, '<')) {
            self::run_updates($current_db_version);
            update_option(self::DB_VERSION_OPTION, EM_FREE_VERSION);
            
            // Set transient to show update notice
            set_transient('em_starter_updated', true, 60 * 60); // 1 hour
        }
    }

    /**
     * Run all necessary updates based on version
     */
    private static function run_updates($from_version) {
        // Migration from 1.x to 2.0
        if (version_compare($from_version, '2.0.0', '<')) {
            self::migrate_to_2_0();
        }
    }

    /**
     * Migration for version 2.0.0
     * - Migrate old settings format if needed
     * - Force preset layout (custom layouts are Pro only)
     * - Clean up any Pro-only settings
     * - Convert old meta keys to new format
     */
    private static function migrate_to_2_0() {
        global $wpdb;

        // 1. Get all events and update their settings
        $events = get_posts(array(
            'post_type' => 'awl_event_monster',
            'posts_per_page' => -1,
            'post_status' => 'any',
            'fields' => 'ids'
        ));

        foreach ($events as $event_id) {
            $meta_key = 'awl_em_settings_' . $event_id;
            $settings = get_post_meta($event_id, $meta_key, true);

            if (is_array($settings)) {
                $updated = false;

                // Force preset layout (custom is Pro only)
                if (isset($settings['em_layout_preference']) && $settings['em_layout_preference'] === 'custom') {
                    $settings['em_layout_preference'] = 'default';
                    $updated = true;
                }

                // ========================================
                // MIGRATE OLD META KEYS TO NEW FORMAT
                // ========================================

                // 1. Venue address: em_address → em_venue
                if (!empty($settings['em_address']) && empty($settings['em_venue'])) {
                    $settings['em_venue'] = $settings['em_address'];
                    $updated = true;
                }

                // 2. Venue phone: em_venue_phone → em_venuee_phone (note the typo in new key)
                if (!empty($settings['em_venue_phone']) && empty($settings['em_venuee_phone'])) {
                    $settings['em_venuee_phone'] = $settings['em_venue_phone'];
                    $updated = true;
                }

                // 3. Venue email: em_venue_email → em_venuee_email
                if (!empty($settings['em_venue_email']) && empty($settings['em_venuee_email'])) {
                    $settings['em_venuee_email'] = $settings['em_venue_email'];
                    $updated = true;
                }

                // 4. Map enabled: em_map → em_map_enabled
                // Old version uses 'show'/'hide', new version uses 'yes'/'no'
                if (isset($settings['em_map']) && !isset($settings['em_map_enabled'])) {
                    $settings['em_map_enabled'] = ($settings['em_map'] === 'show') ? 'yes' : 'no';
                    $updated = true;
                }
                // If venue exists but map setting doesn't, enable map by default
                if (!empty($settings['em_venue']) && !isset($settings['em_map_enabled'])) {
                    $settings['em_map_enabled'] = 'yes';
                    $updated = true;
                }

                // 5. Social share: em_share_btn → em_social_links_enabled
                // Old version uses 'show', new version uses 'yes'
                if (isset($settings['em_share_btn']) && !isset($settings['em_social_links_enabled'])) {
                    $settings['em_social_links_enabled'] = ($settings['em_share_btn'] === 'show') ? 'yes' : 'no';
                    $settings['em_social_display_type'] = 'share_buttons';
                    $updated = true;
                }

                // 6. Countdown: em_countdown → em_countdown_enabled
                if (isset($settings['em_countdown']) && !isset($settings['em_countdown_enabled'])) {
                    $settings['em_countdown_enabled'] = ($settings['em_countdown'] === 'show') ? 'yes' : 'no';
                    $updated = true;
                }

                // 7. Organizer: em_organizer → em_show_organizer
                if (isset($settings['em_organizer']) && !isset($settings['em_show_organizer'])) {
                    $settings['em_show_organizer'] = ($settings['em_organizer'] === 'show') ? 'yes' : 'no';
                    $updated = true;
                }

                // 8. Registration: Enable free registration by default for migrated events
                // Old version may have had 'free' or 'on' value
                if (!isset($settings['em_accept_registration']) || empty($settings['em_accept_registration'])) {
                    $settings['em_accept_registration'] = 'yes';
                    $updated = true;
                }
                // Convert old 'on'/'off' values to 'yes'/'no'
                if (isset($settings['em_accept_registration']) && $settings['em_accept_registration'] === 'on') {
                    $settings['em_accept_registration'] = 'yes';
                    $updated = true;
                }

                // 9. Tickets: Enable free ticket by default (ID=1 is the default "Free Ticket")
                if (!isset($settings['em_tkt_select']) || empty($settings['em_tkt_select'])) {
                    $settings['em_tkt_select'] = array('1'); // Ticket ID 1 = Free Ticket
                    $updated = true;
                }

                // 10. Disable NEW features by default for migrated events
                // (Sponsors & Schedule - these didn't exist in old version)
                if (!isset($settings['em_show_event_sponsor'])) {
                    $settings['em_show_event_sponsor'] = 'no';
                    $updated = true;
                }
                if (!isset($settings['em_show_schedule'])) {
                    $settings['em_show_schedule'] = 'no';
                    $updated = true;
                }

                // 11. Banner image: Migrate old featured image settings
                // Old version used post thumbnail, keep using it
                if (!isset($settings['logo_upd']) || empty($settings['logo_upd'])) {
                    $settings['logo_upd'] = 'image';
                    // Try to get featured image
                    $featured_image = get_the_post_thumbnail_url($event_id, 'full');
                    if ($featured_image && empty($settings['em_upload_image'])) {
                        $settings['em_upload_image'] = $featured_image;
                    }
                    $updated = true;
                }

                // Save updated settings
                if ($updated) {
                    update_post_meta($event_id, $meta_key, $settings);
                }
            }
        }

        // 2. Clean up common settings (remove Pro-only options)
        $common_settings = get_option('awl_em_common_settings', array());
        
        if (is_array($common_settings)) {
            // Remove payment gateway settings (Pro only)
            $pro_only_keys = array(
                'em_stripe_secret_key',
                'em_stripe_publishable_key',
                'em_razorpay_key_id',
                'em_razorpay_key_secret',
                'em_square_application_id',
                'em_square_access_token',
            );
            
            foreach ($pro_only_keys as $key) {
                if (isset($common_settings[$key])) {
                    unset($common_settings[$key]);
                }
            }
            
            // Force PHP mail (SMTP is Pro only)
            $common_settings['email_carrier'] = 'php';
            
            update_option('awl_em_common_settings', $common_settings);
        }

        // Log the migration
        error_log('Event Monster Starter: Migrated to version 2.0.0');
    }

    /**
     * Show admin notices after update
     */
    public static function show_update_notices() {
        // Only show to admins
        if (!current_user_can('manage_options')) {
            return;
        }

        // Check if this is a fresh update
        if (get_transient('em_starter_updated') && !get_option(self::WELCOME_DISMISSED_OPTION)) {
            self::render_welcome_notice();
        }
    }

    /**
     * Render the welcome/update notice
     */
    private static function render_welcome_notice() {
        ?>
        <div class="notice notice-info is-dismissible em-welcome-notice" style="border-left-color: #667eea; padding: 15px 20px;">
            <div style="display: flex; align-items: flex-start; gap: 20px;">
                <div style="flex-shrink: 0;">
                    <span class="dashicons dashicons-megaphone" style="font-size: 40px; color: #667eea;"></span>
                </div>
                <div style="flex-grow: 1;">
                    <h2 style="margin: 0 0 10px 0; color: #1e3a5f;">
                        🎉 <?php _e('Welcome to Event Monster 2.0!', 'event-monster'); ?>
                    </h2>
                    <p style="font-size: 14px; margin-bottom: 15px;">
                        <?php _e('Thank you for updating! This major release includes a completely redesigned interface, improved performance, and new features.', 'event-monster'); ?>
                    </p>

                    <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
                        <div style="background: #f0f4f8; padding: 10px 15px; border-radius: 6px; flex: 1; min-width: 200px;">
                            <strong>✨ <?php _e("What's New:", 'event-monster'); ?></strong>
                            <ul style="margin: 5px 0 0 15px; font-size: 13px;">
                                <li><?php _e('Modern UI with Tailwind CSS', 'event-monster'); ?></li>
                                <li><?php _e('Enhanced FullCalendar integration', 'event-monster'); ?></li>
                                <li><?php _e('Improved event editor', 'event-monster'); ?></li>
                                <li><?php _e('Better mobile responsiveness', 'event-monster'); ?></li>
                            </ul>
                        </div>
                        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 6px; flex: 1; min-width: 200px;">
                            <strong>🚀 <?php _e('Upgrade to Pro', 'event-monster'); ?></strong>
                            <p style="margin: 5px 0; font-size: 13px; opacity: 0.95;">
                                <?php _e('Get payment gateways, unlimited speakers, custom layout builder, and more!', 'event-monster'); ?>
                            </p>
                            <a href="https://awplife.com/account/shop/" target="_blank"
                               style="display: inline-block; background: #ffd700; color: #1e3a5f; padding: 8px 16px; border-radius: 4px; text-decoration: none; font-weight: bold; font-size: 13px; margin-top: 5px;">
                                <?php _e('View Pro Features →', 'event-monster'); ?>
                            </a>
                        </div>
                    </div>

                    <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                        <a href="<?php echo admin_url('edit.php?post_type=awl_event_monster'); ?>" class="button button-primary">
                            <?php _e('View Your Events', 'event-monster'); ?>
                        </a>
                        <a href="https://awplife.com/event-monster-2-changelog/" target="_blank" class="button">
                            <?php _e('View Changelog', 'event-monster'); ?>
                        </a>
                        <a href="#" class="button em-dismiss-welcome" data-nonce="<?php echo wp_create_nonce('em_dismiss_welcome'); ?>">
                            <?php _e('Dismiss', 'event-monster'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            $('.em-dismiss-welcome, .em-welcome-notice .notice-dismiss').on('click', function(e) {
                var nonce = $('.em-dismiss-welcome').data('nonce');
                $.post(ajaxurl, {
                    action: 'em_dismiss_welcome_notice',
                    nonce: nonce
                });
            });
        });
        </script>
        <?php
    }

    /**
     * AJAX handler to dismiss welcome notice
     */
    public static function dismiss_welcome_notice() {
        if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'em_dismiss_welcome')) {
            update_option(self::WELCOME_DISMISSED_OPTION, true);
            delete_transient('em_starter_updated');
        }
        wp_die();
    }

    /**
     * Get upgrade URL
     */
    public static function get_upgrade_url() {
        return 'https://awplife.com/account/shop/';
    }

    /**
     * Check if this is a fresh install (not an upgrade)
     */
    public static function is_fresh_install() {
        return !get_option(self::DB_VERSION_OPTION);
    }
}

// Initialize the updater
Event_Monster_Free_Updater::init();

