<?php

class MessageService {

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

    public function add($message) {

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

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

    public function delete($message) {

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

        $stmt = $this->conn->prepare($query);
        
        $stmt->bindParam(':id', $message->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));
    }
}

?>