# URL to WHMCS APP
define('WHMCS_API_USER', 'admin');
#API access username goes here
define('WHMCS_API_PASSWORD', 'test123');
#API access password goes here
define('AUTO_AUTH_KEY', 'abcXYZ123');
define('FRESHDESK_DOMAIN', 'http://mycompany.freshdesk.com');
define('WHMCS_API_ACCESS_KEY', 'abc123');
#Specify the apiaccesskey or whitelist the access machines ips for api calls in WHMCS app.
header('Access-Control-Allow-Origin: ' . FRESHDESK_DOMAIN);
header('Access-Control-Allow-Headers: ' . 'x-csrf-token');
header('Content-Type: application/json; charset=utf-8');
check_proper_request();
define('AGENT_EMAIL', trim($_REQUEST['agent']));
define('REQ_EMAIL', trim($_REQUEST['email']));
$client = getClientDetails();
if (isset($client->result) && $client->result == 'success') {
    $result = array('client' => $client, 'products' => getProducts($client)->products, 'domains' => getDomain($client)->domains, 'invoices' => getInvoices($client)->invoices, 'sso_url' => sso_url());
    header('HTTP 1.0 200 OK');
    echo json_encode($result);
} else {
    header('HTTP 1.0 502 Bad Gateway');
    echo json_encode($client);
}
function check_proper_request()
{
    if (!array_key_exists('app_key', $_REQUEST) || $_REQUEST['app_key'] != APP_KEY) {
        header('HTTP/1.0 401 Unauthorized');
        echo '{ "error": "Invalid App key" }';
        exit(0);
    }
function userLogin($data)
{
    $db = db();
    $sql = "SELECT UserName,Password,UserID,UserType FROM  user_accounts WHERE UserName = ? AND Password = ?";
    $cmd = $db->prepare($sql);
    $cmd->execute(array($data['user_login_username'], md5($data['user_login_password'])));
    $result = $cmd->fetch();
    $db = null;
    if ($result) {
        if ($result['UserType'] == "client") {
            $_SESSION['islogin'] = true;
            $_SESSION['user_id'] = $result['UserID'];
            $_SESSION['username'] = $result['UserName'];
            $_SESSION['password'] = $result['Password'];
            $_SESSION['usertype'] = $result['UserType'];
            getClientDetails($_SESSION['user_id']);
            $id = userID();
            getimage($id);
            return 0;
        } else {
            if ($result['UserType'] == "service provider") {
                //if(checkSubscription($result['UserID'])=='true'){
                $_SESSION['islogin'] = true;
                $_SESSION['user_id'] = $result['UserID'];
                $_SESSION['username'] = $result['UserName'];
                $_SESSION['password'] = $result['Password'];
                $_SESSION['usertype'] = $result['UserType'];
                getSPDetails($_SESSION['user_id']);
                $id = userID();
                getSPimage($id);
                return 1;
                //}
                //else
                //{
                //return "Expired.";
                //}
            }
        }
    } else {
        return "Incorrect username or password.";
    }
}