<?php
namespace MineCloudvod\RestApi\Member;

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

class Login extends Base{

    protected $base = 'member';

    public function __construct(){
        $this->register();
    }

    public function register(){
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes(){
        /**
         * 账号密码登录
         */
        register_rest_route("{$this->namespace}/{$this->version}", "/".$this->base."/login", [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'user_login'],
                'permission_callback' => '__return_true',
                'args'                => [
                    'log' => [
                        'type' => 'string',
                    ],
                    'pwd' => [
                        'type' => 'string',
                    ],
                ]
        ]);
        /**
         * 账号密码注册
         */
        register_rest_route("{$this->namespace}/{$this->version}", "/".$this->base."/reg", [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'user_reg'],
                'permission_callback' => '__return_true',
                'args'                => [
                    'log' => [
                        'type' => 'string',
                    ],
                    'pwd' => [
                        'type' => 'string',
                    ],
                    'email' => [
                        'type' => 'string',
                    ],
                ]
        ]);
        /**
         * 获取当前登录账号信息
         */
        register_rest_route("{$this->namespace}/{$this->version}", "/".$this->base."/info", [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'user_info'],
                'permission_callback' => 'is_user_logged_in',
                'args'                => [
                    'action' => [
                        'type' => 'string'
                    ]
                ]
        ]);
    }


    public function user_reg(\WP_REST_Request $request){
        $can = get_option( 'users_can_register' );
        if( !$can ){
            return new \WP_Error('cant-trash', '当前站点未开放注册', ['status' => 500]);
        }
        $log  = sanitize_user( $request['log'] );
        $pwd  = sanitize_text_field( $request['pwd'] );
        $email  = sanitize_email( $request['email'] );
        
        if( !$log || !$pwd ){
            return new \WP_Error('cant-trash', '用户名或密码不能为空', ['status' => 500]);
        }
        if( !$email ){
            return new \WP_Error('cant-trash', '请填写正确的邮箱地址', ['status' => 500]);
        }

        $userdata=array(
            'user_login' => $log,
            'display_name' => $log,
            'nickname' => $log,
            'user_pass' => $pwd,
            'first_name' => $log,
            'user_email' => $email
        );
        $user_id = wp_insert_user( $userdata );

        if ( is_wp_error( $user_id ) ) {
            $errors = $user_id->errors;
            $emsg = '';
            foreach($errors as $error){
                $emsg = $error[0];
            }
            return new \WP_Error('cant-trash', $emsg, ['status' => 500]);
        }
        return rest_ensure_response(['success'=>true]);
    }

    public function user_login(\WP_REST_Request $request){
        
        $log  = sanitize_user( $request['log'] );
        $pwd  = sanitize_text_field( $request['pwd'] );
        
        if( !$log || !$pwd ){
            return new \WP_Error('cant-trash', '用户名或密码不能为空', ['status' => 500]);
        }

        $user = wp_signon(['user_login'=>$log,'user_password'=>$pwd,'remember'=>true]);
        if ( is_wp_error( $user ) ) {
            $errors = $user->errors;
            $emsg = '';
            foreach($errors as $error){
                $emsg = $error[0];
            }
            return new \WP_Error('cant-trash', $emsg, ['status' => 500]);
        }
        return rest_ensure_response(['success'=>true]);
    }
    public function user_info(\WP_REST_Request $request){
        $user = wp_get_current_user();
        if( !$user ){
            return new \WP_Error('cant-trash', __('Login first, please.', 'mine-cloudvod'), ['status' => 500]);
        }
        $mcv_wechat_unionid = get_user_meta($user->ID, 'mcv_wechat_unionid', true);
        $mcv_wechat_fwh_openid = get_user_meta($user->ID, 'mcv_wechat_fwh_openid', true);
        $avatar = get_user_meta( $user->ID, 'mcv_avatar', true );
        $mcv_phone = get_user_meta( $user->ID, 'mcv_phone', true );
        $action = sanitize_text_field( $request['action']??'' );
        if( $action === 'unbind_wechat' ){
            if( $mcv_wechat_unionid ){
                delete_user_meta($user->ID, 'mcv_wechat_unionid');
                $mcv_wechat_unionid = '';
            }
            if( $mcv_wechat_fwh_openid ){
                delete_user_meta($user->ID, 'mcv_wechat_fwh_openid');
                $mcv_wechat_fwh_openid = '';
            }
        }

        $data = [
            'uid' => $user->ID,
            'user_login' => $user->user_login,
            'nickname' => $user->display_name,
            'reg_time' => $user->user_registered,
            'avatar' => $avatar,
            'phone' => $mcv_phone,
            'unionid' => $mcv_wechat_unionid?true:false,
        ];

        return rest_ensure_response(['success'=>true, 'data'=>$data]);
    }
}
