<?php
class Presence {
    
    // database connection and table name
    private $conn;
    private $table_name = "presence";
    
    // object properties
    public $id;
    public $userId;
    public $willBePresent = false;
    public $notes = null;
    public $created;
    
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    static function read($db, $uid){
        $query = "
            SELECT will_be_present, notes
            FROM presence
            WHERE user_id = :uid
            ORDER BY created DESC
            LIMIT 1";

        // prepare query statement
        $stmt = $db->prepare($query);
		$stmt->bindParam(":uid", $uid);

        // execute query
        $stmt->execute();
        
        return $stmt;
    }
    
    function create(){      
        
        $query = "INSERT INTO " . $this->table_name . "
            SET user_id=:userId, will_be_present=:willBePresent, notes=:notes";
        
        // prepare query
        $stmt = $this->conn->prepare($query);
        
        // sanitize
        $this->userId=$this->userId;
        $this->created=(new \DateTime())->format('Y-m-d H:i:s');

        
        // bind values
        $stmt->bindParam(":userId", $this->userId);
        $wbp = $this->willBePresent ? 1 : 0;
        $stmt->bindParam(":willBePresent", $wbp);
        $stmt->bindParam(":notes", $this->notes);
       
        // execute query
        if($stmt->execute()){
            return true;
        }
        return false;
        
    }
}
?>