<?php
class User {
// Contributed by qzip! remove if noob.

    private $con, $sqlData;

    public function __construct($con, $id) {
	 $query = $con->prepare('SELECT * FROM users WHERE id=:id');
	 $query->bindParam(':id', $id);
     $query->execute();
	 $this->con = $con;
     $this->sqlData = $query->fetch(PDO::FETCH_ASSOC);
    }

    public function isLoggedIn() {
		if(isset($_SESSION["user"])) {
			$q = $this->con->prepare("SELECT * FROM users WHERE id = :id");
			$q->bindParam(':id',$_SESSION["user"],PDO::PARAM_INT);
			$q->execute();
			$usr = $q->fetch();
			if(!$usr) {
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
    }
	
	public function getMoney($short) {
	    if ($short == "true") {
        $money = $this->sqlData["money"];
		
		if ($money < 1000000) {
         // Anything less than a million
         return number_format($money);
        } else if ($money < 1000000000) {
         // Anything less than a billion
         return number_format($money / 1000000, 1) . 'M';
        } else {
         // At least a billion
         return number_format($money / 1000000000, 1) . 'B';
        
		}
		} else {
		return $this->sqlData["money"];
		}
    }
	
	public function getID($con, $username) {
	    $query = $con->prepare('SELECT id FROM users WHERE username=:username');
	    $query->bindParam(':username', $username);
        $query->execute();	
        $id = $query->fetch(PDO::FETCH_ASSOC);
		if(isset($id['id'])) {
		return $id['id'];
		} else {
		return null;
		}
	}
	
	public function getUsername() {
	    return $this->sqlData["username"] ?? "Undefined";
	}
	
	public function getPassword() {
	    return $this->sqlData["password"] ?? "Undefined";
	}
	
	public function getAvatar() {
		if($this->getUsername() !== "Undefined") {
	    return "/assets/renders/user/headshot?userId=".$this->sqlData["id"];
		} else {
		return "/assets/placeholder.png";
		}
	}
	
	public function getAvatarFull() {
	    return "/assets/renders/user/fullbody?userId=".$this->sqlData["id"] ?? "/assets/placeholder2.png";
	}
	
	public function getLastPaid() {
	     return $this->sqlData["lastPaid"];
	}
	
	public function getFriends($friend = null) {
		if (isset($friend)) {
	    $query = $this->con->prepare('SELECT * FROM friends WHERE user=:user, state="approved", friend=:friend');
	    $query->bindParam(':user', $_SESSION['user']);
		$query->bindParam(':friend', $friend);
        $query->execute();	
        $final = $query->fetchAll(PDO::FETCH_ASSOC);
		if(isset($final)) {
		return $final;
		} else {
		return null;
		}
		
		} else {
	    $query = $this->con->prepare('SELECT * FROM friends WHERE user=:user AND state="approved"');
	    $query->bindParam(':user', $_SESSION['user']);
        $query->execute();	
        $final = $query->fetchAll(PDO::FETCH_ASSOC);
		if(isset($final)) {
		return $final;
		} else {
		return null;
		}
		
		}
	}
	
}