<?php

namespace App\Models\Test;

use App\Models\BaseModel;
use App\Libraries\ValueSet;

class TestDefGrpModel extends BaseModel {
  protected $table      = 'testdefgrp';
  protected $primaryKey = 'TestGrpID';
  protected $allowedFields = [
    'TestSiteID',
    'Member',
    'SeqScr',
    'SeqRpt',
    'CreateDate', 
    'EndDate'
  ]; 
   
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

  public function getGroupMembers($testSiteID) {
    $db = \Config\Database::connect();
    
    $rows = $db->table('testdefgrp')
        ->select('t.TestSiteID as TestSiteID, t.TestSiteCode, t.TestSiteName, t.TestType, t.SeqScr, t. SeqRpt')
        ->join('testdefsite t', 't.TestSiteID=testdefgrp.Member', 'left')
        ->where('testdefgrp.TestSiteID', $testSiteID)
        ->where('testdefgrp.EndDate IS NULL')
        ->orderBy('t.SeqScr', 'ASC')
        ->orderBy('t.SeqRpt', 'ASC')
        ->orderBy('testdefgrp.TestGrpID', 'ASC')
        ->get()->getResultArray();
    
    $rows = ValueSet::transformLabels($rows, [
      'TestType' => 'test_type',
    ]);
    
    return $rows;
  }

  public function getGroupsContainingTest($memberTestSiteID) {
    return $this->select('testdefgrp.*, t.TestSiteCode, t.TestSiteName')
        ->join('testdefsite t', 't.TestSiteID=testdefgrp.TestSiteID', 'left')
        ->where('testdefgrp.Member', $memberTestSiteID)
        ->where('testdefgrp.EndDate IS NULL')
        ->findAll();
  }


  /**
   * Disable group members by TestSiteID
   */
  public function disableByTestSiteID($testSiteID) {
    $this->db->table('testdefgrp')
      ->where('TestSiteID', $testSiteID)
      ->update(['EndDate' => date('Y-m-d H:i:s')]);
  }
}
