<?php
class Customer extends Model {
    protected static string $table = 'customers';

    public static function search(string $q, int $limit = 15): array {
        $stmt = db()->prepare(
            "SELECT * FROM customers 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 {
        $customer = static::find($id);
        if (!$customer) return null;
        $tid = static::tenantId();
        $sales = db()->prepare(
            "SELECT s.sale_no,s.total,s.payment_status,s.created_at,s.status FROM sales s
             WHERE s.customer_id=? AND s.tenant_id=? ORDER BY s.created_at DESC LIMIT 20"
        );
        $sales->execute([$id,$tid]);
        $customer['sales']   = $sales->fetchAll();
        $customer['balance'] = $customer['balance'] ?? 0;
        return $customer;
    }

    public static function recordPayment(int $customerId, float $amount, string $method, string $note=''): void {
        $tid = static::tenantId();
        db()->prepare("UPDATE customers SET balance=GREATEST(0,balance-?) WHERE id=? AND tenant_id=?")
             ->execute([$amount,$customerId,$tid]);
        db()->prepare("INSERT INTO payments (tenant_id,type,reference_id,party_id,party_type,amount,method,note,user_id) VALUES (?,?,?,?,?,?,?,?,?)")
             ->execute([$tid,'customer_payment',$customerId,$customerId,'customer',$amount,$method,$note,Auth::userId()]);
    }
}


