<?php
/**
 * Custom OTP Login for WooCommerce
 * Description: Replaces WooCommerce login/register with phone OTP verification for Iranian numbers
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Define theme constants
define('CUSTOM_OTP_PATH', get_template_directory() . '/');
define('CUSTOM_OTP_URL', get_template_directory_uri() . '/');

class Custom_OTP_Login {

    private $sms_provider;
    private $username;
    private $senderNumber;
    private $api_key;
    private $template;
    private $otp_enabled;

    public function __construct() {
        $this->sms_provider = get_option(TEXT_DOMAIN . '_sms_provider', 'kavenegar');
        $this->username = get_option(TEXT_DOMAIN . '_sms_username', '');
        $this->senderNumber = get_option(TEXT_DOMAIN . '_sms_sender_number', '');
        $this->api_key = get_option(TEXT_DOMAIN . '_sms_api_key', '');
        $this->template = get_option(TEXT_DOMAIN . '_sms_template', '');
        $this->otp_enabled = get_option(TEXT_DOMAIN . '_otp', 'false') === 'true';

        if ($this->otp_enabled) {
            // Enqueue scripts and styles
            add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));

            // Completely replace WooCommerce login and registration forms
            add_action('init', array($this, 'remove_default_forms'));

            // Also replace in My Account page
            add_action('woocommerce_before_customer_login_form', array($this, 'replace_my_account_form'));

            // Add aggressive approach to remove default form
            add_action('template_redirect', 'remove_default_woocommerce_login_form');

            // for checkout
//        add_action('woocommerce_checkout_before_customer_details', array($this, 'replace_checkout_login_form'));
            add_action('woocommerce_before_checkout_form', array($this, 'replace_checkout_login_form'), 5);
        }

        // AJAX handlers (always available for AJAX)
        add_action('wp_ajax_nopriv_send_otp', array($this, 'send_otp'));
        add_action('wp_ajax_send_otp', array($this, 'send_otp'));
        add_action('wp_ajax_nopriv_verify_otp', array($this, 'verify_otp'));
        add_action('wp_ajax_verify_otp', array($this, 'verify_otp'));

        // Create user meta for phone number
        add_action('show_user_profile', array($this, 'add_phone_field'));
        add_action('edit_user_profile', array($this, 'add_phone_field'));
        add_action('personal_options_update', array($this, 'save_phone_field'));
        add_action('edit_user_profile_update', array($this, 'save_phone_field'));


    }

    /**
     * Replace the checkout login form with OTP form
     */
    public function replace_checkout_login_form() {
        if (!is_user_logged_in()) {
            // Check if OTP is enabled, if not, let default form show
            if (!$this->otp_enabled) {
                return; // Don't do anything, let WooCommerce show default form
            }

            // Check if WooCommerce checkout login is enabled
            if (get_option('woocommerce_enable_checkout_login_reminder') !== 'yes') {
                return; // Don't show any login form if WooCommerce setting is disabled
            }

            // Remove the default checkout login form only if OTP is enabled
            remove_action('woocommerce_before_checkout_form', 'woocommerce_checkout_login_form', 10);

            // Display our custom OTP form with toggle
            ?>
            <div class="woocommerce-form-login-toggle">
                <div class="woocommerce-info">
                    <?php _e('Do you want to sign in to your account?', TEXT_DOMAIN); ?>
                    <a href="#" class="showlogin"><?php _e('Click here', TEXT_DOMAIN); ?></a>
                </div>
            </div>
            <form class="woocommerce-form woocommerce-form-login login" method="post" style="display:none;">
                <div class="custom-checkout-otp-container">
                    <div class="otp-form-container jiawaz-otp-form checkout-otp-form">
                        <?php echo $this->get_otp_form('checkout'); ?>
                    </div>
                </div>
            </form>
            <?php
        }
    }
    /**
     * Display custom OTP form on checkout page
     */
    public function display_checkout_otp_form() {
        if (!is_user_logged_in()) {
            ?>
            <div class="woocommerce-form-login-toggle">
                <div class="woocommerce-info">
                    <?php _e('Login with your mobile number', TEXT_DOMAIN); ?>
                </div>
            </div>
            <div class="custom-checkout-otp-container">
                <div class="otp-form-container jiawaz-otp-form checkout-otp-form">
                    <?php echo $this->get_otp_form('checkout'); ?>
                </div>
            </div>
            <?php
        }
    }

    /**
     * Enqueue necessary scripts and styles
     */
    public function enqueue_scripts() {
        if (is_account_page() || is_checkout()) {
            wp_enqueue_script('custom-otp-script', get_template_directory_uri() . '/js/otp.js', array('jquery'), '1.0.0', true);
            wp_localize_script('custom-otp-script', 'custom_otp_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('custom-otp-nonce')
            ));
        }
    }

    /**
     * Remove the default WooCommerce login and registration forms
     */
    public function remove_default_forms() {
        remove_action('woocommerce_login_form', 'woocommerce_form_field', 10);
        remove_action('woocommerce_register_form', 'woocommerce_form_field', 10);
        add_filter('woocommerce_login_credentials', array($this, 'filter_login_credentials'), 10, 3);
        add_filter('woocommerce_login_form_fields', array($this, 'filter_form_fields'));
        add_filter('woocommerce_register_form_fields', array($this, 'filter_form_fields'));
    }

    /**
     * Filter the login credentials
     */
    public function filter_login_credentials($creds, $username, $password) {
        return array();
    }

    /**
     * Filter the form fields to remove the default ones
     */
    public function filter_form_fields($fields) {
        return array();
    }

    /**
     * Replace the entire login/register form container on My Account page
     */
    public function replace_my_account_form() {
        if (!is_user_logged_in()) {
            remove_action('woocommerce_customer_login_form', 'woocommerce_login_form');
            remove_action('woocommerce_customer_login_form', 'woocommerce_register_form');
            ?>
            <div class="custom-login-container u-columns col2-set" id="customer_login">
                <div class="otp-form-container jiawaz-otp-form">
                    <?php echo $this->get_otp_form('login'); ?>
                </div>
            </div>
            <?php
            return false;
        }
    }

    /**
     * Get the custom OTP form HTML
     */
    private function get_otp_form($form_type) {
        $firstNameInput = get_option(TEXT_DOMAIN . '_otp_form_first_name', 'false') === 'true';
        $lastNameInput = get_option(TEXT_DOMAIN . '_otp_form_last_name', 'false') === 'true';
        $emailNameInput = get_option(TEXT_DOMAIN . '_otp_form_email', 'false') === 'true';
        $usernameInput = get_option(TEXT_DOMAIN . '_otp_form_username', 'false') === 'true';
        ob_start();
        ?>
            <div class="phone-number-container <?php echo ($form_type === 'checkout') ? 'checkout-otp-form' : ''; ?>">
                <h3 class="otp-form-title"><?php _e('Login or Register',TEXT_DOMAIN);?></h3>
                <div class="form-row">
                    <label for="phone_number"><?php _e('Enter your mobile number',TEXT_DOMAIN);?></label>
                    <small class="d-block mb-3"><?php _e('A verification code will be sent to this number via SMS.',TEXT_DOMAIN);?></small>
                    <input autofocus type="text" class="otp-mobile-input" dir="ltr" id="phone_number" name="phone_number" placeholder="<?php _e('Start with 09..',TEXT_DOMAIN);?>" required />
                </div>
                <div class="form-row">
                    <button type="button" class="send-otp-button" data-form-type="<?php echo esc_attr($form_type); ?>">
                        <span class="me-2 d-none btn-spinner"><i class="icon-spinner4"></i></span>
                        <span class="btn-text"><?php _e('Get Otp Code',TEXT_DOMAIN);?></span>
                    </button>

                        <?php $termsText =  get_option(TEXT_DOMAIN. '_otp_form_terms');
                        if (!empty($termsText)):?>
                        <p class="mb-0 mt-3 otp-copyright"><?php echo $termsText; ?></p>
                        <?php endif;?>
                </div>
            </div>

            <div class="otp-verification-container" style="display: none;">
                <h3><?php _e('Enter Otp Code',TEXT_DOMAIN);?></h3>
                <small class="d-block mb-3"><?php _e('Enter the verification code sent to your mobile number.',TEXT_DOMAIN);?></small>
                <div class="form-row">
                    <div class="otp-inputs">
                        <?php for ($i = 1; $i <= 5; $i++) : ?>
                            <input type="text" class="otp-input" maxlength="1" data-index="<?php echo $i; ?>" />
                        <?php endfor; ?>
                    </div>
                </div>

                <div class="form-row">
                    <div class="timer-container">
                        <span><?php _e('Remaining time:',TEXT_DOMAIN);?> </span>
                        <span class="timer">02:00</span>
                    </div>
                </div>

                <!-- optional inputs-->
                <?php if ($firstNameInput || $lastNameInput || $emailNameInput || $usernameInput):?>
                    <div class="optional-otp-inputs">
                        <?php if ($firstNameInput):?>
                            <div class="form-row">
                                <input type="text" class="otp-mobile-input optional-otp-input" id="first_name" name="first_name"
                                       placeholder="<?php _e('First Name',TEXT_DOMAIN);?>" required style="display: none;"/>
                            </div>
                        <?php endif;?>

                        <?php if ($lastNameInput):?>
                            <div class="form-row">
                                <input type="text" class="otp-mobile-input optional-otp-input" id="last_name" name="last_name"
                                       placeholder="<?php _e('Last Name',TEXT_DOMAIN);?>" required style="display: none;"/>
                            </div>
                        <?php endif;?>

                        <?php if ($emailNameInput):?>
                            <div class="form-row">
                                <input type="email" class="otp-mobile-input optional-otp-input" dir="ltr" id="email" name="email"
                                       placeholder="<?php _e('Email',TEXT_DOMAIN);?>" required style="display: none;"/>
                            </div>
                        <?php endif;?>

                        <?php if ($usernameInput):?>
                            <div class="form-row">
                                <input type="text" class="otp-mobile-input optional-otp-input" dir="ltr" id="username" name="username"
                                       placeholder="<?php _e('Username',TEXT_DOMAIN);?>" required style="display: none;"/>
                                <small class="d-block mt-2 mb-3 optional-otp-input text-start"><?php _e('username can contain lowercase letters (a-z), numbers (0-9), spaces, underscores (_), hyphens (-), and the "@" symbol.',TEXT_DOMAIN);?></small>
                            </div>
                        <?php endif;?>
                    </div>
                <?php endif;?>



                <div class="form-row">
                    <button type="button" class="verify-otp-button" data-form-type="<?php echo esc_attr($form_type); ?>">
                        <span class="me-2 d-none btn-spinner"><i class="icon-spinner4"></i></span>
                        <span class="btn-text"><?php _e('Confirm',TEXT_DOMAIN);?></span>
                    </button>
                    <button type="button" class="resend-otp-button" style="display: none;">
                        <span class="me-2 d-none btn-spinner"><i class="icon-spinner4"></i></span>
                        <span class="btn-text"><?php _e('Resend Otp Code',TEXT_DOMAIN);?></span>
                    </button>
                </div>
            </div>
        <?php
        return ob_get_clean();
    }

    /**
     * AJAX handler for sending OTP
     */
    public function send_otp() {
        check_ajax_referer('custom-otp-nonce', 'nonce');

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

        if (!$this->validate_iranian_phone_number($phone_number)) {
            wp_send_json_error(array('message' => __('Mobile number is invalid',TEXT_DOMAIN)));
            return;
        }

        $otp = $this->generate_otp();
//        $otp = "12345";
        $this->store_otp_in_session($phone_number, $otp);
        $result = $this->send_sms($phone_number, $otp);
//        $result = true;

        $userExists = $this->phone_exists($phone_number);

        if ($result) {
            wp_send_json_success(array('message' => __('Verification code has been sent',TEXT_DOMAIN),'exists' => $userExists));
        } else {
            wp_send_json_error(array('message' => __('There was a problem sending the verification code.',TEXT_DOMAIN)));
        }
    }

    /**
     * AJAX handler for verifying OTP
     */
    public function verify_otp() {
        check_ajax_referer('custom-otp-nonce', 'nonce');

        $phone_number = isset($_POST['phone_number']) ? sanitize_text_field($_POST['phone_number']) : '';
        $firstName = isset($_POST['first_name']) && !empty($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
        $lastName = isset($_POST['last_name']) && !empty($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
        $email = isset($_POST['email']) && !empty($_POST['email']) ? sanitize_text_field($_POST['email']) : '';
        $username = isset($_POST['username']) && !empty($_POST['username']) ? sanitize_text_field($_POST['username']) : '';

         $user_data = [
             'phone_number' => $phone_number,
         ];
        if ($firstName) $user_data['first_name'] = $firstName;
        if ($lastName) $user_data['last_name'] = $lastName;
        if ($email) $user_data['user_email'] = $email;
        if ($username) $user_data['user_login'] = $username;


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

        if ($this->verify_otp_from_session($phone_number, $otp)) {
            if ($this->phone_exists($phone_number)) {
                $user_id = $this->get_user_by_phone($phone_number);
                if (!$user_id) {
                    wp_send_json_error(array('message' => __('User not found',TEXT_DOMAIN)));
                    return;
                }
            } else {
                $user_id = $this->create_new_user($user_data);
                if (is_wp_error($user_id)) {
                    wp_send_json_error(array('message' => $user_id->get_error_message()));
                    return;
                }
            }

            $this->login_user($user_id);

// Determine redirect URL based on where the user is logging in from
            $redirect_url = wc_get_page_permalink('myaccount'); // Default to account page

// If on checkout page, redirect back to checkout
            if (is_checkout()) {
                $redirect_url = wc_get_checkout_url();
            }

// You could also check the form_type if you want to be more specific
            $form_type = isset($_POST['form_type']) ? sanitize_text_field($_POST['form_type']) : '';
            if ($form_type === 'checkout') {
                $redirect_url = wc_get_checkout_url();
            }

            wp_send_json_success(array(
                'message' => __('Login Successful',TEXT_DOMAIN),
                'redirect' => $redirect_url
            ));
        } else {
            wp_send_json_error(array('message' => __('The verification code is invalid or has expired.',TEXT_DOMAIN)));
        }
    }

    /**
     * Validate Iranian phone number
     */
    private function validate_iranian_phone_number($phone_number) {
        return preg_match('/^09[0-9]{9}$/', $phone_number);
    }

    /**
     * Generate a random 5-digit OTP
     */
    private function generate_otp() {
        return str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * Store OTP in session
     */
    private function store_otp_in_session($phone_number, $otp) {
        $session_data = array(
            'otp' => $otp,
            'timestamp' => time(),
            'expires' => time() + (2 * 60) // 2 minutes expiry
        );
        set_transient('otp_' . md5($phone_number), $session_data, 3 * 60);
    }

    /**
     * Verify OTP from session
     */
    private function verify_otp_from_session($phone_number, $otp) {
        $session_data = get_transient('otp_' . md5($phone_number));

        if (!$session_data) {
            return false;
        }

        if (time() > $session_data['expires']) {
            return false;
        }

        return $session_data['otp'] === $otp;
    }

    /**
     * Send SMS using selected provider
     */
    private function send_sms($phone_number, $otp) {
        switch ($this->sms_provider) {
            case 'kavenegar':
                return $this->send_sms_kavenegar($phone_number, $otp);
            case 'smsir':
                return $this->send_sms_smsir($phone_number, $otp);
            case 'melipayamak':
                return $this->send_sms_melipayamak($phone_number, $otp);
            case 'ghasedak':
                return $this->send_sms_ghasedak($phone_number, $otp);
            default:
                return false;
        }
    }

    /**
     * Send SMS using SMS.ir API
     */
    private function send_sms_smsir($phone_number, $otp) {
        try {
            $url = 'https://api.sms.ir/v1/send/verify';
            $data = array(
                'Mobile' => $phone_number,
                'TemplateId' => $this->template,
                'Parameters' => array(
                    array(
                        'Name' => 'Code',
                        'Value' => $otp
                    )
                )
            );

            $headers = array(
                'X-API-KEY: ' . $this->api_key,
                'Content-Type: application/json',
                'Accept: application/json'
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            $response = curl_exec($ch);
            curl_close($ch);

            $result = json_decode($response);
            return isset($result->status) && $result->status === 1;
        } catch (Exception $e) {
            error_log('SMS.ir Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send SMS using Kavenegar API
     */
    private function send_sms_kavenegar($phone_number, $otp) {
        try {
            $url = "https://api.kavenegar.com/v1/{$this->api_key}/verify/lookup.json";
            $data = array(
                'receptor' => $phone_number,
                'token' => $otp,
                'template' => $this->template
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($response);
            return isset($result->return->status) && $result->return->status == 200;
        } catch (Exception $e) {
            error_log('Kavenegar Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send SMS using Melipayamak API
     */
    private function send_sms_melipayamak($phone_number, $otp) {
        try {
            $url = 'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber';
            $data = array(
                'username' => $this->username,
                'password' => $this->api_key,
                'to' => $phone_number,
                'from' => $this->senderNumber,
                'text' => $otp,
                'bodyId' => $this->template,
                'isFlash' => false
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($response);
            return isset($result->Value) && $result->RetStatus == 1;
        } catch (Exception $e) {
            error_log('Melipayamak Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send SMS using Ghasedak API
     */
    private function send_sms_ghasedak($phone_number, $otp) {
        try {
            $url = 'https://api.ghasedak.me/v2/verification/send/simple';
            $data = array(
                'receptor' => $phone_number,
                'type' => 1,
                'template' => $this->template,
                'token' => $otp
            );
            $headers = array(
                'apikey: ' . $this->api_key
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            $response = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($response);
            return isset($result->result->code) && $result->result->code == 200;
        } catch (Exception $e) {
            error_log('Ghasedak Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Check if a user with the given phone number exists
     */
    private function phone_exists($phone_number) {
        global $wpdb;
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = 'phone_number' AND meta_value = %s",
            $phone_number
        ));
        return $count > 0;
    }

    /**
     * Get user ID by phone number
     */
    private function get_user_by_phone($phone_number) {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare(
            "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'phone_number' AND meta_value = %s",
            $phone_number
        ));
    }

    /**
     * Create a new user with phone number
     */
    private function create_new_user($user_data) {

        // check username
        $username = $user_data['user_login'];
        if(empty($user_data['user_login']) || $user_data['user_login'] == '' || $user_data['user_login'] == 'admin'){
            $username = 'user_' . substr($user_data['phone_number'], -8);
        }else{
            $username = $user_data['user_login'];
        }

        // check email
        if(empty($user_data['user_email'])){
            $email = null;
        }else{
            $email = $user_data['user_email'];
        }

        // generate password
        $user_data['user_pass'] = wp_generate_password(12, true);

        // create user
        $user_id = wp_create_user($username, $password,$email);

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

        $user = new WP_User($user_id);
        $user->set_role('customer');
        update_user_meta($user_id, 'phone_number', $user_data['phone_number']);

        if(!empty($user_data['first_name'])){
            update_user_meta($user_id, 'first_name', $user_data['first_name']);
        }

        if(!empty($user_data['last_name'])){
            update_user_meta($user_id, 'last_name', $user_data['last_name']);
        }

        return $user_id;
    }

    /**
     * Log the user in
     */
    private function login_user($user_id) {
        wp_set_current_user($user_id);
        wp_set_auth_cookie($user_id);
    }

    /**
     * Add phone number field to user profile
     */
    public function add_phone_field($user) {
        ?>
        <h3><?php _e('Phone number',TEXT_DOMAIN);?></h3>
        <table class="form-table">
            <tr>
                <th><label for="phone_number"><?php _e('Phone number',TEXT_DOMAIN);?></label></th>
                <td>
                    <input type="text" name="phone_number" id="phone_number"
                           value="<?php echo esc_attr(get_user_meta($user->ID, 'phone_number', true)); ?>"
                           class="regular-text" />
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Save phone number field
     */
    public function save_phone_field($user_id) {
        if (current_user_can('edit_user', $user_id)) {
            if (isset($_POST['phone_number'])) {
                $phone_number = sanitize_text_field($_POST['phone_number']);
                if ($this->validate_iranian_phone_number($phone_number)) {
                    update_user_meta($user_id, 'phone_number', $phone_number);
                }
            }
        }
    }
}


// Initialize the functionality
function custom_otp_theme_init() {
    if (class_exists('WooCommerce')) {
        new Custom_OTP_Login();
    }
}

add_action('after_setup_theme', 'custom_otp_theme_init');

function remove_default_woocommerce_login_form() {
    if (is_account_page() && !is_user_logged_in()) {
        add_filter('woocommerce_account_content', '__return_false');
        add_filter('woocommerce_login_form_start', '__return_null');
        add_filter('woocommerce_login_form', '__return_null');
        add_filter('woocommerce_login_form_end', '__return_null');
        remove_action('woocommerce_login_form', 'woocommerce_login_form_fields', 10);

        add_action('wp_head', function() {
            echo '<style>
                #customer_login:not(.custom-login-container) {display: none !important;}
                .woocommerce-form-login__submit, .woocommerce-form-login__rememberme, .woocommerce-LostPassword {display: none !important;}
                form.woocommerce-form-login > *:not(.custom-otp-form) {display: none !important;}
                form.woocommerce-form-register > *:not(.custom-otp-form) {display: none !important;}
            </style>';
        });
    }
}



// display phone number in admin dasboard users lists
// 1. Add a new column to the Users admin list
function add_phone_number_column($columns) {
    $new_columns = [];

    foreach ($columns as $key => $value) {
        if ($key === 'email') {
            // Insert our custom column before the email column
            $new_columns['phone_number'] = 'موبایل';
        }
        $new_columns[$key] = $value;
    }

    return $new_columns;
}
add_filter('manage_users_columns', 'add_phone_number_column');

// 2. Show the phone number in the new column
function show_phone_number_column_content($value, $column_name, $user_id) {
    if ($column_name == 'phone_number') {
        $phone = get_user_meta($user_id, 'phone_number', true);
        return $phone ? esc_html($phone) : '—';
    }
    return $value;
}
add_action('manage_users_custom_column', 'show_phone_number_column_content', 10, 3);

// 3. Make the column sortable
function phone_number_column_sortable($columns) {
    $columns['phone_number'] = 'phone_number';
    return $columns;
}
add_filter('manage_users_sortable_columns', 'phone_number_column_sortable');

// 4. Adjust the query to sort by phone number
function phone_number_orderby_column($query) {
    if (!is_admin()) return;

    $screen = get_current_screen();
    if ($screen->id !== 'users' || !isset($_GET['orderby']) || $_GET['orderby'] !== 'phone_number') return;

    $query->query_vars['meta_key'] = 'phone_number';
    $query->query_vars['orderby'] = 'meta_value';
}
add_action('pre_get_users', 'phone_number_orderby_column');
