<?php

namespace App\Models\Test;

use App\Models\BaseModel;

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

  /**
   * Get group members for a test group
   */
  public function getGroupMembers($testSiteID) {
    $db = \Config\Database::connect();
    
    return $db->table('testdefgrp')
        ->select('testdefgrp.*, t.TestSiteCode, t.TestSiteName, t.TestType, vs.VValue as MemberTypeCode')
        ->join('testdefsite t', 't.TestSiteID=testdefgrp.Member', 'left')
        ->join('valueset vs', 'vs.VID=t.TestType', 'left')
        ->where('testdefgrp.TestSiteID', $testSiteID)
        ->where('testdefgrp.EndDate IS NULL')
        ->orderBy('testdefgrp.TestGrpID', 'ASC')
        ->get()->getResultArray();
  }

  /**
   * Get all groups that contain a specific test
   */
  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();
  }
}
