<?php

class CategoryService {

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

    public function add($category) {

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

        $stmt->bindParam(':category', $category->category);

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

    public function update($category) {

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

        $stmt->bindParam(':category', $category->category);
        $stmt->bindParam(':id', $category->id);

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

    public function delete($category) {

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

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

    public function getCategoryWhere($category) {

        $query = "SELECT * FROM " . $this->table . " WHERE LOWER(category) = :category";

        $stmt = $this->conn->prepare($query);
        $category = strtolower($category);
        $stmt->bindParam(':category', $category);
        $stmt->execute();
        return ($stmt->fetch(PDO::FETCH_ASSOC));
    }
}

?>