<?php

namespace App\Models\Test;

use App\Models\BaseModel;

class TestMapModel extends BaseModel {
  protected $table      = 'testmap';
  protected $primaryKey = 'TestMapID';
  protected $allowedFields = [
    'TestSiteID',
    'HostType', 
    'HostID', 
    'HostDataSource', 
    'HostTestCode', 
    'HostTestName',
    'ClientType', 
    'ClientID', 
    'ClientDataSource',
    'ConDefID',
    'ClientTestCode', 
    'ClientTestName', 
    'CreateDate', 
    'EndDate'
  ]; 
	
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

  /**
   * Get test mappings by test site
   */
  public function getMappingsByTestSite($testSiteID) {
    return $this->where('TestSiteID', $testSiteID)
        ->where('EndDate IS NULL')
        ->findAll();
  }

  /**
   * Get test mappings by client (equipment/workstation)
   */
  public function getMappingsByClient($clientType, $clientID) {
    return $this->where('ClientType', $clientType)
        ->where('ClientID', $clientID)
        ->where('EndDate IS NULL')
        ->findAll();
  }

  /**
   * Get test mappings by host (site/HIS)
   */
  public function getMappingsByHost($hostType, $hostID) {
    return $this->where('HostType', $hostType)
        ->where('HostID', $hostID)
        ->where('EndDate IS NULL')
        ->findAll();
  }

  /**
   * Get test mapping by client test code and container
   */
  public function getMappingByClientCode($clientTestCode, $conDefID = null) {
    $builder = $this->where('ClientTestCode', $clientTestCode)
        ->where('EndDate IS NULL');
    
    if ($conDefID) {
        $builder->where('ConDefID', $conDefID);
    }
    
    return $builder->findAll();
  }

  /**
   * Get test mapping by host test code
   */
  public function getMappingByHostCode($hostTestCode) {
    return $this->where('HostTestCode', $hostTestCode)
        ->where('EndDate IS NULL')
        ->findAll();
  }

  /**
   * Check if mapping exists for client and host
   */
  public function mappingExists($testSiteID, $clientType, $clientID, $clientTestCode) {
    return $this->where('TestSiteID', $testSiteID)
        ->where('ClientType', $clientType)
        ->where('ClientID', $clientID)
        ->where('ClientTestCode', $clientTestCode)
        ->where('EndDate IS NULL')
        ->countAllResults() > 0;
  }
}
