<?php

class GalleryImageService {

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

    public function add($gallery_image) {

        $query = "INSERT INTO " . $this->table . 
            " SET caption = :caption,  
                image = :image";
        
        $stmt = $this->conn->prepare($query);
        
        $gallery_image->caption = htmlspecialchars(strip_tags($gallery_image->caption));
        $gallery_image->image = htmlspecialchars(strip_tags($gallery_image->image));

        $stmt->bindParam(':caption', $gallery_image->caption);
        $stmt->bindParam(':image', $gallery_image->image);
        
        if($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    public function update($gallery_image) {

        $query = "UPDATE " . $this->table . 
            " SET caption = :caption,  
                image = :image
              WHERE id = :id";
        
        $stmt = $this->conn->prepare($query);
        
        $gallery_image->caption = htmlspecialchars(strip_tags($gallery_image->caption));
        $gallery_image->image = htmlspecialchars(strip_tags($gallery_image->image));

        $stmt->bindParam(':caption', $gallery_image->caption);
        $stmt->bindParam(':image', $gallery_image->image);
        $stmt->bindParam(':id', $gallery_image->id);

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


    public function list() {

        $query = "SELECT * FROM " . $this->table . " ORDER BY id 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 listLimitTo($limit) {

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

        $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 delete($gallery_image) {

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

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

    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));
    }
}

?>