<?php

class RoomTemperature {
    private $conn;
    private $table_name = "room_temperatures";

    public $id;
    public $temperature;
    public $humidity;
    public $recorded_at;

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

    // Create a new temperature record
    public function create() {
        $query = "INSERT INTO " . $this->table_name . "
                  SET
                    temperature=:temperature,
                    humidity=:humidity";

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

        // sanitize
        $this->temperature = htmlspecialchars(strip_tags((string) ($this->temperature ?? '')));
        $this->humidity = htmlspecialchars(strip_tags((string) ($this->humidity ?? '')));

        // bind values
        $stmt->bindParam(":temperature", $this->temperature);
        $stmt->bindParam(":humidity", $this->humidity);

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

        return false;
    }

    // Read all temperature records, ordered by recorded_at desc
    public function readAll() {
        $query = "SELECT
                    id, temperature, humidity, recorded_at
                  FROM
                    " . $this->table_name . "
                  ORDER BY
                    recorded_at DESC";

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

        return $stmt;
    }

    // Get the latest temperature reading
    public function getLatest() {
        $query = "SELECT
                    id, temperature, humidity, recorded_at
                  FROM
                    " . $this->table_name . "
                  ORDER BY
                    recorded_at DESC
                  LIMIT 0,1";

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

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

        if ($row) {
            $this->id = $row['id'];
            $this->temperature = $row['temperature'];
            $this->humidity = $row['humidity'];
            $this->recorded_at = $row['recorded_at'];
            return true;
        }
        return false;
    }

    // Read records for a specific month and year (for calendar view)
    public function readByMonth($year, $month) {
        $query = "SELECT
                    id, temperature, humidity, recorded_at
                  FROM
                    " . $this->table_name . "
                  WHERE
                    YEAR(recorded_at) = :year AND MONTH(recorded_at) = :month
                  ORDER BY
                    recorded_at ASC";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(":year", $year);
        $stmt->bindParam(":month", $month);
        $stmt->execute();

        return $stmt;
    }
}
