<?php

require_once('const.php');
$context = array();
$context['theme'] = get_template_directory_uri();
$context['register'] = $const_register_page;
$context['forget'] = $const_forget_page;
if (is_user_logged_in()) {
    wp_redirect($const_my_page);
} else {
    if ($_POST) {
        $phone = $_POST['phone'];
        $password = $_POST['password'];
        if (!$phone) {
            $context['error'] = '请输入用户名';
        } else if (!$password) {
            $context['error'] = '请输入密码';
        } else {
            if (strlen($phone) != 11) {
                $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)) {
                wp_redirect($const_my_page);
            } else if ($user->get_error_code() == 'invalid_username') {
                $context['error'] = '请输入有效的用户名';
            } else if ($user->get_error_code() == 'incorrect_password') {
                $context['error'] = '您输入的密码无效';
            }
        }
    }
}
Timber::render('login.html', $context);

?>