<?php
namespace App\Models\Master;

use App\Models\BaseModel;

class MasterTestsModel extends BaseModel {
    protected $table = 'master_tests';
    protected $primaryKey = 'test_id';
    protected $allowedFields = [
        'dept_id',
        'test_code',
        'test_name',
        'test_unit',
        'test_method',
        'cva',
        'ba',
        'tea',
        'created_at',
        'updated_at',
        'deleted_at'
    ];
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    public function search($keyword = null) {
        $builder = $this->builder();
        $builder->select('
            master_tests.test_id as testId,
            master_tests.test_code as testCode,
            master_tests.test_name as testName,
            master_tests.test_unit as testUnit,
            master_tests.test_method as testMethod,
            master_tests.cva,
            master_tests.ba,
            master_tests.tea,
            master_depts.dept_name as deptName
        ');
        $builder->join('master_depts', 'master_depts.dept_id = master_tests.dept_id', 'left');
        $builder->where('master_tests.deleted_at', null);

        if ($keyword) {
            $builder->groupStart()
                ->like('master_tests.test_name', $keyword)
                ->groupEnd();
        }

        $builder->groupBy('master_tests.test_id, master_depts.dept_name');
        $builder->orderBy('master_tests.test_name', 'ASC');

        return $builder->get()->getResultArray();
    }
}
