<?php
class Database {
    private $_handler;
 
    public function __construct($host = "localhost", $username = "root", $password = "0308Martinez", $database = "rest")
    {
        Try {
            $this->_handler = new PDO('mysql:host=' . $host . ';dbname=' . $database, $username, $password);
            $this->_handler->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $this->_handler->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        }
        Catch (Exception $e) {
            throw new Exception('Database connection error :' . $e->getMessage());
        }
    }
    
    private function query($sql, ...$args)
    {
        //$this->_logger->writeLog(Logger::DEBUG, 'Processing request : ' . $sql);
        $request = $this->_handler->prepare($sql);
        if($request ==! false) {
            if($request->execute($args))
            {
                $resultArray = $request->fetchAll();
                $request->closeCursor();
                return $resultArray;
            }
            else {
                return null;
            }
        } else {
            return null;
        }
    }
    
    private function execute($sql, ...$args)
    {
        //$this->_logger->writeLog(Logger::DEBUG, 'Processing request : ' . $sql);
        $request = $this->_handler->prepare($sql);
        if($request ==! false) {
            if($request->execute($args))
            {
                return true;
            }
            else {
                return false;
            }
        } else {
            return false;
        }
    }
    
    public function insererCarnet($nom, $prenom)
    {
        return $this->execute('INSERT INTO carnet (nom, prenom) VALUES (?, ?)', $nom, $prenom);
    }
    
    public function getCarnet($id = 0)
    {
        if($id == 0)
        {
            return $this->query('SELECT * FROM carnet');
        }
        else {
            return $this->query('SELECT * FROM carnet WHERE id = ?', $id);
        }
    }
    
    public function deleteCarnet($id)
    {
        return $this->execute('DELETE FROM carnet WHERE id = ?', $id);
    }
    
    public function updateCarnet($id, $nom, $prenom)
    {
        return $this->execute('UPDATE carnet SET nom = ?, prenom = ? WHERE id = ?', $nom, $prenom, $id);
    }
    
}