<?php
  
  namespace App\Models;
  
  use CodeIgniter\Model;
  
  class VendorBusinessAreaModel extends Model
  {
    protected $table = 'vendor_business_areas';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
      'vendor_seq', 'business_area'
    ];
    
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = null;
    
    protected $validationRules = [
      'vendor_seq' => 'required|integer|is_not_unique[vendors.id]',
      'business_area' => 'required|max_length[100]'
    ];
    
    protected $validationMessages = [
      'vendor_seq' => [
        'required' => '벤더사 id는 필수입니다.',
        'is_not_unique' => '존재하지 않는 벤더사입니다.'
      ],
      'business_area' => [
        'required' => '사업 분야는 필수입니다.'
      ]
    ];
    
    // 벤더사의 사업 분야 일괄 업데이트
    public function updateBusinessAreas($vendorId, $businessAreas)
    {
      $this->db->transStart();
      
      // 기존 사업 분야 삭제
      $this->where('vendor_seq', $vendorId)->delete();
      
      // 새로운 사업 분야 추가
      if (!empty($businessAreas)) {
        $insertData = [];
        foreach ($businessAreas as $area) {
          $insertData[] = [
            'vendor_seq' => $vendorId,
            'business_area' => $area
          ];
        }
        $this->insertBatch($insertData);
      }
      
      $this->db->transComplete();
      
      return $this->db->transStatus();
    }
  }