<?php

namespace App\Classes\General\Eloquent\Filters;

use Illuminate\Database\Eloquent\Builder;

class AffiliateSearch implements Filter
{

    /**
     * @param Builder $builder
     * @param $value
     * @return Builder|mixed
     */
    public static function apply(Builder $builder, $value)
    {
        // Sanitize input to prevent SQL injection
        // Remove any characters that could be used for SQL injection
        $sanitized = preg_replace('/[^a-zA-Z0-9\s\-_]/', '', $value);
        
        // Trim whitespace
        $sanitized = trim($sanitized);
        
        // If sanitized value is empty, return builder without filtering
        if (empty($sanitized)) {
            return $builder;
        }
        
        return $builder->where(function ($query) use ($sanitized) {
            $query->where('campaign_name', 'LIKE', '%' . $sanitized . '%')
                  ->orWhere('code', 'LIKE', '%' . $sanitized . '%')
                  ->orWhere('campaign_description', 'LIKE', '%' . $sanitized . '%');
        });
    }

}

