<?php
class GuesthousePhoto
{
    private $conn;
    private $table_name = "guesthouse_photos";

    public $id;
    public $guesthouse_id;
    public $photo_url;
    public $is_main;
    public $uploaded_at;

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

    public function create()
    {
        $query = "INSERT INTO " . $this->table_name . " SET guesthouse_id=:guesthouse_id, photo_url=:photo_url, is_main=:is_main, uploaded_at=:uploaded_at";
        $stmt = $this->conn->prepare($query);

        $this->guesthouse_id = htmlspecialchars(strip_tags($this->guesthouse_id));
        $this->photo_url = htmlspecialchars(strip_tags($this->photo_url));
        $this->is_main = htmlspecialchars(strip_tags($this->is_main));
        $this->uploaded_at = date('Y-m-d H:i:s');

        $stmt->bindParam(":guesthouse_id", $this->guesthouse_id);
        $stmt->bindParam(":photo_url", $this->photo_url);
        $stmt->bindParam(":is_main", $this->is_main);
        $stmt->bindParam(":uploaded_at", $this->uploaded_at);

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

    public function getByGuesthouseId($guesthouse_id)
    {
        $query = "SELECT * FROM " . $this->table_name . " WHERE guesthouse_id = ? ORDER BY is_main DESC, uploaded_at DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $guesthouse_id);
        $stmt->execute();
        return $stmt;
    }

    public function deleteByGuesthouseId($guesthouse_id)
    {
        $query = "DELETE FROM " . $this->table_name . " WHERE guesthouse_id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $guesthouse_id);
        return $stmt->execute();
    }

    public function findById($id)
    {
        $query = "SELECT * FROM " . $this->table_name . " WHERE id = ? LIMIT 0,1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

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