<?php
  
  namespace App\Models;
  
  use CodeIgniter\Model;
  
  class VendorAddressModel extends Model
  {
    protected $table = 'vendor_addresses';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
      'vendor_id', 'address_type', 'zip_code', 'address',
      'detail_address', 'city', 'district', 'is_primary'
    ];
    
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    
    protected $validationRules = [
      'vendor_id' => 'required|integer|is_not_unique[vendors.id]',
      'address_type' => 'required|in_list[HEAD_OFFICE,BRANCH,WAREHOUSE,BILLING]',
      'zip_code' => 'permit_empty|max_length[10]',
      'address' => 'required|max_length[500]',
      'detail_address' => 'permit_empty|max_length[500]',
      'city' => 'permit_empty|max_length[100]',
      'district' => 'permit_empty|max_length[100]',
      'is_primary' => 'permit_empty|in_list[0,1]'
    ];
    
    protected $validationMessages = [
      'vendor_id' => [
        'required' => '벤더사 id는 필수입니다.',
        'is_not_unique' => '존재하지 않는 벤더사입니다.'
      ],
      'address' => [
        'required' => '주소는 필수입니다.'
      ]
    ];
    
    // 기본 주소로 설정
    public function setPrimaryAddress($vendorId, $addressId)
    {
      $this->db->transStart();
      
      // 기존 기본 주소 해제
      $this->where('vendor_id', $vendorId)
        ->set('is_primary', 0)
        ->update();
      
      // 새로운 기본 주소 설정
      $this->update($addressId, ['is_primary' => 1]);
      
      $this->db->transComplete();
      
      return $this->db->transStatus();
    }
  }