<?php

namespace App\Models\Test;

use App\Models\BaseModel;

class TestDefTechModel extends BaseModel {
  protected $table      = 'testdeftech';
  protected $primaryKey = 'TestTechID';
  protected $allowedFields = [
    'TestSiteID',
    'DisciplineID', 
    'DepartmentID', 
    'ResultType', 
    'RefType', 
    'VSet', 
    'ReqQty', 
    'ReqQtyUnit', 
    'Unit1', 
    'Factor', 
    'Unit2', 
    'Decimal', 
    'CollReq', 
    'Method', 
    'ExpectedTAT', 
    'CreateDate', 
    'EndDate'
  ];  
  
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

  /**
   * Get technical details for a test
   */
  public function getTechDetails($testSiteID) {
    $db = \Config\Database::connect();
    
    return $db->table('testdeftech')
        ->select('testdeftech.*, d.DisciplineName, dept.DepartmentName')
        ->join('discipline d', 'd.DisciplineID=testdeftech.DisciplineID', 'left')
        ->join('department dept', 'dept.DepartmentID=testdeftech.DepartmentID', 'left')
        ->where('testdeftech.TestSiteID', $testSiteID)
        ->where('testdeftech.EndDate IS NULL')
        ->get()->getResultArray();
  }

  /**
   * Get tests by discipline
   */
  public function getTestsByDiscipline($disciplineID, $siteID = null) {
    $builder = $this->select('testdeftech.*, testdefsite.TestSiteCode, testdefsite.TestSiteName')
        ->join('testdefsite', 'testdefsite.TestSiteID=testdeftech.TestSiteID', 'left')
        ->where('testdeftech.DisciplineID', $disciplineID)
        ->where('testdeftech.EndDate IS NULL');
    
    if ($siteID) {
        $builder->where('testdefsite.SiteID', $siteID);
    }
    
    return $builder->findAll();
  }

  /**
   * Get tests by department
   */
  public function getTestsByDepartment($departmentID, $siteID = null) {
    $builder = $this->select('testdeftech.*, testdefsite.TestSiteCode, testdefsite.TestSiteName')
        ->join('testdefsite', 'testdefsite.TestSiteID=testdeftech.TestSiteID', 'left')
        ->where('testdeftech.DepartmentID', $departmentID)
        ->where('testdeftech.EndDate IS NULL');
    
    if ($siteID) {
        $builder->where('testdefsite.SiteID', $siteID);
    }
    
    return $builder->findAll();
  }
}
