<?php
namespace App\Models\Organization;
use App\Models\BaseModel;
use App\Libraries\ValueSet;

class SiteModel extends BaseModel {
  protected $table = 'site';
  protected $primaryKey = 'SiteID';
  protected $allowedFields = ['SiteCode', 'ExtSiteID', 'SiteName', 'AccountID', 'SiteType', 'Parent', 'SiteClass', 'ME',
    'CreateDate', 'EndDate']; 
		
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = 'EndDate';
   
  public function getSites($filter) {
		$builder = $this->select('site.SiteID, site.SiteCode, site.SiteName, s1.SiteName as ParentName, account.AccountName')
      ->join('account', 'account.AccountID=site.AccountID', 'left')
      ->join('site s1', 's1.SiteID=site.Parent', 'left');

		if (!empty($filter['SiteCode'])) {
			$builder->like('site.SiteCode', $filter['SiteCode'], 'both');
		}
		if (!empty($filter['SiteName'])) {
			$builder->like('site.SiteName', $filter['SiteName'], 'both');
		}

		$rows = $builder->findAll();
    
    return $rows;
  }

  public function getSite($SiteID) {
    $row = $this->select('site.*, account.AccountName, s1.SiteName as ParentName')
      ->join('account', 'account.AccountID=site.AccountID', 'left')
      ->join('site s1', 's1.SiteID=site.Parent', 'left')
      ->where('site.SiteID', $SiteID)
      ->first();
    
    if (!$row) return null;
    
    $row = ValueSet::transformLabels([$row], [
      'SiteTypeID' => 'site_type',
      'SiteClassID' => 'site_class',
    ])[0];
    
    return $row;
  }
}
