<?php 
namespace PortalPeople\datadash\models;

use backend\models\Sysmodels;

class SltSearch extends \yii\base\Model
{

    private $classModel;
    public $trxrange;
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $model = Sysmodels::find()->where(['name' => 'slt'])->one();
        $this->classModel = $model->source;
    }

    public function rules()
    {
        return [
            [$this->attributes(), 'safe'],
            ['trxrange', 'string'], // Ensure trxrange is a string
        ];
    }

    public function search($params)
    {
        $query = $this->classModel::find(); // Assuming Slt is the model representing the SLT data

        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => $params['perPage'] ?? 20, // Set the number of items per page
            ],
            'sort' => [
                'defaultOrder' => ['_ID' => SORT_ASC], // Default sorting by ID descending
            ],
        ]);

        $this->load($params, '');

        if (!$this->validate()) {
            // If validation fails, return an empty data provider
            $query->where('0=1');
            return $dataProvider;
        }
        // Apply filters based on the attributes of the model
        if (!empty($this->trxrange) && str_contains($this->trxrange, ' - ')) {
            list($start, $end) = explode(' - ', $this->trxrange);
            $query->andFilterWhere(['between', 'DATE', $start, $end]);
        } elseif (!empty($this->trxrange) && str_contains($this->trxrange, '>')) {
            $query->andFilterWhere(['>', 'DATE', $this->trxrange]);
        } elseif (!empty($this->trxrange) && str_contains($this->trxrange, '<')) {
            $query->andFilterWhere(['<', 'DATE', $this->trxrange]);
        } else {
            $query->andFilterWhere(['=', 'DATE', $this->trxrange]);
        }

        foreach($this->attributes() as $attribute) {
            if (isset($this->$attribute) && !in_array($attribute, ['trxrange'])) {
                $query->andFilterWhere(['like', $attribute, $this->$attribute]);
            }
        }
        // Add conditions bas
        return $dataProvider;
    }
}
