<?php 

class Korisnik{

    private $con;

    public function __construct($db){
		$this->con = $db;
    }

    public function login($data){
        $sql = "SELECT id_user, password FROM user WHERE username = '{$data["username"]}'";
        $result=mysqli_query($this->con,$sql);
        if(mysqli_num_rows($result)==0){
            return 0; 
        }else{
            $row = mysqli_fetch_assoc($result);
            if(password_verify($data["password"], $row["password"])){
                $id = $row["id_user"];
                // sends to c# script into www.text
                return $id;
            }else{
                return "-1"; 
            }
        }
    }

   public function register($data){
        $data["password"] = password_hash(mysqli_escape_string($this->con,$_POST["password"]), PASSWORD_DEFAULT);

        // Check if name exists
        $sql = "SELECT id_user FROM user WHERE username ='{$data["username"]}'";
        $result = mysqli_query($this->con, $sql); 
        if(mysqli_num_rows($result)!=0){
            return 0; 
        }else{
            $sql = "INSERT into user set 
            username = '{$data["username"]}',
            password = '{$data["password"]}'";
            
            $result=mysqli_query($this->con,$sql);
            $id = mysqli_insert_id($this->con); 
            $id == 0 ?  0 : $id;
            return $id;
        }
    }

    public function readProfile($id){
        $sql = "SELECT username, experience, level FROM user
        WHERE id_user = '$id'"; 
        $result = mysqli_query($this->con, $sql); 
        $row = mysqli_fetch_assoc($result);
        $data = array(); 
        $data = $row;  
        return $data; 
    }

    public function changePassword($data, $id){
        $data["password"] = password_hash(mysqli_escape_string($this->con,$_POST["password"]), PASSWORD_DEFAULT);
        $sql = "UPDATE user SET password = '{$data["password"]}' WHERE id_user='$id';"; 
        if(mysqli_query($this->con, $sql) === TRUE){
            return 1;
        }else{
            return 0;
        }
    }

}

?>