<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class PC_Membership_Public {

    public static function init() {
        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );

        add_shortcode( 'pc_membership_checkout', array( __CLASS__, 'checkout_shortcode' ) );
        add_shortcode( 'pc_membership_login', array( __CLASS__, 'login_shortcode' ) );
        add_shortcode( 'pc_membership_register', array( __CLASS__, 'register_shortcode' ) );
        add_shortcode( 'pc_membership_account', array( __CLASS__, 'account_shortcode' ) );
        add_shortcode( 'pc_membership_success', array( __CLASS__, 'success_shortcode' ) );
        add_shortcode( 'pc_membership_cancel', array( __CLASS__, 'cancel_shortcode' ) );
        add_shortcode( 'pc_membership_pricing', array( __CLASS__, 'pricing_shortcode' ) );

        add_action( 'wp_ajax_pc_membership_create_checkout', array( __CLASS__, 'ajax_create_checkout' ) );
        add_action( 'wp_ajax_nopriv_pc_membership_create_checkout', array( __CLASS__, 'ajax_create_checkout' ) );

        add_action( 'wp_ajax_pc_membership_cancel_subscription', array( __CLASS__, 'ajax_cancel_subscription' ) );
        add_action( 'wp_ajax_nopriv_pc_membership_cancel_subscription', array( __CLASS__, 'ajax_cancel_subscription' ) );

        add_action( 'wp_ajax_pc_membership_update_payment_method', array( __CLASS__, 'ajax_update_payment_method' ) );
        add_action( 'wp_ajax_nopriv_pc_membership_update_payment_method', array( __CLASS__, 'ajax_update_payment_method' ) );

        add_action( 'wp_ajax_pc_membership_login', array( __CLASS__, 'ajax_login' ) );
        add_action( 'wp_ajax_nopriv_pc_membership_login', array( __CLASS__, 'ajax_login' ) );

        add_action( 'wp_ajax_pc_membership_register', array( __CLASS__, 'ajax_register' ) );
        add_action( 'wp_ajax_nopriv_pc_membership_register', array( __CLASS__, 'ajax_register' ) );

        add_action( 'wp_ajax_pc_membership_update_profile', array( __CLASS__, 'ajax_update_profile' ) );

        add_action( 'template_redirect', array( __CLASS__, 'handle_stripe_return' ) );
    }

    public static function enqueue_assets() {
        if ( ! self::is_membership_page() ) {
            return;
        }

        wp_enqueue_style( 'pc-membership-public-style', PC_MEMBERSHIP_PLUGIN_URL . 'public/css/public-style.css', array(), PC_MEMBERSHIP_VERSION );
        wp_enqueue_script( 'pc-membership-stripe-js', 'https://js.stripe.com/v3/', array(), null, true );
        wp_enqueue_script( 'pc-membership-public-script', PC_MEMBERSHIP_PLUGIN_URL . 'public/js/public-script.js', array( 'jquery', 'pc-membership-stripe-js' ), PC_MEMBERSHIP_VERSION, true );

        $options = get_option( 'pc_membership_options' );
        $publishable_key = '';

        if ( ! empty( $options ) ) {
            $mode = isset( $options['mode'] ) ? $options['mode'] : 'test';
            $publishable_key = isset( $options[ $mode . '_publishable_key' ] ) ? $options[ $mode . '_publishable_key' ] : '';
        }

        wp_localize_script( 'pc-membership-public-script', 'pcMembership', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'pc_membership_nonce' ),
            'stripe_key' => $publishable_key,
            'i18n'     => array(
                'processing'   => __( 'Processing...', 'pc-membership-abc123' ),
                'selectPlan'   => __( 'Please select a plan', 'pc-membership-abc123' ),
                'error'        => __( 'An error occurred. Please try again.', 'pc-membership-abc123' ),
                'success'      => __( 'Success!', 'pc-membership-abc123' ),
                'cancel'       => __( 'Cancel Subscription', 'pc-membership-abc123' ),
                'confirmCancel'=> __( 'Are you sure you want to cancel your subscription?', 'pc-membership-abc123' ),
            ),
        ) );
    }

    private static function is_membership_page() {
        if ( ! is_singular() && ! is_page() ) {
            return false;
        }

        $options = get_option( 'pc_membership_options', array() );
        $page_ids = array(
            isset( $options['checkout_page_id'] ) ? $options['checkout_page_id'] : 0,
            isset( $options['login_page_id'] ) ? $options['login_page_id'] : 0,
            isset( $options['register_page_id'] ) ? $options['register_page_id'] : 0,
            isset( $options['account_page_id'] ) ? $options['account_page_id'] : 0,
            isset( $options['success_page_id'] ) ? $options['success_page_id'] : 0,
            isset( $options['cancel_page_id'] ) ? $options['cancel_page_id'] : 0,
        );

        return in_array( get_the_ID(), array_filter( $page_ids ) );
    }

    public static function checkout_shortcode( $atts ) {
        ob_start();
        self::render_checkout_page();
        return ob_get_clean();
    }

    public static function render_checkout_page() {
        global $wpdb;

        $plans = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}pc_membership_plans ORDER BY price ASC" );

        if ( empty( $plans ) ) {
            echo '<div class="pc-membership-message pc-membership-message-info">';
            esc_html_e( 'No membership plans available at this time.', 'pc-membership-abc123' );
            echo '</div>';
            return;
        }

        $options = get_option( 'pc_membership_options' );
        $mode = isset( $options['mode'] ) ? $options['mode'] : 'test';

        echo '<div class="pc-membership-checkout-wrapper">';
        echo '<div class="pc-membership-pricing-cards">';

        foreach ( $plans as $plan ) {
            $benefits = array_filter( array_map( 'trim', explode( "\n", $plan->benefits ) ) );
            $billing_label = $plan->is_subscription
                ? sprintf( '%s / %s', pc_membership_format_price( $plan->price ), $plan->billing_interval )
                : pc_membership_format_price( $plan->price );

            echo '<div class="pc-membership-pricing-card" data-plan-id="' . esc_attr( $plan->id ) . '">';
            echo '<div class="pc-membership-pricing-header">';
            echo '<h3 class="pc-membership-plan-name">' . esc_html( $plan->name ) . '</h3>';
            echo '<div class="pc-membership-plan-price">';
            echo '<span class="pc-membership-price-amount">' . esc_html( pc_membership_format_price( $plan->price ) ) . '</span>';
            if ( $plan->is_subscription ) {
                echo '<span class="pc-membership-price-interval"> / ' . esc_html( $plan->billing_interval ) . '</span>';
            }
            echo '</div>';

            if ( $plan->trial_days > 0 ) {
                echo '<div class="pc-membership-trial-badge">';
                printf( esc_html__( '%d Day Free Trial', 'pc-membership-abc123' ), $plan->trial_days );
                echo '</div>';
            }

            echo '</div>';

            if ( $plan->description ) {
                echo '<div class="pc-membership-plan-description">' . wp_kses_post( $plan->description ) . '</div>';
            }

            if ( ! empty( $benefits ) ) {
                echo '<ul class="pc-membership-plan-benefits">';
                foreach ( $benefits as $benefit ) {
                    echo '<li><span class="dashicons dashicons-yes-alt"></span>' . esc_html( $benefit ) . '</li>';
                }
                echo '</ul>';
            }

            echo '<button class="pc-membership-select-plan-btn button button-primary" data-plan-id="' . esc_attr( $plan->id ) . '">';
            esc_html_e( 'Select Plan', 'pc-membership-abc123' );
            echo '</button>';
            echo '</div>';
        }

        echo '</div>';

        echo '<div class="pc-membership-checkout-form-wrapper" style="display: none;">';
        echo '<div id="pc-membership-checkout-form-container"></div>';
        echo '</div>';
        echo '</div>';
    }

    public static function login_shortcode( $atts ) {
        if ( is_user_logged_in() ) {
            $account_page = self::get_page_url( 'account' );
            if ( $account_page ) {
                wp_redirect( $account_page );
                exit;
            }
        }

        ob_start();
        self::render_login_form();
        return ob_get_clean();
    }

    public static function render_login_form() {
        $options = get_option( 'pc_membership_options' );
        $register_page = isset( $options['register_page_id'] ) ? get_permalink( $options['register_page_id'] ) : false;
        $account_page = self::get_page_url( 'account' );
        ?>
        <div class="pc-membership-login-wrapper">
            <div class="pc-membership-login-form-container">
                <h2><?php esc_html_e( 'Member Login', 'pc-membership-abc123' ); ?></h2>

                <form id="pc-membership-login-form" method="post">
                    <?php wp_nonce_field( 'pc_membership_login', 'pc_membership_login_nonce' ); ?>

                    <div class="pc-membership-form-group">
                        <label for="user_login"><?php esc_html_e( 'Username or Email', 'pc-membership-abc123' ); ?></label>
                        <input type="text" name="user_login" id="user_login" required class="regular-text">
                    </div>

                    <div class="pc-membership-form-group">
                        <label for="user_password"><?php esc_html_e( 'Password', 'pc-membership-abc123' ); ?></label>
                        <input type="password" name="user_password" id="user_password" required class="regular-text">
                    </div>

                    <div class="pc-membership-form-group">
                        <label class="pc-membership-remember-me">
                            <input type="checkbox" name="rememberme" value="forever">
                            <?php esc_html_e( 'Remember me', 'pc-membership-abc123' ); ?>
                        </label>
                    </div>

                    <button type="submit" class="button button-primary pc-membership-login-btn">
                        <?php esc_html_e( 'Log In', 'pc-membership-abc123' ); ?>
                    </button>

                    <div class="pc-membership-login-links">
                        <?php if ( $register_page ) : ?>
                            <a href="<?php echo esc_url( $register_page ); ?>">
                                <?php esc_html_e( 'Create an account', 'pc-membership-abc123' ); ?>
                            </a>
                        <?php endif; ?>
                        <a href="<?php echo esc_url( wp_lostpassword_url() ); ?>">
                            <?php esc_html_e( 'Forgot password?', 'pc-membership-abc123' ); ?>
                        </a>
                    </div>
                </form>

                <div id="pc-membership-login-message"></div>
            </div>
        </div>
        <?php
    }

    public static function register_shortcode( $atts ) {
        if ( is_user_logged_in() ) {
            $account_page = self::get_page_url( 'account' );
            if ( $account_page ) {
                wp_redirect( $account_page );
                exit;
            }
        }

        ob_start();
        self::render_registration_form();
        return ob_get_clean();
    }

    public static function render_registration_form() {
        $options = get_option( 'pc_membership_options' );
        $login_page = isset( $options['login_page_id'] ) ? get_permalink( $options['login_page_id'] ) : false;
        ?>
        <div class="pc-membership-register-wrapper">
            <div class="pc-membership-register-form-container">
                <h2><?php esc_html_e( 'Create Account', 'pc-membership-abc123' ); ?></h2>

                <form id="pc-membership-register-form" method="post">
                    <?php wp_nonce_field( 'pc_membership_register', 'pc_membership_register_nonce' ); ?>

                    <div class="pc-membership-form-group">
                        <label for="user_login"><?php esc_html_e( 'Username', 'pc-membership-abc123' ); ?> *</label>
                        <input type="text" name="user_login" id="user_login" required class="regular-text" minlength="4">
                    </div>

                    <div class="pc-membership-form-group">
                        <label for="user_email"><?php esc_html_e( 'Email', 'pc-membership-abc123' ); ?> *</label>
                        <input type="email" name="user_email" id="user_email" required class="regular-text">
                    </div>

                    <div class="pc-membership-form-group">
                        <label for="user_password"><?php esc_html_e( 'Password', 'pc-membership-abc123' ); ?> *</label>
                        <input type="password" name="user_password" id="user_password" required class="regular-text" minlength="8">
                    </div>

                    <div class="pc-membership-form-group">
                        <label for="user_password_confirm"><?php esc_html_e( 'Confirm Password', 'pc-membership-abc123' ); ?> *</label>
                        <input type="password" name="user_password_confirm" id="user_password_confirm" required class="regular-text">
                    </div>

                    <button type="submit" class="button button-primary pc-membership-register-btn">
                        <?php esc_html_e( 'Create Account', 'pc-membership-abc123' ); ?>
                    </button>

                    <div class="pc-membership-login-links">
                        <?php if ( $login_page ) : ?>
                            <a href="<?php echo esc_url( $login_page ); ?>">
                                <?php esc_html_e( 'Already have an account? Log in', 'pc-membership-abc123' ); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </form>

                <div id="pc-membership-register-message"></div>
            </div>
        </div>
        <?php
    }

    public static function account_shortcode( $atts ) {
        if ( ! is_user_logged_in() ) {
            $login_page = self::get_page_url( 'login' );
            if ( $login_page ) {
                wp_redirect( $login_page );
                exit;
            }
        }

        ob_start();
        self::render_account_page();
        return ob_get_clean();
    }

    public static function render_account_page() {
        $user = wp_get_current_user();
        $subscription = self::get_user_subscription( $user->ID );
        ?>
        <div class="pc-membership-account-wrapper">
            <div class="pc-membership-account-header">
                <h2><?php printf( esc_html__( 'Welcome, %s', 'pc-membership-abc123' ), esc_html( $user->display_name ) ); ?></h2>
                <a href="<?php echo esc_url( wp_logout_url( self::get_page_url( 'login' ) ) ); ?>" class="button">
                    <?php esc_html_e( 'Log Out', 'pc-membership-abc123' ); ?>
                </a>
            </div>

            <?php if ( $subscription ) : ?>
                <?php
                global $wpdb;
                $plan = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pc_membership_plans WHERE id = %d", $subscription->plan_id ) );
                ?>

                <div class="pc-membership-subscription-details">
                    <h3><?php esc_html_e( 'Your Subscription', 'pc-membership-abc123' ); ?></h3>

                    <div class="pc-membership-subscription-info">
                        <div class="pc-membership-subscription-row">
                            <span class="pc-membership-label"><?php esc_html_e( 'Plan', 'pc-membership-abc123' ); ?>:</span>
                            <span class="pc-membership-value"><?php echo $plan ? esc_html( $plan->name ) : esc_html__( 'Unknown', 'pc-membership-abc123' ); ?></span>
                        </div>

                        <div class="pc-membership-subscription-row">
                            <span class="pc-membership-label"><?php esc_html_e( 'Status', 'pc-membership-abc123' ); ?>:</span>
                            <span class="pc-membership-value pc-membership-status-<?php echo esc_attr( $subscription->status ); ?>">
                                <?php echo esc_html( ucfirst( $subscription->status ) ); ?>
                            </span>
                        </div>

                        <div class="pc-membership-subscription-row">
                            <span class="pc-membership-label"><?php esc_html_e( 'Started', 'pc-membership-abc123' ); ?>:</span>
                            <span class="pc-membership-value"><?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $subscription->started_at ) ) ); ?></span>
                        </div>

                        <?php if ( $subscription->expires_at ) : ?>
                            <div class="pc-membership-subscription-row">
                                <span class="pc-membership-label"><?php esc_html_e( 'Expires', 'pc-membership-abc123' ); ?>:</span>
                                <span class="pc-membership-value"><?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $subscription->expires_at ) ) ); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if ( $subscription->status === 'active' && $plan && $plan->is_subscription ) : ?>
                        <div class="pc-membership-subscription-actions">
                            <button type="button" id="pc-membership-cancel-subscription" class="button button-secondary" data-subscription-id="<?php echo esc_attr( $subscription->id ); ?>">
                                <?php esc_html_e( 'Cancel Subscription', 'pc-membership-abc123' ); ?>
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            <?php else : ?>
                <div class="pc-membership-no-subscription">
                    <p><?php esc_html_e( 'You don\'t have an active membership subscription.', 'pc-membership-abc123' ); ?></p>
                    <a href="<?php echo esc_url( self::get_page_url( 'checkout' ) ); ?>" class="button button-primary">
                        <?php esc_html_e( 'Choose a Plan', 'pc-membership-abc123' ); ?>
                    </a>
                </div>
            <?php endif; ?>

            <div class="pc-membership-account-section">
                <h3><?php esc_html_e( 'Profile Information', 'pc-membership-abc123' ); ?></h3>
                <form id="pc-membership-profile-form" method="post">
                    <?php wp_nonce_field( 'pc_membership_update_profile', 'pc_membership_profile_nonce' ); ?>

                    <div class="pc-membership-form-group">
                        <label for="display_name"><?php esc_html_e( 'Display Name', 'pc-membership-abc123' ); ?></label>
                        <input type="text" name="display_name" id="display_name" value="<?php echo esc_attr( $user->display_name ); ?>" class="regular-text">
                    </div>

                    <div class="pc-membership-form-group">
                        <label for="user_email"><?php esc_html_e( 'Email', 'pc-membership-abc123' ); ?></label>
                        <input type="email" name="user_email" id="user_email" value="<?php echo esc_attr( $user->user_email ); ?>" class="regular-text" readonly>
                        <p class="description"><?php esc_html_e( 'Email cannot be changed.', 'pc-membership-abc123' ); ?></p>
                    </div>

                    <button type="submit" class="button button-primary">
                        <?php esc_html_e( 'Update Profile', 'pc-membership-abc123' ); ?>
                    </button>
                </form>
            </div>
        </div>
        <?php
    }

    public static function success_shortcode( $atts ) {
        ob_start();
        ?>
        <div class="pc-membership-success-wrapper">
            <div class="pc-membership-success-message">
                <div class="pc-membership-success-icon">
                    <span class="dashicons dashicons-yes-alt" style="font-size: 64px; height: 64px; width: 64px; color: #46b450;"></span>
                </div>
                <h2><?php esc_html_e( 'Payment Successful!', 'pc-membership-abc123' ); ?></h2>
                <p><?php esc_html_e( 'Thank you for your purchase. Your membership is now active.', 'pc-membership-abc123' ); ?></p>
                <a href="<?php echo esc_url( self::get_page_url( 'account' ) ); ?>" class="button button-primary">
                    <?php esc_html_e( 'Go to My Account', 'pc-membership-abc123' ); ?>
                </a>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    public static function cancel_shortcode( $atts ) {
        ob_start();
        ?>
        <div class="pc-membership-cancel-wrapper">
            <div class="pc-membership-cancel-message">
                <div class="pc-membership-cancel-icon">
                    <span class="dashicons dashicons-dismiss" style="font-size: 64px; height: 64px; width: 64px; color: #dc3232;"></span>
                </div>
                <h2><?php esc_html_e( 'Payment Cancelled', 'pc-membership-abc123' ); ?></h2>
                <p><?php esc_html_e( 'Your payment was cancelled. No charges were made.', 'pc-membership-abc123' ); ?></p>
                <a href="<?php echo esc_url( self::get_page_url( 'checkout' ) ); ?>" class="button button-primary">
                    <?php esc_html_e( 'Try Again', 'pc-membership-abc123' ); ?>
                </a>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    public static function pricing_shortcode( $atts ) {
        ob_start();
        self::render_checkout_page();
        return ob_get_clean();
    }

    private static function get_page_url( $page_type ) {
        $options = get_option( 'pc_membership_options' );
        $page_id = isset( $options[ $page_type . '_page_id' ] ) ? absint( $options[ $page_type . '_page_id' ] ) : 0;
        return $page_id ? get_permalink( $page_id ) : home_url();
    }

    private static function get_user_subscription( $user_id ) {
        global $wpdb;
        return $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}pc_membership_subscriptions WHERE user_id = %d AND status = 'active' ORDER BY id DESC LIMIT 1",
            $user_id
        ) );
    }

    public static function ajax_create_checkout() {
        check_ajax_referer( 'pc_membership_nonce', 'nonce' );

        $plan_id = isset( $_POST['plan_id'] ) ? absint( $_POST['plan_id'] ) : 0;

        if ( ! $plan_id ) {
            wp_send_json_error( __( 'Invalid plan', 'pc-membership-abc123' ) );
        }

        if ( ! class_exists( 'PC_Membership_Stripe' ) ) {
            require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/stripe-handler.php';
        }

        $result = PC_Membership_Stripe::create_checkout_session( $plan_id );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result->get_error_message() );
        }

        wp_send_json_success( array( 'url' => $result->url ) );
    }

    public static function ajax_cancel_subscription() {
        check_ajax_referer( 'pc_membership_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( __( 'Must be logged in', 'pc-membership-abc123' ) );
        }

        $subscription_id = isset( $_POST['subscription_id'] ) ? absint( $_POST['subscription_id'] ) : 0;

        if ( ! $subscription_id ) {
            wp_send_json_error( __( 'Invalid subscription', 'pc-membership-abc123' ) );
        }

        global $wpdb;
        $subscription = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pc_membership_subscriptions WHERE id = %d AND user_id = %d", $subscription_id, get_current_user_id() ) );

        if ( ! $subscription ) {
            wp_send_json_error( __( 'Subscription not found', 'pc-membership-abc123' ) );
        }

        if ( ! class_exists( 'PC_Membership_Stripe' ) ) {
            require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/stripe-handler.php';
        }

        $result = PC_Membership_Stripe::cancel_subscription( $subscription->stripe_subscription_id );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result->get_error_message() );
        }

        $wpdb->update( $wpdb->prefix . 'pc_membership_subscriptions', array( 'status' => 'cancelled' ), array( 'id' => $subscription_id ) );

        wp_send_json_success();
    }

    public static function ajax_update_payment_method() {
        check_ajax_referer( 'pc_membership_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( __( 'Must be logged in', 'pc-membership-abc123' ) );
        }

        if ( ! class_exists( 'PC_Membership_Stripe' ) ) {
            require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/stripe-handler.php';
        }

        $result = PC_Membership_Stripe::create_portal_session();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result->get_error_message() );
        }

        wp_send_json_success( array( 'url' => $result->url ) );
    }

    public static function ajax_login() {
        check_ajax_referer( 'pc_membership_login', 'nonce' );

        $user_login = isset( $_POST['user_login'] ) ? sanitize_text_field( wp_unslash( $_POST['user_login'] ) ) : '';
        $user_password = isset( $_POST['user_password'] ) ? $_POST['user_password'] : '';

        if ( empty( $user_login ) || empty( $user_password ) ) {
            wp_send_json_error( __( 'Please enter username and password', 'pc-membership-abc123' ) );
        }

        $user = wp_authenticate_username_password( null, $user_login, $user_password );

        if ( is_wp_error( $user ) ) {
            wp_send_json_error( $user->get_error_message() );
        }

        wp_set_auth_cookie( $user->ID, true );

        $redirect_url = self::get_page_url( 'account' );

        wp_send_json_success( array( 'redirect' => $redirect_url ) );
    }

    public static function ajax_register() {
        check_ajax_referer( 'pc_membership_register', 'nonce' );

        $user_login = isset( $_POST['user_login'] ) ? sanitize_text_field( wp_unslash( $_POST['user_login'] ) ) : '';
        $user_email = isset( $_POST['user_email'] ) ? sanitize_email( wp_unslash( $_POST['user_email'] ) ) : '';
        $user_password = isset( $_POST['user_password'] ) ? $_POST['user_password'] : '';
        $user_password_confirm = isset( $_POST['user_password_confirm'] ) ? $_POST['user_password_confirm'] : '';

        if ( empty( $user_login ) || empty( $user_email ) || empty( $user_password ) ) {
            wp_send_json_error( __( 'All fields are required', 'pc-membership-abc123' ) );
        }

        if ( ! is_email( $user_email ) ) {
            wp_send_json_error( __( 'Invalid email address', 'pc-membership-abc123' ) );
        }

        if ( $user_password !== $user_password_confirm ) {
            wp_send_json_error( __( 'Passwords do not match', 'pc-membership-abc123' ) );
        }

        if ( strlen( $user_password ) < 8 ) {
            wp_send_json_error( __( 'Password must be at least 8 characters', 'pc-membership-abc123' ) );
        }

        if ( username_exists( $user_login ) ) {
            wp_send_json_error( __( 'Username already exists', 'pc-membership-abc123' ) );
        }

        if ( email_exists( $user_email ) ) {
            wp_send_json_error( __( 'Email already registered', 'pc-membership-abc123' ) );
        }

        $user_id = wp_create_user( $user_login, $user_password, $user_email );

        if ( is_wp_error( $user_id ) ) {
            wp_send_json_error( $user_id->get_error_message() );
        }

        wp_update_user( array(
            'ID' => $user_id,
            'display_name' => $user_login,
        ) );

        $user = get_userdata( $user_id );
        $user->set_role( 'subscriber' );

        wp_set_auth_cookie( $user_id, true );

        do_action( 'pc_membership_user_registered', $user_id, $user_login, $user_email );

        $redirect_url = self::get_page_url( 'account' );

        wp_send_json_success( array( 'redirect' => $redirect_url ) );
    }

    public static function ajax_update_profile() {
        check_ajax_referer( 'pc_membership_update_profile', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error( __( 'Must be logged in', 'pc-membership-abc123' ) );
        }

        $display_name = isset( $_POST['display_name'] ) ? sanitize_text_field( wp_unslash( $_POST['display_name'] ) ) : '';

        if ( empty( $display_name ) ) {
            wp_send_json_error( __( 'Display name is required', 'pc-membership-abc123' ) );
        }

        $result = wp_update_user( array(
            'ID' => get_current_user_id(),
            'display_name' => $display_name,
        ) );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result->get_error_message() );
        }

        wp_send_json_success();
    }

    public static function handle_stripe_return() {
        if ( ! isset( $_GET['session_id'] ) ) {
            return;
        }

        $session_id = sanitize_text_field( wp_unslash( $_GET['session_id'] ) );

        if ( ! class_exists( 'PC_Membership_Stripe' ) ) {
            require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/stripe-handler.php';
        }

        $session = PC_Membership_Stripe::retrieve_session( $session_id );

        if ( is_wp_error( $session ) ) {
            return;
        }

        $success_page = self::get_page_url( 'success' );
        if ( $success_page ) {
            wp_redirect( $success_page );
            exit;
        }
    }
}
