<?php

namespace App\Models\RefRange;

use App\Models\BaseModel;

class RefTxtModel extends BaseModel
{
  protected $table = 'reftxt';
  protected $primaryKey = 'RefTxtID';
  protected $allowedFields = [
    'SiteID',
    'TestSiteID',
    'SpcType',
    'Sex',
    'Criteria',
    'AgeStart',
    'AgeEnd',
    'TxtRefType',
    'RefTxt',
    'Flag',
    'Notes',
    'CreateDate',
    'StartDate',
    'EndDate'
  ];

  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

  /**
   * Get active text reference ranges for a test
   */
  public function getActiveByTestSiteID($testSiteID) {
    return $this->where('TestSiteID', $testSiteID)
      ->where('EndDate', null)
      ->orderBy('RefTxtID', 'ASC')
      ->findAll();
  }


  /**
   * Get formatted text reference ranges with labels
   *
   * @param int $testSiteID
   * @return array
   */
  public function getFormattedByTestSiteID($testSiteID)
  {
      $rows = $this->getActiveByTestSiteID($testSiteID);
      
      return array_map(function ($r) {
          return [
              'RefTxtID'       => $r['RefTxtID'],
              'TxtRefType'     => $r['TxtRefType'],
              'TxtRefTypeLabel'=> $r['TxtRefType'] ? \App\Libraries\ValueSet::getLabel('text_ref_type', $r['TxtRefType']) : '',
              'Sex'            => $r['Sex'],
              'SexLabel'       => $r['Sex'] ? \App\Libraries\ValueSet::getLabel('gender', $r['Sex']) : '',
                'AgeStart'       => $r['AgeStart'] !== null ? (int) $r['AgeStart'] : null,
                'AgeEnd'         => $r['AgeEnd'] !== null ? (int) $r['AgeEnd'] : null,
              'RefTxt'         => $r['RefTxt'],
              'Flag'           => $r['Flag'],
          ];
      }, $rows ?? []);
  }

  /**
   * Disable all text reference ranges for a test
   *
   * @param int $testSiteID
   * @return void
   */
  public function disableByTestSiteID($testSiteID)
  {
      $this->where('TestSiteID', $testSiteID)
          ->set('EndDate', date('Y-m-d H:i:s'))
          ->update();
  }

  /**
   * Batch insert text reference ranges
   *
   * @param int $testSiteID
   * @param int $siteID
   * @param array $ranges
   * @return void
   */
    public function batchInsert($testSiteID, $siteID, $ranges)
    {
        foreach ($ranges as $range) {
            $ageStart = array_key_exists('AgeStart', $range) && $range['AgeStart'] !== '' && $range['AgeStart'] !== null
                ? (int) $range['AgeStart']
                : null;
            $ageEnd = array_key_exists('AgeEnd', $range) && $range['AgeEnd'] !== '' && $range['AgeEnd'] !== null
                ? (int) $range['AgeEnd']
                : null;

            $this->insert([
                'TestSiteID' => $testSiteID,
                'SiteID'     => $siteID,
                'SpcType'    => $range['SpcType'] ?? 'GEN',
                'TxtRefType' => $range['TxtRefType'],
                'Sex'        => $range['Sex'],
                'AgeStart'   => $ageStart,
                'AgeEnd'     => $ageEnd,
                'RefTxt'     => $range['RefTxt'] ?? '',
                'Flag'       => $range['Flag'] ?? null,
                'CreateDate' => date('Y-m-d H:i:s'),
            ]);
        }
    }
}
