<?php

namespace App\Models\Test;

use App\Models\BaseModel;

class TestDefCalModel extends BaseModel {
  protected $table      = 'testdefcal';
  protected $primaryKey = 'TestCalID';
  protected $allowedFields = [
    'TestSiteID',
    'DisciplineID', 
    'DepartmentID',
    'FormulaInput', 
    'FormulaCode', 
    'RefType',
    'Unit1', 
    'Factor', 
    'Unit2', 
    'Decimal',
    'Method',
    'CreateDate', 
    'EndDate'
  ];  
  
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

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

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

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