<?php

require_once __DIR__ .'/../init_cloud.php';

$inputRules = [
    "email" => ["required" => true, "validate" => ["filter" => FILTER_VALIDATE_EMAIL]],
    "password" => ["required" => true, "validate" => []],
];

$error = [];

if (__RB_validateInput($inputRules, 'login', $error)) {
    $json = "";

    if (__RB_api_cloud(__RB_API_ACTION_CLOUD_LOGIN, $_POST, $json)) {
        $_SESSION['id'] = $json['data']['id'];
        $_SESSION['status'] = $json['data']['status'];
        //$_SESSION['lng'] = $json['data']['lng'];
        $_SESSION['address'] = $json['data']['address'];
        $_SESSION['transactions'] = $json['data']['transactions'];
        $_SESSION['product'] = $json['data']['product'];
        $_SESSION['lotteries'] = $json['data']['lotteries'];
        $_SESSION['signed_in'] = true;

        //$__RB_success['login'] = true;
        $response = ["status" => 'success'];

        echo json_encode($response);

        exit;

    } else {
        if ($json && is_array($json) && !empty($json['code'])) {
            switch ($json['code']) {
                case 1001:
                case 1004:
                    $errorMsg = $__RB_LNG['error']['form']['login']['incorrect'];

                    break;

                case 1002:
                    $errorMsg = $__RB_LNG['error']['form']['login']['disabled_user'];

                    break;
                
                default: $errorMsg = "Process error";
            }

            $response = [
                'status' => 'failed',
                'errors' => [[
                    'type' => 'validation',
                    'code' => $json['code'],
                    'message' => $json['code'] <= 1 ? 'Process error' : $errorMsg
                ]]
            ];
        
            echo json_encode($response);
        
            exit;

        } else {
            $response = [
                'status' => 'failed',
                'errors' => [[
                    'type' => 'validation',
                    'code' => PROCESS_ERROR,
                    'message' => $json['code'] <= 1 ? 'Process error' : $errorMsg
                ]]
            ];
        
            echo json_encode($response);
        
            exit;
        }
    }

} else {
    $response = [
        'status' => 'failed',
        'errors' => $error
    ];

    echo json_encode($response);

    exit;
}
