<?php

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

function generateNumericCaptcha() {

    $ea_digits = array(
        'sj_dg_cd-1' => '9636',
        'sj_dg_cd-2' => '5423',
        'sj_dg_cd-3' => '9559',
        'sj_dg_cd-4' => '3663',
        'sj_dg_cd-5' => '8568',
        'sj_dg_cd-6' => '7436',
        'sj_dg_cd-7' => '7755',
        'sj_dg_cd-8' => '6565',
        'sj_dg_cd-9' => '3693',
        'sj_dg_cd-11' => '1568',
        'sj_dg_cd-12' => '3569',
        'sj_dg_cd-13' => '3576',
        'sj_dg_cd-14' => '8364',
        'sj_dg_cd-15' => '5622',
        'sj_dg_cd-17' => '9966',
        'sj_dg_cd-18' => '5743',
        'sj_dg_cd-19' => '2368',
        'sj_dg_cd-20' => '6465',
        'sj_dg_cd-21' => '5759',
        'sj_dg_cd-22' => '3435',
        'sj_dg_cd-23' => '9895',
        'sj_dg_cd-24' => '6358',
        'sj_dg_cd-25' => '7459',
        'sj_dg_cd-26' => '9357',
        'sj_dg_cd-27' => '5938',
        'sj_dg_cd-28' => '5628',
        'sj_dg_cd-29' => '3685',
        'sj_dg_cd-30' => '6834',
        'sj_dg_cd-31' => '6545',
        'sj_dg_cd-32' => '7353',
        'sj_dg_cd-33' => '9955',
        'sj_dg_cd-34' => '7626',
        'sj_dg_cd-35' => '5767',
        'sj_dg_cd-36' => '3929',
        'sj_dg_cd-37' => '7473',
        'sj_dg_cd-38' => '3474',
        'sj_dg_cd-39' => '9584',
        'sj_dg_cd-40' => '6383',
        'sj_dg_cd-41' => '9592',
        'sj_dg_cd-42' => '8646',
        'sj_dg_cd-43' => '4232',
        'sj_dg_cd-44' => '6797',
        'sj_dg_cd-45' => '2728',
        'sj_dg_cd-46' => '3646',
        'sj_dg_cd-47' => '3639',
        'sj_dg_cd-48' => '1564',
    );

    $randomKey = array_rand($ea_digits);
    $randomName = $randomKey;
    $randomCode = $ea_digits[$randomKey];
    set_transient('numeric_captcha_code', $randomCode, 60 * 5);

    $now = current_time( 'timestamp' );
    set_transient('numeric_captcha_timestamp', $now, 60 * 5);

    $source = get_template_directory_uri() . '/assets/digits/' . $randomName . '.jpg';
    
    header( 'Content-Type: application/json' );
    echo json_encode( array(
        'source'    => __($source, "etiuse-lab")
    ) );

    wp_die();
}
add_action( 'wp_ajax_nopriv_generateNumericCaptcha', 'generateNumericCaptcha' );
add_action( 'wp_ajax_generateNumericCaptcha', 'generateNumericCaptcha' );

/*
* Login -> Exists Form Shortcode
*/
function ea_login_exists_callback() {

    $nonce = $_POST['nonce'];
    if ( ! wp_verify_nonce( $nonce, 'login_nonce' ) ) {
        die( 'Invalid nonce' );
    }

    $message = '';
    $exists = '';
    $form = '';
    $image_recaptcha = intval($_POST['image_recaptcha']);

    $numeric_captcha = get_transient('numeric_captcha_code');

    if( $numeric_captcha && ($image_recaptcha == $numeric_captcha) ) {

        $now = current_time( 'timestamp' );
        $numeric_captcha_timestamp = get_transient('numeric_captcha_timestamp');

        if( $now - $numeric_captcha_timestamp > 120 ) { // Code has been Expired

            $validate = false;
            $message .= 'کد امنیتی وارد شده منقضی شده است، لطفا دوباره تلاش نمایید';

        } else {

            $phone_raw = $_POST['phone'];
            $phone_raw = preg_replace('/\D/', '', $phone_raw);
            if (strlen($phone_raw) == 11 && substr($phone_raw, 0, 2) == "09") {
                $validate = true;
                $phone = "98" . substr($phone_raw, 1);
                // Search for user by user_phone meta field
                $user_query = new WP_User_Query(array(
                    'meta_key' => 'user_phone',
                    'meta_value' => $phone,
                    'fields' => 'ID'
                ));
                $exists = ! empty( $user_query->get_results() );

                $user = null;
                if ($exists) {
                    $user_id = $user_query->get_results()[0];
                    $user = get_user_by('id', $user_id);
                }

                if (is_object($user) && in_array('administrator', $user->roles)) {

                    $validate = false;
                    $message .= 'شما مجاز به ورود نمی باشید';

                } else { // User is not an administrator
                    
                    ob_start();
                    ?>
                    <!-- LOGIN FORM -->
                    <form class="ea_login_form" id="ea_login_form" style="display:none;">
                        <!-- FORM MESSAGE -->
                        <div class="ea_login_message" id="ea_login_message" style="display:none;"></div>
                        <!-- PASSWORD -->
                        <div class='ea_login_field ea_floating_field'>
                            <div class='ea_login_field_input_wrapper'>
                                <input type='password' class='ea_login_field_input' id='ea_login_password' name='password' placeholder=' ' required>
                                <label class='ea_login_label ea_floating_label' for='password'>
                                    <span class='ea_login_field_icon'>
                                            <?php echo file_get_contents( get_template_directory() . '/assets/icons/lock-01.svg' ); ?>
                                    </span>
                                    <span class='ea_login_label_text'>
                                        رمز عبور
                                    </span>
                                </label>
                                <div id='ea_login_password_toggle'>
                                    <span class='ea_show_password'>
                                        <?php echo file_get_contents( get_template_directory() . '/assets/icons/eye.svg' ); ?>
                                    </span>
                                    <span class='ea_hide_password'>
                                        <?php echo file_get_contents( get_template_directory() . '/assets/icons/eye-off.svg' ); ?>
                                    </span>
                                </div>
                            </div>
                            <!-- <div class='ea_login_field_desc'></div>
                            <div class='ea_login_field_error'></div> -->
                        </div>
                        <input type='submit' value='ورود به اتیوس' class='ea_login_submit' id='ea_login_submit' disabled='true'>
                        <div class="ea_login_btns_wrapper"> 
                            <button class="ea_login_btn" id="ea_btn_loginOtp" type="button">
                                ورود با کد یکبار مصرف
                            </button>
                            <button class="ea_login_btn" id="ea_btn_forgetPass" type="button">
                                فراموشی رمز عبور
                            </button>
                        </div>
                    </form>

                    <!-- OTP FORM -->
                    <form class="ea_login_form" id="ea_otp_form" style="display:none;">
                        <!-- FORM MESSAGE -->
                        <div class="ea_login_message" id="ea_otp_message" style="display:none;"></div>
                        <!-- OTP INPUT -->
                        <div class="ea_otp_input_wrapper">
                            <div class="ea_otp_input_container">
                                <input type="tel" class="ea_otp_input" id="ea_otp_1" maxlength="1" data-index="0" autocomplete="off">
                                <input type="tel" class="ea_otp_input" id="ea_otp_2" maxlength="1" data-index="1" autocomplete="off">
                                <input type="tel" class="ea_otp_input" id="ea_otp_3" maxlength="1" data-index="2" autocomplete="off">
                                <input type="tel" class="ea_otp_input" id="ea_otp_4" maxlength="1" data-index="3" autocomplete="off">
                                <input type="tel" class="ea_otp_input" id="ea_otp_5" maxlength="1" data-index="4" autocomplete="off">
                                <input type="tel" class="ea_otp_input" id="ea_otp_6" maxlength="1" data-index="5" autocomplete="off">
                            </div>
                            <input type="hidden" id="ea_login_otp" name="code" required>
                        </div>
                        <input type="submit" value="ورود به اتیوس" class="ea_login_submit" id="ea_otp_submit">
                        <div class="ea_login_btns_wrapper"> 
                            <button class="ea_login_btn" id="ea_btn_resendOtp" type="button" disabled="true">
                                ارسال مجدد کد
                            </button>
                            <button class="ea_login_btn" id="ea_btn_changeNumber" type="button">
                                تغییر شماره
                            </button>
                        </div>
                    </form>

                    <?php
                    $form = ob_get_clean();

                }

            } else {
                $validate = false;
                $message = 'شماره وارد شده نامعتبر می باشد. لطفا دوباره تلاش کنید';
            }
        }
    } else { // image reCAPTCHA verification failed
        $validate = false;
        $message .= 'کد امنیتی وارد شده صحیح نمی باشد، لطفا دوباره تلاش نمایید';
    }

    delete_transient('numeric_captcha_code');
    delete_transient('numeric_captcha_timestamp');

    header( 'Content-Type: application/json' );
    echo json_encode( array(
        'validate'   => $validate,
        'exists'     => $exists,
        'form'     => $form,
        'message'    => __($message, "etiuse-lab")
    ) );

    wp_die();
}
add_action( 'wp_ajax_ea_login_exists', 'ea_login_exists_callback' );
add_action( 'wp_ajax_nopriv_ea_login_exists', 'ea_login_exists_callback' );

/*
* Login -> Login Form Shortcode
*/
function ea_login_login() {

    $phone_raw = $_POST['phone'];
    $phone_raw = preg_replace('/\D/', '', $phone_raw);
    if (strlen($phone_raw) == 11 && substr($phone_raw, 0, 2) == "09") {
        $phone = "98" . substr($phone_raw, 1);

        // Find user by user_phone meta field
        $user_query = new WP_User_Query(array(
            'meta_key' => 'user_phone',
            'meta_value' => $phone,
            'fields' => 'ID'
        ));
        $user_ids = $user_query->get_results();
        if (!empty($user_ids)) {
            $user = get_user_by('id', $user_ids[0]);
            $info = array();
            $info['user_login'] = $user->user_login;
            $info['user_password'] = $_POST['password'];
            $info['remember'] = true;

            $user = wp_signon( $info, false );
            if ( is_wp_error($user) ) {
                $response = array(
                    'loggedin' => false,
                    'message' => __("رمز وارد شده صحیح نمی باشد", "etiuse-lab")
                );
            } else {

                $home_url = home_url();
                $user_roles = $user->roles;
                $redirect_url = '';
                
                $role_redirects = [
                    'Manager' => '/p/m', // Manager
                    'Accountant' => '/p/a', // Accountant
                    'Lab' => '/p/l', // Lab
                    'Supervisor' => '/p/c', // Supervisor
                    'Specialist' => '/p/s', // Specialist
                    'Client' => '/p', // Client
                    'subscriber' => '/p/sign-up', // Subscriber
                ];
                
                foreach ($role_redirects as $role => $path) {
                    if (in_array($role, $user_roles)) {
                        $redirect_url = trailingslashit($home_url) . ltrim($path, '/');
                        break;
                    }
                }
                
                // Default to /p if no matching role found
                if (empty($redirect_url)) {
                    $redirect_url = trailingslashit($home_url) . 'p';
                }

                $response = array(
                    'loggedin' => true,
                    'redirecturl' => $redirect_url
                );
            }
        } else {
            $response = array(
                'loggedin' => false,
                'message' => __("کاربری با این شماره وجود ندارد!", "etiuse-lab")
            );
        }
    } else {
        $response = array(
            'loggedin' => false,
            'message' => __("شماره وارد شده معتبر نمی باشد! لطفا دوباره تلاش کنید", "etiuse-lab")
        );
    }
    
    header( 'Content-Type: application/json' );
    echo json_encode($response);
    wp_die();
}
add_action( 'wp_ajax_nopriv_ea_login_login', 'ea_login_login' );
add_action( 'wp_ajax_ea_login_login', 'ea_login_login' );

/*
* Login -> Login Form Shortcode
*/
function ea_login_otp_generator() {

    $phone_raw = $_POST['phone'];
    $phone_raw = preg_replace('/\D/', '', $phone_raw);
    if (strlen($phone_raw) == 11 && substr($phone_raw, 0, 2) == "09") {

        // Search for user by user_phone meta field
        $phone = "98" . substr($phone_raw, 1);
        $user_query = new WP_User_Query(array(
            'meta_key' => 'user_phone',
            'meta_value' => $phone,
            'fields' => 'ID'
        ));
        $exists = ! empty( $user_query->get_results() );

        $user = null;
        if ($exists) {
            $user_id = $user_query->get_results()[0];
            $user = get_user_by('id', $user_id);
        }
            
        $digits = array();
        for ($i = 0; $i < 6; $i++) {
            array_push($digits, rand(0, 9));
        }
        // Ensure we have at least one duplicate digit (not all unique)
        while (count(array_unique($digits)) == 6) {
            $digits[rand(0, 5)] = rand(0, 9);
        }
        $otp_code = implode("", $digits);
        $now = current_time( 'timestamp' );

        $mode = $_POST['user'];
        if ( $mode == 'exists' || $mode == 'forget' ){
            
            if ($exists && isset($user_id)) {
                update_user_meta($user_id, 'user_otp_code', $otp_code);
                update_user_meta($user_id, 'user_otp_timestamp', $now);
            } else {
                $response = array(
                    'generated' => false,
                    'message' => __("کاربری با این شماره وجود ندارد!", "etiuse-lab")
                );
                header( 'Content-Type: application/json' );
                echo json_encode($response);
                wp_die();
            }

        } else if( $mode == 'new' ){
            session_start();
            $_SESSION['otp_code'] = $otp_code;
            $_SESSION['otp_code_timestamp'] = $now;
        }  
        
        // etiuse_send_sms( $phone, 109769, array( $otp_code ) );
        
        $response = array(
            'generated' => true,
            'otp'       => $otp_code // ! TEMP
        );

    } else {
        $response = array(
            'generated' => false,
            'message' => __("شماره وارد شده معتبر نمی باشد! لطفا دوباره تلاش کنید", "etiuse-lab")
        );
    }
    
    header( 'Content-Type: application/json' );
    echo json_encode($response);
    wp_die();
}
add_action( 'wp_ajax_nopriv_ea_login_otp_generator', 'ea_login_otp_generator' );
add_action( 'wp_ajax_ea_login_otp_generator', 'ea_login_otp_generator' );

/*
* Login -> Login Form Shortcode
*/
function ea_login_otp() {

    $phone_raw = $_POST['phone'];
    $phone_raw = preg_replace('/\D/', '', $phone_raw);

    if (strlen($phone_raw) == 11 && substr($phone_raw, 0, 2) == "09") {

        $otp = $_POST['otp'];
        $mode = $_POST['user'];
        $phone = "98" . substr($phone_raw, 1);

        if( $mode == 'exists' || $mode == 'forget' ){
            
            // Find user by user_phone meta field
            $user_query = new WP_User_Query(array(
                'meta_key' => 'user_phone',
                'meta_value' => $phone,
                'fields' => 'ID'
            ));
            $user_ids = $user_query->get_results();
            if (!empty($user_ids)) {

                $user = get_user_by('id', $user_ids[0]);
                $user_id = $user->ID;

                $user_otp_code = get_user_meta($user_id, 'user_otp_code', true);

                if( $otp == $user_otp_code ) {

                    $now = current_time( 'timestamp' );
                    $time_diff = ( $now - get_user_meta( $user_id, 'user_otp_timestamp', true ) ) / ( 60 );
                    if( $time_diff > 5 ) {
    
                        $response = array(
                            'loggedin' => false,
                            'message' => __("کد یکبار مصرف وارد شده منقضی شده است. لطفا دوباره تلاش کنید", "etiuse-lab")
                        );
    
                    } else {
            
                        wp_set_current_user( $user_id, $user->user_login );
                        wp_set_auth_cookie( $user_id );
                        do_action( 'wp_login', $user->user_login, $user );
                        
                        if( $mode == 'exists' ) {

                            $home_url = home_url();
                            $user_roles = $user->roles;
                            $redirect_url = '';
                            
                            $role_redirects = [
                                'manager' => '/p/m', // Manager
                                'accountant' => '/p/a', // Acountant
                                'lab' => '/p/l', // Lab
                                'supervisor' => '/p/c', // Supervisor
                                'specialist' => '/p/s', // Specialist
                                'client' => '/p', // Client
                                'subscriber' => '/p/sign-up', // Subscriber
                            ];
                            
                            foreach ($role_redirects as $role => $path) {
                                if (in_array($role, $user_roles)) {
                                    $redirect_url = trailingslashit($home_url) . ltrim($path, '/');
                                    break;
                                }
                            }
                            
                            // Default to /p if no matching role found
                            if (empty($redirect_url)) {
                                $redirect_url = trailingslashit($home_url) . 'p';
                            }

                            $response = array(
                                'loggedin' => true,
                                'redirecturl' => $redirect_url
                            );

                        } else {
                            $home_url = home_url();
                            $redirect_url = trailingslashit($home_url) . 'p/account/?forget_password=true';
                            
                            $response = array(
                                'loggedin' => true,
                                'redirecturl' => $redirect_url
                            );
                        }
    
                    }
                } else {
                    $response = array(
                        'loggedin' => false,
                        'message' => __("کد یکبار مصرف وارد شده صحیح نمی باشد", "etiuse-lab")
                    );
                }

            } else {
                $response = array(
                    'loggedin' => false,
                    'message' => __("کاربری با این شماره وجود ندارد!", "etiuse-lab")
                );
            }

        } else if( $mode == 'new' ) {

            session_start();
            $saved_otp_code = $_SESSION['otp_code'];
            if($otp == $saved_otp_code) {

                $now = current_time( 'timestamp' );
                $time_diff = ( $now - $_SESSION['otp_code_timestamp'] ) / ( 60 );
                if( $time_diff > 5 ) {
                    $response = array(
                        'loggedin' => false,
                        'message' => __("کد یکبار مصرف وارد شده منقضی شده است. لطفا دوباره تلاش کنید", "etiuse-lab")
                    );
                } else {

                    $password = wp_generate_password(12);
                    do {
                        $random_number = mt_rand(100000, 999999);
                        $username = 'user_' . $random_number;
                        $existing_user = get_user_by('login', $username);
                    } while ($existing_user !== false);
                    
                    $new_user_id = wp_create_user($username, $password);
    
                    if (is_wp_error($new_user_id)) {
                        $response = array(
                            'loggedin' => false,
                            'message' => __($new_user_id->get_error_message(), "etiuse-lab")
                        );
                    } else {
                        
                        $user = get_user_by('id', $new_user_id);
                        wp_set_current_user($new_user_id, $user->user_login);
                        wp_set_auth_cookie($new_user_id);
                        do_action('wp_login', $user->user_login);
    
                        update_user_meta( $new_user_id, 'user_phone', $phone );
                        update_user_meta( $new_user_id, 'user_status', 'active' );
    
                        $home_url = home_url();
                        $redirect_url = trailingslashit($home_url) . 'p/sign-up';

                        $response = array(
                            'loggedin' => true,
                            'redirecturl' => $redirect_url
                        );
                    }
                }
            } else {
                $response = array(
                    'loggedin' => false,
                    'message' => __("کد یکبار مصرف وارد شده صحیح نمی باشد", "etiuse-lab")
                );
            }
        }
        
    } else {
        $response = array(
            'loggedin' => false,
            'message' => __("شماره وارد شده معتبر نمی باشد! لطفا دوباره تلاش کنید", "etiuse-lab")
        );
    }
    
    header( 'Content-Type: application/json' );
    echo json_encode($response);
    wp_die();
}
add_action( 'wp_ajax_nopriv_ea_login_otp', 'ea_login_otp' );
add_action( 'wp_ajax_ea_login_otp', 'ea_login_otp' );