<?php

class TechStack
{
    private $conn;
    private $table_name = "tech_stack";

    public $id;
    public $name;
    public $logo;
    public $type;

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

    public function readAll()
    {
        $query = "SELECT * FROM " . $this->table_name . " ORDER BY name 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->name = $row['name'];
            $this->logo = $row['logo'];
            $this->type = $row['type'];
            return true;
        }
        return false;
    }

    public function create()
    {
        $query = "INSERT INTO " . $this->table_name . "
                  SET
                    name = :name,
                    logo = :logo,
                    type = :type";

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

        // Sanitize and bind values
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->logo = htmlspecialchars(strip_tags($this->logo));
        $this->type = htmlspecialchars(strip_tags($this->type));

        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':logo', $this->logo);
        $stmt->bindParam(':type', $this->type);

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

        return false;
    }

    public function update()
    {
        $query = "UPDATE " . $this->table_name . "
                  SET
                    name = :name,
                    logo = :logo,
                    type = :type
                  WHERE id = :id";

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

        // Sanitize and bind values
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->logo = htmlspecialchars(strip_tags($this->logo));
        $this->type = htmlspecialchars(strip_tags($this->type));

        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':logo', $this->logo);
        $stmt->bindParam(':type', $this->type);
        $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;
    }
}

?>