<?php
/**
 * users.php - Processes Actions for Users
 * 
 * API requests sent here from js/users.js
 * 
 *  */
// Set Header
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include '../inc/config.inc.php';

$out = array('error' => false);

$crud = 'read';

if ( isset($_GET['crud']) ){
	$crud = $_GET['crud'];
}



// 1.2. User Login [for Admin & Users]
if ( $crud == 'userlogin' ){
	$username_email = strip_tags(stripslashes($_POST['username_email']));
	$password = strip_tags($_POST['password']);
	$last_login = date('Y-m-d H:i:s');
	
	try
	{
        //if ( $username == 'admin' OR $username == 'superadmin' ){ // Admin
        if ( $username_email == 'admin' OR $username_email == 'superadmin' ){ // Admin
            //$stmt = $db_con->prepare("SELECT * FROM admin WHERE username=:username");
            //$stmt->execute(array(":username"=>$username));
            $stmt = $db_con->prepare("SELECT * FROM admin WHERE username=:username");
            $stmt->execute(array(":username"=>$username_email));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
                
            if ( $stmt->rowCount() > 0 ){
                if ( password_verify($password, $row['password']) ){
                    // 1. Successful Login
                    $query = $db_con->prepare("UPDATE admin SET last_login='$last_login' WHERE id='".$row['id']."'");
                    $query->execute();
                    
                    session_start(); // Start Session
                    $_SESSION["loggedin"] = true;
                    $_SESSION['admin'] = $row['id'];

                    $out['error'] = false;
                    $out['role'] = 'admin'; // Role: Admin
                    $out['notice'] = 'successful'; // Notice
                    $out['message'] = 'Login Successful. Thank you!'; // Message
                } else {
                    // 2. Wrong Password
                    $out['error'] = true;
                    $out['role'] = 'admin'; // Role: Admin
                    $out['notice'] = 'no_match'; // Notice
                    $out['message'] = 'Login Failed. Username or Password is wrong!'; // Message
                }
            } else {
                // 3. Error Occured or Account Not Found
                $out['error'] = true;
                $out['role'] = 'admin'; // Role: Admin
                $out['notice'] = 'not_found'; // Notice
                $out['message1'] = 'Account Not Found!'; // Message
                $out['message2'] = $stmt->errorCode(); // Message
            }
            unset($stmt);
        }
        else { // User
            //$stmt = $db_con->prepare("SELECT * FROM users WHERE username=:username");
            //$stmt->execute(array(":username"=>$username));
            $stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
            $stmt->execute(array(":email"=>$username_email));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            $out['error_die'] = 'After Try{}';
                
            if ( $stmt->rowCount() > 0 ){
                $out['error_die'] = 'It exists';

                if ( password_verify($password, $row['password']) ){
                    $out['error_die'] = 'Password Matches';

                    if ( $row['verified'] == 'No' ){
                        // 1. Has User Verified Account?
                        $out['error'] = false;
                        $out['role'] = 'user'; // Role: User
                        $out['notice'] = 'verify'; // Notice
                        $out['message'] = 'Account Has Not Been Verified. Check your Email: <br>( '.$row['email'].' )'; // Message
                    } else {
                        if ( $row['activate'] == 'deactivate' ){
// 1. Has User Verified Account?
$out['error'] = true;
$out['role'] = 'user'; // Role: User
$out['notice'] = 'no_match'; // Notice
$out['message'] = 'Account Has Been Deactivated. Kindly Contact Customer Care <br> (support@criptohopper.live)'; // Message
} else {
                        // 2. Successful Login
                        $query = $db_con->prepare("UPDATE users SET last_login='$last_login', online_status='online' WHERE id='".$row['id']."'");
                        $query->execute();
                        
                        session_start(); // Start Session
                        $_SESSION["loggedin"] = true;
                        $_SESSION['user'] = $row['id'];

                        $out['error'] = false;
                        $out['role'] = 'user'; // Role: User
                        $out['notice'] = 'successful'; // Notice
                        $out['message'] = 'Login Successful. Thank you!'; // Message
                    }
                    }
                } else {
                    // 3. Wrong Password
                    $out['error'] = true;
                    $out['role'] = 'user'; // Role: User
                    $out['notice'] = 'no_match'; // Notice
                    //$out['message'] = 'Login Failed. Username or Password is wrong!'; // Message
                    $out['message'] = 'Login Failed. Username/Email or Password is wrong!'; // Message
                }
            } else {
                // 4. Error Occured or Account Not Found
                $out['error'] = true;
                $out['role'] = 'user'; // Role: User
                $out['notice'] = 'not_found'; // Notice
                $out['message1'] = 'Account Not Found!'; // Message
                $out['message2'] = $stmt->errorCode(); // Message
            }
            unset($stmt);
        }
	}
	catch(PDOException $e){
		echo $e->getMessage();
	}
	$db_con = null;
	unset($db_con);
}



// 2.2. Save New User
if ( $crud == 'newuser' ){
	$fullname = strip_tags(stripslashes($_POST['fullname']));
    $username = strip_tags(stripslashes($_POST['username']));
    $home_address = strip_tags(stripslashes($_POST['home_address']));
    $city = strip_tags(stripslashes($_POST['city']));
    $postal_code = strip_tags(stripslashes($_POST['postal_code']));
    $country = strip_tags(stripslashes($_POST['country']));
    $currency = strip_tags(stripslashes($_POST['currency']));
	$phone = strip_tags(stripslashes($_POST['phone']));
    $email = strip_tags(stripslashes($_POST['email']));
    
	$password_plain = strip_tags($_POST['password']);
    $passwordhash = password_hash($password_plain, PASSWORD_DEFAULT); // hash password

    $created = date('Y-m-d H:i:s');

    // Confirmation Code = Fullname (3) + Username (4) + Email (3)
    $ver_code = codeGen( substr($fullname,3,3), substr($username,2,4), substr($email,0,3) );
    //$ver_code = codeGen();

    try
    {
        $stmt = $db_con->prepare("SELECT * FROM users WHERE username=:username AND email=:email");
        $stmt->execute(array(":username"=>$username, ":email"=>$email));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ( $stmt->rowCount() > 0 ){
            // 1. Username or Email Exists
            if ( $row['username'] == $username ){
                // 1.1. Username Exists
                $out['error'] = true;
                $out['notice'] = 'exists'; // Notice
                $out['field'] = 'username'; // Field
                $out['message'] = 'Username Already Exists!'; // Message
            }
            elseif ( $row['email'] == $email ){
                // 1.2. Email Exists
                $out['error'] = true;
                $out['notice'] = 'exists'; // Notice
                $out['field'] = 'email'; // Field
                $out['message'] = 'Email Already Exists!'; // Message
            }
        }
        else {
            // 2. Sign Up User
           $query = "INSERT INTO users(username, password, password_plain, email, fullname, home_address, city, postal_code, country, currency, phone, ver_code, activate, message_on, message_heading,message_billing, created)VALUES(:username, :password, :password_plain, :email, :fullname,:home_address, :city, :postal_code, :country, :currency, :phone, :ver_code, 'activate', 'No','', '', :created)";$stmt = $db_con->prepare($query);$stmt->execute([  ':username' => $username, ':password' => $passwordhash,':password_plain' => $password_plain,':email' => $email, ':fullname' => $fullname, ':home_address' => $home_address, ':city' => $city,':postal_code' => $postal_code,':country' => $country,':currency' => $currency,':phone' => $phone, ':ver_code' => $ver_code, ':created' => $created]);

$user_id = $db_con->lastInsertId();

            if ($stmt->rowCount() > 0) {
                // 2.1. Sign Up Successful
                $user_id = $db_con->lastInsertId();

                $active_deposit = "INSERT INTO user_active_deposit(user_id) VALUES ('$user_id')";
                $db_con->exec($active_deposit);

                $last_deposit = "INSERT INTO user_last_deposit(user_id) VALUES ('$user_id')";
                $db_con->exec($last_deposit);
                
                $last_withdrawal = "INSERT INTO user_last_withdrawal(user_id) VALUES ('$user_id')";
                $db_con->exec($last_withdrawal);

                $pending_withdraw = "INSERT INTO user_pending_withdraw(user_id) VALUES ('$user_id')";
                $db_con->exec($pending_withdraw);

                $profit_lost = "INSERT INTO user_profit_lost(user_id) VALUES ('$user_id')";
                $db_con->exec($profit_lost);

                $total_balance = "INSERT INTO user_total_balance(user_id) VALUES ('$user_id')";
                $db_con->exec($total_balance);

                $total_deposit = "INSERT INTO user_total_deposit(user_id) VALUES ('$user_id')";
                $db_con->exec($total_deposit);

                $total_earning = "INSERT INTO user_total_earning(user_id) VALUES ('$user_id')";
                $db_con->exec($total_earning);

                $total_withdrawal = "INSERT INTO user_total_withdrawal(user_id) VALUES ('$user_id')";
                $db_con->exec($total_withdrawal);

                $trade_session = "INSERT INTO user_trade_session(user_id) VALUES ('$user_id')";
                $db_con->exec($trade_session);

                //$transactions = "INSERT INTO user_transactions(user_id) VALUES ('$user_id')";
                //$db_con->exec($transactions);

                // Send Email Verification
                //ConfirmEmail($noreplyEmail, $BASE_URL, $email, $fullname, $ver_code, $db_con->lastInsertId());
                ConfirmEmail($noreplyEmail, $BASE_URL, $email, $fullname, $ver_code, $user_id);

                $out['error'] = false;
                $out['notice'] = 'successful'; // Notice
                $out['message'] = 'Signed Up Successfully.'; // Message
                $out['mailsent'] = 'Mail Sent!';
            } else {
                // 2.2. Something Went Wrong
                $out['error'] = true;
                $out['notice'] = 'wrong'; // Notice
                $out['message'] = 'Sorry! Something Went Wrong.<br>Try again.'; // Message
            }
        }
        unset($stmt);
    }
    catch(PDOException $e){
		echo $e->getMessage();
	}
	$db_con = null;
    unset($db_con);
}
// 2.3. Verify Account = Ver Code
if ( $crud == 'verifyuser' ){
    $user_id = strip_tags(stripslashes($_POST['user_id']));
    $ver_code = strip_tags($_POST['ver_code']);
    $created = date('Y-m-d H:i:s');

    try
    {
        $stmt = $db_con->prepare("SELECT * FROM users WHERE id=:user_id");
        $stmt->execute(array(":user_id"=>$user_id));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ( $stmt->rowCount() > 0 ){
            if ( $row['verified'] == 'No' ){
                if ( $row['ver_code'] == $ver_code ){
                    // 1. Verified
                    $query = $db_con->prepare("UPDATE users SET verified='Yes' WHERE id='$user_id' AND email='".$row['email']."'");
                    $query->execute();

                    $out['error'] = false;
                    $out['notice'] = 'successful'; // Notife
                    $out['message'] = 'Your Account Has Been Verified!'; // Message

                    // Send Welcome Email
                    $email = $row['email'];
                    $fullname = $row['fullname'];
                    $username = $row['username'];
                    $password_plain = $row['password_plain'];
                    $created_date = date('Y-m-d', strtotime($row['created']));
                    
                    WelcomeToASN($noreplyEmail, $BASE_URL, $email, $fullname, $username, $password_plain, $created_date);
                } else {
                    // 2. Wrong VerCode
                    $out['error'] = true;
                    $out['notice'] = 'wrong'; // Notice
                    $out['message'] = 'Incorrect Verification Code.<br>Check your email and try again!'; // Message
                }
            } else {
                // 3. Already Verified
                $out['error'] = true;
                $out['notice'] = 'wrong'; // Notice
                $out['message'] = 'This account has already been verified.<br><br>Kindly login!'; // Message
            }
        } else {
            // 4. Error - Account Not Found
            $out['error'] = true;
            $out['notice'] = 'noaccount'; // Notice
            $out['message'] = 'Account Not Found!'; // Message
        }
        unset($stmt);
    }
    catch(PDOException $e){
		echo $e->getMessage();
	}
	$db_con = null;
    unset($db_con);
}



header("Content-type: application/json");
echo json_encode($out);
die();