<?php

class Faq
{
    private $conn;
    private $table_name = "faqs";

    public $id;
    public $question;
    public $answer;

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

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

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

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

        // Sanitize and bind values
        $this->question = htmlspecialchars(strip_tags($this->question));
        $this->answer = htmlspecialchars(strip_tags($this->answer));

        $stmt->bindParam(':question', $this->question);
        $stmt->bindParam(':answer', $this->answer);

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

        return false;
    }

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

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

        // Sanitize and bind values
        $this->question = htmlspecialchars(strip_tags($this->question));
        $this->answer = htmlspecialchars(strip_tags($this->answer));

        $stmt->bindParam(':question', $this->question);
        $stmt->bindParam(':answer', $this->answer);
        $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;
    }
}

?>