<?php
include_once('./_common.php');
include_once(G5_LIB_PATH.'/login_guard.lib.php');

header('Content-Type: application/json; charset=utf-8');

function layer_login_json($ok, $message, $extra = array()) {
    $payload = array_merge(array(
        'ok' => (bool)$ok,
        'message' => (string)$message,
    ), $extra);

    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

$login_guard_state = login_guard_get_state();
$captcha_required = login_guard_is_captcha_required($login_guard_state);
$captcha_image_url = G5_CAPTCHA_URL.'/kcaptcha_image.php?t='.time();
$captcha_session_url = G5_CAPTCHA_URL.'/kcaptcha_session.php';

if ($is_member) {
    layer_login_json(true, '이미 로그인 상태입니다.', array(
        'remaining_attempts' => login_guard_get_remaining_attempts($login_guard_state),
        'captcha_required' => $captcha_required,
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

$mb_id_input = trim(isset($_POST['mb_id']) ? $_POST['mb_id'] : '');
$mb_password = trim(isset($_POST['mb_password']) ? $_POST['mb_password'] : '');
$captcha_key = trim(isset($_POST['captcha_key']) ? $_POST['captcha_key'] : '');
$auto_login = isset($_POST['auto_login']) && $_POST['auto_login'];

if ($captcha_required) {
    if (!login_guard_verify_captcha_input($captcha_key)) {
        layer_login_json(false, "로그인 실패가 누적되어 자동등록방지 숫자 입력이 필요합니다.\n자동등록방지 숫자를 확인 후 다시 입력해 주세요.", array(
            'remaining_attempts' => 0,
            'locked' => true,
            'captcha_required' => true,
            'captcha_image_url' => $captcha_image_url,
            'captcha_session_url' => $captcha_session_url,
            'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
        ));
    }
}

if ($mb_id_input === '' || $mb_password === '') {
    layer_login_json(false, '회원아이디 또는 비밀번호를 입력해 주세요.', array(
        'remaining_attempts' => login_guard_get_remaining_attempts($login_guard_state),
        'captcha_required' => $captcha_required,
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

$mb = get_member($mb_id_input);
if (!$mb['mb_id']) {
    $mb = sql_fetch(" select * from {$g5['member_table']} where mb_email = '{$mb_id_input}' ");
}

if (!$mb['mb_id'] || !login_password_check($mb, $mb_password, $mb['mb_password'])) {
    $login_guard_state = login_guard_record_failure($login_guard_state);
    $locked = login_guard_is_captcha_required($login_guard_state);
    $remaining = login_guard_get_remaining_attempts($login_guard_state);
    $message = $locked
        ? "로그인 실패가 5회 누적되어 자동등록방지 숫자 입력이 필요합니다.\n(30분 후 자동 해제)"
        : '로그인에 실패했습니다. 아이디 또는 비밀번호를 확인해 주세요.';

    layer_login_json(false, $message, array(
        'remaining_attempts' => $remaining,
        'locked' => $locked,
        'captcha_required' => $locked,
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

if ($mb['mb_intercept_date'] && $mb['mb_intercept_date'] <= date("Ymd", G5_SERVER_TIME)) {
    layer_login_json(false, '접근이 금지된 계정입니다.', array(
        'remaining_attempts' => login_guard_get_remaining_attempts($login_guard_state),
        'captcha_required' => login_guard_is_captcha_required($login_guard_state),
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

if ($mb['mb_leave_date'] && $mb['mb_leave_date'] <= date("Ymd", G5_SERVER_TIME)) {
    layer_login_json(false, '탈퇴한 계정입니다.', array(
        'remaining_attempts' => login_guard_get_remaining_attempts($login_guard_state),
        'captcha_required' => login_guard_is_captcha_required($login_guard_state),
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

if (is_use_email_certify() && !preg_match('/[1-9]/', $mb['mb_email_certify'])) {
    layer_login_json(false, '메일인증 후 로그인할 수 있습니다. 일반 로그인 페이지에서 인증을 진행해 주세요.', array(
        'remaining_attempts' => login_guard_get_remaining_attempts($login_guard_state),
        'captcha_required' => login_guard_is_captcha_required($login_guard_state),
        'captcha_image_url' => $captcha_image_url,
        'captcha_session_url' => $captcha_session_url,
        'lock_seconds' => login_guard_get_remaining_lock_seconds($login_guard_state)
    ));
}

set_session('ss_mb_id', $mb['mb_id']);
set_session('ss_mb_key', md5($mb['mb_datetime'] . get_real_client_ip() . $_SERVER['HTTP_USER_AGENT']));
if (function_exists('update_auth_session_token')) {
    update_auth_session_token($mb['mb_datetime']);
}

if ($config['cf_use_point']) {
    $sum_point = get_point_sum($mb['mb_id']);
    sql_query(" update {$g5['member_table']} set mb_point = '{$sum_point}' where mb_id = '{$mb['mb_id']}' ");
}

if ($auto_login) {
    $key = md5($_SERVER['SERVER_ADDR'] . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $mb['mb_password']);
    set_cookie('ck_mb_id', $mb['mb_id'], 86400 * 31);
    set_cookie('ck_auto', $key, 86400 * 31);
} else {
    set_cookie('ck_mb_id', '', 0);
    set_cookie('ck_auto', '', 0);
}

if (defined('G5_USE_SHOP') && G5_USE_SHOP && function_exists('set_cart_id')) {
    $member = $mb;
    cart_item_clean();
    set_cart_id('');
    $s_cart_id = get_session('ss_cart_id');
    $sql = " update {$g5['g5_shop_cart_table']} set ct_select = '0' where od_id = '{$s_cart_id}' ";
    sql_query($sql);
}

login_guard_record_success();

layer_login_json(true, '로그인에 성공했습니다.', array(
    'remaining_attempts' => LOGIN_GUARD_FAIL_LIMIT,
    'locked' => false,
    'captcha_required' => false,
    'captcha_image_url' => $captcha_image_url,
    'captcha_session_url' => $captcha_session_url,
    'lock_seconds' => 0,
    'mb_id' => $mb['mb_id']
));
