<?php

namespace App\Models\Test;

use App\Models\BaseModel;

class TestDefSiteModel extends BaseModel {
  protected $table      = 'testdefsite';
  protected $primaryKey = 'TestSiteID';
  protected $allowedFields = [
    'SiteID', 
    'TestSiteCode', 
    'TestSiteName', 
    'TestType', 
    'Description', 
    'SeqScr', 
    'SeqRpt', 
    'IndentLeft',
    'FontStyle',
    'VisibleScr', 
    'VisibleRpt', 
    'CountStat', 
    'CreateDate', 
    'StartDate',
    'EndDate'
  ]; 
  
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = 'StartDate';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

  /**
   * Get all tests with type information
   */
  public function getTests($siteId = null, $testType = null, $visibleScr = null, $visibleRpt = null, $keyword = null) {
    $builder = $this->select("testdefsite.TestSiteID, testdefsite.TestSiteCode, testdefsite.TestSiteName, testdefsite.TestType, 
                  testdefsite.SeqScr, testdefsite.SeqRpt, testdefsite.VisibleScr, testdefsite.VisibleRpt,
                  testdefsite.CountStat, testdefsite.StartDate, testdefsite.EndDate,
                  valueset.VValue as TypeCode, valueset.VDesc as TypeName")
      ->join("valueset", "valueset.VID=testdefsite.TestType", "left")
      ->where('testdefsite.EndDate IS NULL');
    
    if ($siteId) {
        $builder->where('testdefsite.SiteID', $siteId);
    }
    
    if ($testType) {
        $builder->where('testdefsite.TestType', $testType);
    }
    
    if ($visibleScr !== null) {
        $builder->where('testdefsite.VisibleScr', $visibleScr);
    }
    
    if ($visibleRpt !== null) {
        $builder->where('testdefsite.VisibleRpt', $visibleRpt);
    }
    
    if ($keyword) {
        $builder->like('testdefsite.TestSiteName', $keyword);
    }
    
    return $builder->orderBy('testdefsite.SeqScr', 'ASC')->findAll();
  }

  /**
   * Get single test with all related details based on TestType
   */
  public function getTest($TestSiteID) {
    $db = \Config\Database::connect();
    
    $row = $this->select("testdefsite.*, valueset.VValue as TypeCode, valueset.VDesc as TypeName")
      ->join("valueset", "valueset.VID=testdefsite.TestType", "left")
      ->where("testdefsite.TestSiteID", $TestSiteID)
      ->find($TestSiteID);
    
    if (!$row) return null;

    $typeCode = $row['TypeCode'] ?? '';
    
    // Load related details based on TestType
    if ($typeCode === 'CALC') {
        // Load calculation details with joined discipline and department
        $row['testdefcal'] = $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();
        
        // Load test mappings
        $testMapModel = new \App\Models\Test\TestMapModel();
        $row['testmap'] = $testMapModel->where('TestSiteID', $TestSiteID)->where('EndDate IS NULL')->findAll();
        
    } elseif ($typeCode === 'GROUP') {
        // Load group members with test details
        $row['testdefgrp'] = $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();
        
        // Load test mappings
        $testMapModel = new \App\Models\Test\TestMapModel();
        $row['testmap'] = $testMapModel->where('TestSiteID', $TestSiteID)->where('EndDate IS NULL')->findAll();
        
    } elseif ($typeCode === 'TITLE') {
        // Load test mappings only for TITLE type
        $testMapModel = new \App\Models\Test\TestMapModel();
        $row['testmap'] = $testMapModel->where('TestSiteID', $TestSiteID)->where('EndDate IS NULL')->findAll();
        
    } elseif (in_array($typeCode, ['TEST', 'PARAM'])) {
        // TEST or PARAM - load technical details with joined tables
        $row['testdeftech'] = $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();
        
        // Load test mappings
        $testMapModel = new \App\Models\Test\TestMapModel();
        $row['testmap'] = $testMapModel->where('TestSiteID', $TestSiteID)->where('EndDate IS NULL')->findAll();
    }
    
    return $row;
  }
}
