<?php

class Recognition
{
    private $conn;
    private $table_name = "recognitions";

    public $id;
    public $title;
    public $issuer;
    public $icon;

    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function readAll()
    {
        $query = "SELECT * FROM " . $this->table_name . " ORDER BY title ASC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

    public function readOne()
    {
        $query = "SELECT * FROM " . $this->table_name . " WHERE id = ? LIMIT 0,1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $this->title = $row['title'];
            $this->issuer = $row['issuer'];
            $this->icon = $row['icon'];
            return true;
        }
        return false;
    }

    public function create()
    {
        $query = "INSERT INTO " . $this->table_name . "
                  SET
                    title = :title,
                    issuer = :issuer,
                    icon = :icon";

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

        // Sanitize and bind values
        $this->title = htmlspecialchars(strip_tags($this->title));
        $this->issuer = htmlspecialchars(strip_tags($this->issuer));
        $this->icon = htmlspecialchars(strip_tags($this->icon));

        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':issuer', $this->issuer);
        $stmt->bindParam(':icon', $this->icon);

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

        return false;
    }

    public function update()
    {
        $query = "UPDATE " . $this->table_name . "
                  SET
                    title = :title,
                    issuer = :issuer,
                    icon = :icon
                  WHERE id = :id";

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

        // Sanitize and bind values
        $this->title = htmlspecialchars(strip_tags($this->title));
        $this->issuer = htmlspecialchars(strip_tags($this->issuer));
        $this->icon = htmlspecialchars(strip_tags($this->icon));

        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':issuer', $this->issuer);
        $stmt->bindParam(':icon', $this->icon);
        $stmt->bindParam(':id', $this->id);

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

        return false;
    }

    public function delete()
    {
        $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);

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

        return false;
    }
}

?>