<?php
class Supplier extends Model {
    protected static string $table = 'suppliers';

    public static function search(string $q, int $limit = 15): array {
        $stmt = db()->prepare(
            "SELECT * FROM suppliers WHERE tenant_id=? AND is_active=1
             AND (name LIKE ? OR phone LIKE ? OR email LIKE ?) LIMIT ?"
        );
        $like = "%{$q}%";
        $stmt->execute([static::tenantId(),$like,$like,$like,$limit]);
        return $stmt->fetchAll();
    }

    public static function withTransactions(int $id): ?array {
        $supplier = static::find($id);
        if (!$supplier) return null;
        $tid = static::tenantId();
        $purchases = db()->prepare(
            "SELECT p.purchase_no,p.total,p.payment_status,p.created_at FROM purchases p
             WHERE p.supplier_id=? AND p.tenant_id=? ORDER BY p.created_at DESC LIMIT 20"
        );
        $purchases->execute([$id,$tid]);
        $supplier['purchases'] = $purchases->fetchAll();
        return $supplier;
    }
}
