<?php
namespace MineCloudvod\Member;
use MineCloudvod\Libs\QRcode;

class Sms {
    private $login_id = 'sms';
    public function __construct( ) {

        add_action('rest_api_init', [$this, 'register_routes']);

        add_filter( 'mcv_user_login_options', [ $this, 'login_options' ] );

        add_filter( 'mcv_login_script', [ $this, 'login_script' ], 10, 2 );
        
    }

    public function login_script( $script, $key ){
        if( $key == $this->login_id ){
            $script = mcv_trim( '
                jQuery(function(){
                    let html = \'<div class="mcv-uc-login"><div class="components-base-control text"><div class="components-base-control__field"><input class="components-text-control__input" type="text" id="mcv-uc-phone" placeholder="请输入手机号" name="phone" autocomplete="phone"></div></div><div class="components-base-control text"><div class="components-base-control__field" style="position: relative;"><input class="components-text-control__input" type="text" id="mcv-uc-check-code" placeholder="验证码" autocomplete="off"><button id="mcv-uc-send-code" style="border: 0;background: transparent;position: absolute;right: 0;padding: 0 12px;line-height: 48px;color: var(--wp--preset--color--maincolor, #1769fe);cursor: pointer;">发送验证码</button></div></div><p class="mcv-uc-protocol checked">我已阅读并同意<a class="mcv-privacy-btn">《服务协议和隐私政策》</a></p><div class="components-base-control text"><div class="components-base-control__field"><input class="components-text-control__input login-btn" type="button" id="mcv-uc-phone-login" value="登录" style="color:#fff;border:0;cursor:pointer;"></div></div></div>\';
                    jQuery("#login_container").html(html);
                    if(!window?.mcvmsgtime) window.mcvmsgtime = 0;
                    jQuery("#mcv-uc-send-code").on("click", function(){
                        let phone = jQuery("#mcv-uc-phone").val();
                        if( !phone ){
                            jQuery("#mcv-uc-phone").focus();
                            return;
                        }
                        if( !/^1[3456789]\d{9}$/.test(phone) ){
                            layer.msg("手机号码格式错误");
                            jQuery("#mcv-uc-phone").focus();
                            return;
                        }

                        if( window.mcvmsgtime > 0 ){
                            return;
                        }
                        if( !jQuery(".mcv-uc-protocol").hasClass("checked")){
                            layer.msg("请先同意服务协议和隐私政策");
                            return;
                        }
                        window.mcvmsgtime = 60;
                        let timer = setInterval(function(){
                            window.mcvmsgtime--;
                            console.log(window.mcvmsgtime);
                            jQuery("#mcv-uc-send-code", "body").html(window.mcvmsgtime+"秒后重发");
                            if(window.mcvmsgtime <= 0){
                                clearInterval(timer);
                                jQuery("#mcv-uc-send-code").html("发送验证码");
                            }
                        }, 1000);
                        wp.apiFetch({
                            path: "/mine-cloudvod/v1/member/send_code",
                            method: "POST",
                            data: {
                                phone: phone,
                            }
                        }).then(function(res){
                            if(res.status == "0"){
                                layer.msg("验证码发送失败（"+res.msg+"）");
                            }
                            if(res.status == "1"){
                                if(res.data.code == "OK"){
                                    layer.msg("验证码发送成功");
                                    jQuery("#mcv-uc-check-code").val("").focus();
                                }else{
                                    layer.msg("验证码发送失败（"+res.data.message+"）");
                                }
                            }
                        });
                    });
                    jQuery("#mcv-uc-phone-login").on("click", function(){
                        let phone = jQuery("#mcv-uc-phone").val();
                        let code = jQuery("#mcv-uc-check-code").val();
                        if( !phone ){
                            jQuery("#mcv-uc-phone").focus();
                            return;
                        }
                        if( !/^1[3456789]\d{9}$/.test(phone) ){
                            layer.msg("手机号码格式错误");
                            jQuery("#mcv-uc-phone").focus();
                            return;
                        }
                        if( !code ){
                            layer.msg("请输入验证码");
                            jQuery("#mcv-uc-check-code").focus();
                            return;
                        }
                        wp.apiFetch({
                            path: "/mine-cloudvod/v1/member/sms_login",
                            method: "POST",
                            data: {
                                phone: phone,
                                code: code,
                            },
                        }).then(function(res){
                            if(res.status == "0"){
                                layer.msg("登录失败（"+res.msg+"）");
                            }
                            if(res.status == "1"){
                                if(res.data.uid){
                                    layer.msg("登录成功",{time:1000}, function(){
                                        window.location.reload();
                                    });
                                }else{
                                    layer.msg("登录失败（"+res.msg+"）");
                                }
                            }
                        });
                    });
                                
                });
            ' );
        }
        return $script;
    }

    public function login_options( $login3 ){
        $ops = false;
        if( isset( MINECLOUDVOD_SETTINGS[$this->login_id] ) ) $ops = MINECLOUDVOD_SETTINGS[$this->login_id];
        $login3[] = array(
            'id'        => $this->login_id,
            'type'      => 'fieldset',
            'title'     => '短信登录',
            'fields'    => array(
                array(
                    'id'    => 'status',
                    'type'  => 'switcher',
                    'title' => __('State', 'mine-cloudvod'),
                    'text_on'    => __('Enable', 'mine-cloudvod'),
                    'text_off'   => __('Disable', 'mine-cloudvod'),
                    'default' => $ops ? $ops['status'] : false,
                ),
                array(
                    'id'    => 'title',
                    'type'  => 'text',
                    'title' => __('Title', 'mine-cloudvod'),
                    'dependency' => array('status', '==', true),
                    'default' => '验证码登录',
                ),
                [ // 短信服务商
                    'id'      => 'company',
                    'type'    => 'button_set',
                    'title'   => '短信服务商',
                    'inline'  => true,
                    'options' => [
                        'aliyun'    => '阿里云',
                    ],
                    'dependency' => array('status', '==', true),
                    'default'   => 'aliyun',
                ],
                array(
                    'id'    => 'AppID',
                    'type'  => 'text',
                    'title' => 'AccessKeyId',
                    'dependency' => array('status', '==', true),
                    'default' => $ops ? $ops['AppID'] : false,
                ),
                array(
                    'id'    => 'AppSecret',
                    'type'  => 'text',
                    'title' => 'AccessKeySecret',
                    'dependency' => array('status', '==', true),
                    'default' => $ops ? $ops['AppSecret'] : false,
                ),
                array(
                    'id'    => 'sign',
                    'type'  => 'text',
                    'title' => '短信签名',
                    'dependency' => array('status', '==', true),
                    'default' => get_bloginfo( 'name' ),
                ),
                array(
                    'id'    => 'template',
                    'type'  => 'text',
                    'title' => '短信模板CODE',
                    'dependency' => array('status', '==', true),
                ),
            ),
        );
        return $login3;
    }
    public function register_routes(){
        /**
         * 登录回调
         */
        register_rest_route('mine-cloudvod/v1', '/member/send_code', [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'send_code'],
                'permission_callback' => '__return_true',
                'args'                => [
                    'phone' => [
                        'type' => 'string'
                    ],
                ]
        ]);
        /**
         * 登录回调
         */
        register_rest_route('mine-cloudvod/v1', '/member/sms_login', [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'mcv_login'],
                'permission_callback' => '__return_true',
                'args'                => [
                    'code' => [
                        'type' => 'string'
                    ],
                    'phone' => [
                        'type' => 'string'
                    ],
                ]
        ]);
    }
    /**
     * 发送验证码
     */
    public function send_code( \WP_REST_Request $request ){
        $phone = sanitize_text_field( $request['phone'] );
        $msg = '';
        // 验证手机号是否为空
        if( empty($phone) ) {
            $msg =  __('Phone is missed', 'mine-cloudvod');
        }
        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $msg = __('Invalid phone number format', 'mine-cloudvod');
        }
        $options = MINECLOUDVOD_SETTINGS['uc_login3'][$this->login_id] ?? [];
        $accessKeyID = $options['AppID']??'';
        $accessKeySecret = $options['AppSecret']??'';
        $sign = $options['sign']??'';
        $template = $options['template']??'';
        if( !$accessKeyID || !$accessKeySecret || !$sign || !$template ){
            $msg = __('Some settings is missed', 'mine-cloudvod');
        }
        if( $msg ){
            return rest_ensure_response(['status' => '0', 'msg' => $msg]);
        }
        $code = wp_rand(100000, 999999);
        global $McvApi;
        $data = [
            'sdk' => $McvApi->encrypt( [
                'accessKeyID' => $accessKeyID,
                'accessKeySecret' => $accessKeySecret,
            ] ),
            'phone' => $phone,
            'template' => $options['template']??'',
            'sign' => $sign,
            'code' => $code,
            'mode' => 'aliyunsms',
        ];
        $result = $McvApi->call( 'sendmsg', $data );
        // $result = ['status' => 1, 'data' => ['success' => $code, 'code' => 'OK', 'msg' => 'success']];
        if( $result['status'] == 1 && isset($result['data']['code']) && $result['data']['code'] == 'OK' ){
            set_transient('mcv_sms_code_'.$phone, $code, 10 * MINUTE_IN_SECONDS);
        }
        return rest_ensure_response($result);
    }
    /**
     * 登录回调
     */
    public function mcv_login( \WP_REST_Request $request ){
        $phone = sanitize_text_field( $request['phone'] );
        $msg = '';
        // 验证手机号是否为空
        if( empty($phone) ) {
            $msg =  __('Phone is missed', 'mine-cloudvod');
        }
        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $msg = __('Invalid phone number format', 'mine-cloudvod');
        }

        $code = sanitize_text_field( $request['code'] );
        if( empty($code) ){
            $msg =  __('Code is missed', 'mine-cloudvod');
        }
        $stored_code = get_transient('mcv_sms_code_'.$phone);
        if( !$stored_code || $stored_code != $code ){ 
            $msg =  __('Code is incorrect', 'mine-cloudvod');
        }
    	
        if( $msg ){
            return rest_ensure_response(['status' => '0', 'msg' => $msg]);
        }

        global $wpdb;
        $uid = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT ID FROM $wpdb->users LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID=$wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key='mcv_phone' and $wpdb->usermeta.meta_value=%s;",
                $phone
            )
        );
        
        if( $uid ){
            $user = get_user_by('id', $uid);
            wp_set_current_user( $uid );
            wp_set_auth_cookie($uid,true,is_ssl());
            do_action( 'wp_login', $user->user_login, $user );
            return rest_ensure_response(['status' => '1', 'data' => ['uid' => $uid]]);
        }else{
            $pass = wp_create_nonce(wp_rand(10,1000));
            $login_name = $phone;
            $username = 'mcv_'. $phone;
            $userdata=array(
                'user_login' => $login_name,
                'display_name' => $username,
                'user_nicename' => $username,
                'user_pass' => $pass,
                'first_name' => $username
            );
            $user_id = wp_insert_user( $userdata );
            
            if ( !is_wp_error( $user_id ) ) {
                $user = get_user_by('id', $user_id);
                update_user_meta($user_id, 'mcv_phone', $phone);
                wp_set_current_user( $user_id );
                wp_set_auth_cookie($user_id,true,is_ssl());
                do_action( 'wp_login', $user->user_login, $user );
                return rest_ensure_response(['status' => '1', 'data' => ['uid' => $user_id]]);
            }
            else{
                return rest_ensure_response(['status' => '0', 'msg' => __('Database error, try later!', 'mine-cloudvod')]);
            }
        }
    }
}