<?php
class Entity
{
    private $conn;

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

    public function getEntityByCode($code)
    {
        $sql = "SELECT 
                e.id, 
                e.name, 
                e.description, 
                r.name AS region_name,
                c.name AS comuna_name,
                e.adress, 
                e.pic, 
                e.state 
            FROM 
                entity e
            JOIN 
                region r ON e.region = r.code
            JOIN 
                comuna c ON e.comuna = c.code
            WHERE 
                e.code = ?
    ";

        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $code);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function getEntityById($id)
    {
        $sql = "SELECT
                e.id, 
                e.name, 
                e.description, 
                r.name AS region_name,
                c.name AS comuna_name,
                e.adress, 
                e.pic, 
                e.state 
            FROM 
                entity e
            JOIN 
                region r ON e.region = r.code
            JOIN 
                comuna c ON e.comuna = c.code
            WHERE 
                e.id = ?
    ";

        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function getEntityCodeById($id)
    {
        $sql = "SELECT e.code FROM entity e WHERE e.id = ?
    ";

        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['code'] ?? null;
    }
}
