<?php

$context = array();
$context['theme'] = get_template_directory_uri();
if (is_user_logged_in()) {
    $user = wp_get_current_user();
    user_redirect($user);
} else {
    if ($_POST) {
        $phone = $_POST['phone'];
        $password = $_POST['password'];
        if (!$phone) {
            $context['error'] = '请输入用户名';
        } else if (!$password) {
            $context['error'] = '请输入密码';
        } else {
            if (strlen($phone) != 11 && $phone != 'admin') {
                $response = wp_remote_post('http://218.1.67.130:8988/api/NanTongWechat/LoginWechat' .
                    '?userName=' . $phone . '&password=' . $password
                );
                $body = json_decode($response['body']);
                $data = $body->data;
                if ($data) {
                    $password = $data->WorkNoAndId;
                }
            }
            $creds['user_login'] = $phone;
            $creds['user_password'] = $password;
            $creds['remember'] = true;
            $user = wp_signon($creds, false);
            if (!is_wp_error($user)) {
                user_redirect($user);
            } else if ($user->get_error_code() == 'invalid_username') {
                $context['error'] = '此帐号尚未注册';
            } else if ($user->get_error_code() == 'incorrect_password') {
                $context['error'] = '您输入的密码有误';
            }
        }
    }
    Timber::render('manager.html', $context);
}

?>