<?php
class Database {
    private $host;
    private $user;
    private $pass;
    private $dbname;
    private $pdo;

	public function __construct($host, $user, $pass, $dbname) {
		$this->host = $host;
		$this->user = $user;
		$this->pass = $pass;
		$this->dbname = $dbname;
	}
	public function connect() {
		$driver_options = [
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
		];
		$dsn = "mysql:host=$this->host;dbname=$this->dbname";
		$this->pdo = new PDO($dsn, $this->user, $this->pass,$driver_options);
	}

	public function query($sql, $params = []) {
		$stmt = $this->pdo->prepare($sql);
		if ($stmt->execute($params) === true)
			return $stmt;
		return false;
	}

	public function lastInsertId(){
		return $this->pdo->lastInsertId();
	}
}

class res {
	public $id;
	public $title;
	public $done;
	public function __construct(){
		$this->done = (bool)$this->done;;
	}
}

class Todo {
	static private $db = NULL;

	public static function todo($id,$title,$done){
	return ["id"=>$id,"title"=>$title,"done"=>(bool)$done];

	}
	public static function init(){
	//TODO
		self::$db = new Database("localhost","test","test","test"); // vos parametres !!!!
		self::$db->connect();  
	}

	public static function find($id) {
		$sql = "SELECT * FROM  todo WHERE id = ?";
		$stmt  = self::$db->query($sql,[$id]);

		$stmt->setFetchMode(PDO::FETCH_CLASS, 'res');
		$result = $stmt->fetch();

		return $result;
	}

	public static function findCompleted(){
		$sql = "SELECT * FROM  todo WHERE done = '1'";
		$stmt  = self::$db->query($sql);

		$stmt->setFetchMode(PDO::FETCH_CLASS, 'res');
		$result = $stmt->fetchAll();
		return $result;
	}

	public static function findUnCompleted(){
		$sql = "SELECT * FROM  todo WHERE done = '0'";
		$stmt  = self::$db->query($sql);

		$stmt->setFetchMode(PDO::FETCH_CLASS, 'res');
		$result = $stmt->fetchAll();
		return $result;
	}

	public static function findAll() {
		$sql = "SELECT id,title, done FROM  todo";
		$stmt  = self::$db->query($sql);
		//		$result = $stmt->fetchAll(PDO::FETCH_FUNC, "Todo::todo");
			$stmt->setFetchMode(PDO::FETCH_CLASS, 'res');

		$result = $stmt->fetchAll();
		return $result;
	}

	public static function update($todo){

		$sql = "UPDATE todo SET title = ?, done = ? WHERE id = ?";
		$stmt  = self::$db->query($sql,[$todo['title'],(int)$todo['done'],$todo['id']]);
	}

	public static function create($todo){

		$sql = "INSERT INTO todo (title, done) VALUES (?, ?)";
		$stmt  = self::$db->query($sql,[$todo['title'],(int)$todo['done']]);
		return self::$db->lastInsertId();
	}

	public static function delete($id){
		$sql = "DELETE FROM todo WHERE id=?";
		$stmt  = self::$db->query($sql,[$id]);
	}
}

