<?php
namespace App\Models\Master;

use App\Models\BaseModel;

class MasterControlsModel extends BaseModel {
    protected $table = 'master_controls';
    protected $primaryKey = 'control_id';
    protected $allowedFields = [
        'dept_id',
        'control_name',
        'lot',
        'producer',
        'exp_date',
        'created_at',
        'updated_at',
        'deleted_at'
    ];
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    public function search($keyword = null, $deptId = null) {
        $builder = $this->builder();
        $builder->select('
            master_controls.control_id as controlId,
            master_controls.control_name as controlName,
            master_controls.lot,
            master_controls.producer,
            master_controls.exp_date as expDate,
            master_depts.dept_name as deptName
        ');
        $builder->join('master_depts', 'master_depts.dept_id = master_controls.dept_id', 'left');
        $builder->where('master_controls.deleted_at', null);

        if ($deptId) {
            $builder->where('master_controls.dept_id', $deptId);
        }

        if ($keyword) {
            $builder->groupStart()
                ->like('master_controls.control_name', $keyword)
                ->orLike('master_controls.lot', $keyword)
                ->orLike('master_controls.producer', $keyword)
                ->groupEnd();
        }

        $builder->orderBy('master_controls.control_name', 'ASC');
        
        $results = $builder->get()->getResultArray();
        
        // Add deptName after camelCase conversion from BaseModel
        foreach ($results as &$row) {
            $row['deptName'] = $row['deptName'] ?? null;
        }

        return $results;
    }
}
