<?php
// 'user' object
class User{
 
    // database connection and table name
    private $conn;
    private $table_name = "AppUsers";
 
    // object properties
    public $id;
	public $email;
    public $name;
    public $surname;
    public $celnr;
    public $password;
	
 
    // constructor
    public function __construct($db){
        $this->conn = $db;
    }
 
// create new user record
function create(){

 
    // insert query
    $query = "INSERT INTO `AppUsers`SET ( `email`, `name`, `surname`, `celnr`, `password`) VALUES (:email,:name,:surname,:celnr,:password)";
				

    // prepare the query
    $stmt = $this->conn->prepare($query);
 
    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->surname=htmlspecialchars(strip_tags($this->surname));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->celnr=htmlspecialchars(strip_tags($this->celnr));
    $this->password=htmlspecialchars(strip_tags($this->password));
 
    // bind the values
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':surname', $this->surname);
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':celnr', $this->celnr);
 
    // hash the password before saving to database
    $password_hash = password_hash($this->password, PASSWORD_BCRYPT);
    
    $stmt->bindParam(':password', $password_hash);

    if($stmt->execute()){
        return "true";
    }


    // execute the query, also check if query was successful
   // if($stmt->execute()){
   //     return true;
   // }
 
    return "false";
}
 
// check if given email exist in the database
function emailExists(){
 
    // query to check if email exists
    $query = "SELECT id, name, surname,celnr, password
            FROM " . $this->table_name . "
            WHERE email = ?
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));
 
    // bind given email value
    $stmt->bindParam(1, $this->email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
        $this->name = $row['name'];
        $this->surname = $row['surname'];
        $this->celnr = $row['celnr'];
        $this->password = $row['password'];
 
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
}
 
// update() method will be here
}