<?php
class Unit extends Model {
    protected static string $table = 'units';

    public static function all(string $orderBy = 'name ASC', int $limit = 0, int $offset = 0): array {
        $sql = "SELECT * FROM units WHERE tenant_id = ? ORDER BY {$orderBy}";
        if ($limit > 0) $sql .= " LIMIT {$limit} OFFSET {$offset}";
        $stmt = db()->prepare($sql);
        $stmt->execute([static::tenantId()]);
        return $stmt->fetchAll();
    }

    public static function find(int $id): ?array {
        return parent::find($id);
    }

    public static function create(array $data): int {
        $stmt = db()->prepare(
            "INSERT INTO units (tenant_id, name, abbreviation, description, is_active) VALUES (?, ?, ?, ?, ?)"
        );
        $stmt->execute([
            static::tenantId(),
            $data['name'],
            $data['abbreviation'] ?? null,
            $data['description'] ?? null,
            $data['is_active'] ?? 1
        ]);
        return (int)db()->lastInsertId();
    }

    public static function update(int $id, array $data): bool {
        $stmt = db()->prepare(
            "UPDATE units SET name=?, abbreviation=?, description=?, is_active=?, updated_at=NOW() 
             WHERE id=? AND tenant_id=?"
        );
        return $stmt->execute([
            $data['name'],
            $data['abbreviation'] ?? null,
            $data['description'] ?? null,
            $data['is_active'] ?? 1,
            $id,
            static::tenantId()
        ]);
    }

    public static function delete(int $id): bool {
        // Check if unit is being used by any products
        $stmt = db()->prepare("SELECT COUNT(*) FROM products WHERE tenant_id=? AND unit=?");
        $stmt->execute([static::tenantId(), $id]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            return false; // Cannot delete if in use
        }
        
        $stmt = db()->prepare("DELETE FROM units WHERE id=? AND tenant_id=?");
        return $stmt->execute([$id, static::tenantId()]);
    }

    public static function getActiveUnits(): array {
        $stmt = db()->prepare("SELECT * FROM units WHERE tenant_id=? AND is_active=1 ORDER BY name");
        $stmt->execute([static::tenantId()]);
        return $stmt->fetchAll();
    }

    public static function toggleStatus(int $id): bool {
        $stmt = db()->prepare("UPDATE units SET is_active = NOT is_active WHERE id=? AND tenant_id=?");
        return $stmt->execute([$id, static::tenantId()]);
    }
}
