<?php

class AuthorService {

    private $conn;
    private $table = "author";
    
    public function __construct($db) {
        $this->conn = $db;
    }

    public function add($author) {

        $query = "INSERT INTO " . $this->table . 
            " SET full_name = :full_name, 
                email = :email";
        
        $stmt = $this->conn->prepare($query);
        
        $author->full_name = htmlspecialchars(strip_tags($author->full_name));
        $author->email = htmlspecialchars(strip_tags($author->email));

        $stmt->bindParam(':full_name', $author->full_name);
        $stmt->bindParam(':email', $author->email);

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

    public function update($author) {

        $query = "UPDATE " . $this->table . 
            " SET full_name = :full_name, email = :email WHERE id = :id";
        
        $stmt = $this->conn->prepare($query);
        
        $author->full_name = htmlspecialchars(strip_tags($author->full_name));
        $author->email = htmlspecialchars(strip_tags($author->email));

        $stmt->bindParam(':full_name', $author->full_name);
        $stmt->bindParam(':email', $author->email);
        $stmt->bindParam(':id', $author->id);

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

    public function delete($author) {

        $query = "DELETE FROM " . $this->table . " WHERE id = :id";

        $stmt = $this->conn->prepare($query);
        
        $stmt->bindParam(':id', $author->id);
        
        if($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    public function list() {

        $query = "SELECT * FROM " . $this->table . " ORDER BY created_at DESC ";

        $stmt = $this->conn->prepare($query);
        $stmt->execute();

        $result_list = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {       
            array_push($result_list, $row);
        }
        return $result_list;
    }

    public function get($id) {

        $query = "SELECT * FROM " . $this->table . " WHERE id = :id";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        return ($stmt->fetch(PDO::FETCH_ASSOC));
    }
}

?>