<?php
require_once('_conf/globals.php');
require_once('_conf/db_con.php');
$postData = file_get_contents('php://input');
$postData = json_decode($postData);
// Allowed genders
$allowed_genders = array('male', 'female', 'other');

// Register
if($postData){
    $postAction = $postData->action;
}else{
    $postAction = 'Custom';
}
if($postAction === 'signup'){
    $userData = $postData->userData;
    $response = new stdClass();
    require_once('users_class.php');
    
    // Fetch countries
    $url = 'https://restcountries.com/v3.1/all?fields=name';
    $pre_countries = file_get_contents($url);
    if ($pre_countries !== null) {
        $pre_countries = json_decode($pre_countries, true);
        $countries = array_map(function ($country) {
            return $country['name']['common'];
        }, $pre_countries);
    }

    // Validate

    if(!isset($userData->country) || empty($userData->country)){
        $response->status = 'fail';
        $response->fail_status =  'country';
        $response->message = 'You need to select a country';
        echo json_encode($response);
        exit();
    }

    if(!in_array($userData->country, $countries)){
        $response->status = 'fail';
        $response->fail_status =  'country';
        $response->message = 'Invalid country';
        echo json_encode($response);
        exit();
    }


    if(!$userData->acceptTerms){
        $response->status = 'fail';
        $response->fail_status =  'tos';
        $response->message = 'You need to accept the terms of use';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->username) || empty($userData->username)){
        $response->status = 'fail';
        $response->fail_status =  'username';
        $response->message = 'Empty username';
        echo json_encode($response);
        exit();
    }

    if (strlen($userData->username) < 3) {
        $response->status = 'fail';
        $response->fail_status =  'username';
        $response->message = 'Username is too short, minimum 3 characters';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->gender) || empty($userData->gender)){
        $response->status = 'fail';
        $response->fail_status =  'gender';
        $response->message = 'Empty gender';
        echo json_encode($response);
        exit();
    }

    if(!in_array($userData->gender, $allowed_genders)){
        $response->status = 'fail';
        $response->fail_status =  'gender';
        $response->message = 'Invalid gender';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->email) || empty($userData->email)){
        $response->status = 'fail';
        $response->fail_status =  'email';
        $response->message = 'Empty email';
        echo json_encode($response);
        exit();
    }

    if (!filter_var($userData->email, FILTER_VALIDATE_EMAIL)) {
        $response->status = 'fail';
        $response->fail_status =  'email';
        $response->message = 'Invalid email';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->password) || empty($userData->password)){
        $response->status = 'fail';
        $response->fail_status =  'password';
        $response->message = 'Empty password';
        echo json_encode($response);
        exit();
    }

    if (strlen($userData->password) < 6) {
        $response->status = 'fail';
        $response->fail_status =  'password';
        $response->message = 'Password is too short, minimum 6 characters';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->password2) || empty($userData->password2)){
        $response->status = 'fail';
        $response->fail_status =  'password2';
        $response->message = 'Confirm password';
        echo json_encode($response);
        exit();
    }

    if($userData->password !== $userData->password2){
        $response->status = 'fail';
        $response->fail_status =  'passwords';
        $response->message = 'Passwords does not match';
        echo json_encode($response);
        exit();
    }

    
    // Assign information
    $_psw = password_hash($userData->password, PASSWORD_BCRYPT, ["cost" => 12]);

    $user =  new Users();
    $user->username = $userData->username;
    $user->country = $userData->country;
    $user->gender =  $userData->gender;
    $user->email = $userData->email;
    $user->password = $_psw;
    $user->dob = $userData->dob;
    
    if($user->username_exists()){
        $response->status = 'fail';
        $response->fail_status =  'username';
        $response->message = 'Username is already in use';
        echo json_encode($response);
        exit();
    }

    if($user->email_exists()){
        $response->status = 'fail';
        $response->fail_status =  'email';
        $response->message = 'Email is already in use';
        echo json_encode($response);
        exit();
    }

    $user->register();
}

// Login
if($postAction === 'login'){
    $userData = $postData->userData;
    $response = new stdClass();
    require_once('users_class.php');
    $user =  new Users();
    if($user->isAuth()){
        $response->status = 'error';
        $response->fail_status =  'login';
        $response->message = 'Already logged in';
        echo json_encode($response);
        exit();
    }
    $user->username = $userData->username;
    $user->password = $userData->password;

    if(!isset($userData->username) || empty($userData->username)){
        $response->status = 'fail';
        $response->fail_status =  'username';
        $response->message = 'Fill out your username';
        echo json_encode($response);
        exit();
    }

    if(!isset($userData->password) || empty($userData->password)){
        $response->status = 'fail';
        $response->fail_status =  'password';
        $response->message = 'Fill out your password';
        echo json_encode($response);
        exit();
    }

    $userInfo = $user->login();
    if($userInfo){
        if(password_verify($user->password, $userInfo['psw'])){
            $session_code = $user->setLogin($userInfo['id']);
            setcookie('authCookie', $session_code, time() + (10 * 365 * 24 * 60 * 60));
            setcookie('authId', $userInfo['id'], time() + (10 * 365 * 24 * 60 * 60));

            $response->status = 'success';
            $response->fail_status =  'login';
            $response->message = 'Login success';
            echo json_encode($response);
            exit();
        }else{
            $response->status = 'fail';
            $response->fail_status =  'password';
            $response->message = 'Incorrect password';
            echo json_encode($response);
            exit();
        }
    }else{
        $response->status = 'fail';
        $response->fail_status =  'username';
        $response->message = 'Incorrect details';
        echo json_encode($response);
        exit();
    }
}
if ($postAction === 'updateUserSettings') {
    $uSettings = $postData->settings;
    require_once('users_class.php');
    $user = new Users();
    if($user->isAuth()){
        foreach ($uSettings as $setting => $value) {
            if ($user->allowedSetting($setting)) {
                if (isset($value) && !empty($value)) {
                    $user->update_user_data($setting, $value, $_COOKIE['authId']);
                }
            }
        }
    }
}

if (isset($_GET['getUserSettings']) && $_GET['getUserSettings'] == true){
    require_once('users_class.php');
    $user = new Users();
    if($user->isAuth()){
        $userSettings = $user->initUserSettings();
        echo $userSettings;
    }
}

if(isset($_GET['isAuth']) && $_GET['isAuth'] == true){
    require_once('users_class.php');
    $user = new Users();
    if($user->isAuth()){
        $response = new stdClass();
        $response->status = true;
        echo json_encode($response);
    }else{
        if(isset($_COOKIE['authId'])){
            $user->logout();
        }
        $response = new stdClass();
        $response->status = false;
        echo json_encode($response);
    }
}

if(isset($_GET['logout']) && $_GET['logout'] == 'true'){
	setcookie('authCookie','', time() - 3600);
	setcookie('authId', '', time() - 3600);
    require_once('users_class.php');
    $user = new Users();
    $user->logout();
}

if(isset($_POST['action']) && $_POST['action'] == 'updatePublicProfile'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK){
            $avatar_temp = $_FILES['avatar']['tmp_name'];
            $avatar_name = $_FILES['avatar']['name'];
            $avatar_size = $_FILES['avatar']['size'];
            $fileExtension = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
            $avatar_content = file_get_contents($avatar_temp);
    
            $users->updateAvatar($avatar_temp, $fileExtension);
        }

        if(isset($_FILES['banner']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK){
            $banner_temp = $_FILES['banner']['tmp_name'];
            $banner_name = $_FILES['banner']['name'];
            $banner_size = $_FILES['banner']['size'];
            $fileExtension = strtolower(pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION));
            $banner_content = file_get_contents($banner_temp);
    
            $users->updateBanner($banner_temp, $fileExtension);
        }
    
        if(isset($_POST['bio']) && !empty($_POST['bio'])){
            $bio = htmlspecialchars($_POST['bio']);
            $users->updateBio($bio);
        }
    }
}
if($postAction == 'userInit'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        $userData = $users->initUser();
        echo $userData;
    }
}

if($postAction == 'getUser'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        if($users->hasPaid()){
            $userId = intval($postData->userId);
            $userData = $users->getUser($userId);
            echo $userData;
        }
    }
}

if(isset($_POST['action']) && $_POST['action'] == 'uploadGalleryImage'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        if(isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK){
            $image_temp = $_FILES['image']['tmp_name'];
            $image_name = $_FILES['image']['name'];
            $image_size = $_FILES['image']['size'];
            $fileExtension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $image_content = file_get_contents($image_temp);
    
            $users->uploadGalleryImage($image_temp, $fileExtension);
        }
    }
}

if($postAction == 'deleteImage'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        if($users->hasPaid()){
            $users->deleteImage($postData->image);
        }
    }
}

if($postAction == 'getMessages'){
    require_once('users_class.php');
    $users = new Users();
    $user_id = $postData->user_id;
    if($users->isAuth()){
        if($users->hasPaid()){
            $messages = $users->receive_messages($user_id);
            echo $messages;
        }
    }
}

if($postAction == 'sendMessage'){
    require_once('users_class.php');
    $users = new Users();
    $user_id = $postData->user_id;
    $message = $postData->newMessage;

    if($users->isAuth()){
        if($users->hasPaid()){
            $users->sendMessage($user_id, $message);
            $messages = $users->receive_messages($user_id);
            echo $messages;
        }
    }
}

if($postAction == 'getConversations'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        if($users->hasPaid()){
            $conversations = $users->get_conversations();
            echo $conversations;
        }
    }
}

if($postAction == 'unread'){
    require_once('users_class.php');
    $users = new Users();

    if($users->isAuth()){
        $status = $users->checkUnread();
        echo $status;
    }
}


if($postAction == 'updatePassword'){
    require_once('users_class.php');
    $users = new Users();
    if($users->isAuth()){
        $status = $users->updatePassword($postData->currPass, $postData->newPass, $postData->confPass);
        echo $status;
    }
}

if($postAction == 'isPaid'){
    require_once('users_class.php');
    $user = new Users();
    if($user->isAuth()){
        $status = $user->hasPaid();
        $response = new stdClass();
        $response->status = $status;
        echo json_encode($response);
    }
}
