<?php
class Brand extends Model {
    protected static string $table = 'brands';

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

    public static function all(string $orderBy = 'name ASC', int $limit = 0, int $offset = 0): array {
        $sql = "SELECT * FROM brands 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 brands (tenant_id, name, description) VALUES (?, ?, ?)"
        );
        $stmt->execute([
            static::tenantId(),
            $data['name'],
            $data['description'] ?? null
        ]);
        return (int)db()->lastInsertId();
    }

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

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