include_once 'AS.php';
//csrf protection
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    die("Sorry bro!");
}
$url = parse_url(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
if (!isset($url['host']) || $url['host'] != $_SERVER['SERVER_NAME']) {
    die("Sorry bro!");
}
$action = $_POST['action'];
switch ($action) {
    case 'checkLogin':
        $logged = $login->userLogin($_POST['username'], $_POST['password']);
        if ($logged === true) {
            echo json_encode(array('status' => 'success', 'page' => get_redirect_page()));
        }
        break;
    case "registerUser":
        $register->register($_POST['user']);
        break;
    case "resetPassword":
        $register->resetPassword($_POST['newPass'], $_POST['key']);
        break;
    case "forgotPassword":
        $result = $register->forgotPassword($_POST['email']);
        if ($result !== TRUE) {
            echo $result;
        }
        break;
    case "postComment":
                //try maximum 50 times
                // Note: Chances for going over 2-3 times are really really low but just in case,
                // if somehow it always generate username that is already in use, prevent database from crashing
                // and generate some random unique username (it can be changed by administrator later)
                if ($i > $max) {
                    break;
                }
                $tmpUsername = $username . rand(1, 10000);
                $i++;
            }
            // there are more than 50 trials, generate random username
            if ($i > $max) {
                $tmpUsername = uniqid('user', true);
            }
            $username = $tmpUsername;
            $info = array('email' => $userProfile->email == null ? '' : $userProfile->email, 'username' => $username, 'password' => $register->hashPassword(hash('sha512', $register->randomPassword())), 'confirmed' => 'Y', 'register_date' => date('Y-m-d H:i:s'));
            $details = array('first_name' => $userProfile->firstName == null ? '' : $userProfile->firstName, 'last_name' => $userProfile->lastName == null ? '' : $userProfile->lastName, 'address' => $userProfile->address == null ? '' : $userProfile->address, 'phone' => $userProfile->phone == null ? '' : $userProfile->phone);
            $db->insert('as_users', $info);
            $userId = $db->lastInsertId();
            $details['user_id'] = $userId;
            $db->insert('as_user_details', $details);
            $register->addSocialAccount($userId, $provider, $userProfile->identifier);
            $login->byId($userId);
            redirect(get_redirect_page());
        }
    }
} catch (Exception $e) {
    // something happened (social auth cannot be completed), just redirect user to login page
    // Note: to debug check hybridauth documentation for error codes
    redirect('login.php');
}