<?php

class House {
    public static function all() {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT * FROM houses ORDER BY CAST(number AS UNSIGNED)"
        );
    }

    public static function findById($id) {
        $db = Database::getInstance();
        return $db->fetchOne(
            "SELECT * FROM houses WHERE id = ?",
            [$id]
        );
    }

    public static function findByNumber($number) {
        $db = Database::getInstance();
        return $db->fetchOne(
            "SELECT * FROM houses WHERE number = ?",
            [$number]
        );
    }

    public static function getActive() {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT * FROM houses WHERE status = 'activa' ORDER BY CAST(number AS UNSIGNED)"
        );
    }

    public static function getAccessible() {
        $db = Database::getInstance();
        $accessibleIds = Auth::getAccessibleHouseIds();

        if (empty($accessibleIds)) {
            return [];
        }

        $placeholders = str_repeat('?,', count($accessibleIds) - 1) . '?';
        return $db->fetchAll(
            "SELECT * FROM houses WHERE id IN ($placeholders) ORDER BY CAST(number AS UNSIGNED)",
            $accessibleIds
        );
    }

    public static function update($id, $data) {
        $db = Database::getInstance();
        return $db->execute(
            "UPDATE houses SET status = ?, consumption_only = ?, owner_name = ?, owner_email = ?, owner_phone = ? WHERE id = ?",
            [
                $data['status'],
                $data['consumption_only'] ?? 0,
                $data['owner_name'] ?? null,
                $data['owner_email'] ?? null,
                $data['owner_phone'] ?? null,
                $id
            ]
        );
    }

    public static function countActive() {
        $db = Database::getInstance();
        $result = $db->fetchOne(
            "SELECT COUNT(*) as count FROM houses WHERE status = 'activa'",
            []
        );
        return $result['count'] ?? 0;
    }

    public static function countAll() {
        $db = Database::getInstance();
        $result = $db->fetchOne(
            "SELECT COUNT(*) as count FROM houses",
            []
        );
        return $result['count'] ?? 0;
    }

    public static function search($query) {
        $db = Database::getInstance();
        $term = "%$query%";
        return $db->fetchAll(
            "SELECT * FROM houses 
             WHERE number LIKE ? OR owner_name LIKE ? 
             ORDER BY CAST(number AS UNSIGNED) 
             LIMIT 10",
            [$term, $term]
        );
    }
}
