<?php

namespace App\Models\RefRange;

use App\Models\BaseModel;

class RefNumModel extends BaseModel
{
  protected $table = 'refnum';
  protected $primaryKey = 'RefNumID';
  protected $allowedFields = [
    'SiteID',
    'TestSiteID',
    'SpcType',
    'Sex',
    'Criteria',
    'AgeStart',
    'AgeEnd',
    'NumRefType',
    'RangeType',
    'LowSign',
    'Low',
    'HighSign',
    'High',
    'Display',
    'Flag',
    'Interpretation',
    'Notes',
    'CreateDate',
    'StartDate',
    'EndDate'
  ];

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

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


  /**
   * Get formatted numeric reference ranges with labels
   *
   * @param int $testSiteID
   * @return array
   */
  public function getFormattedByTestSiteID($testSiteID)
  {
      $rows = $this->getActiveByTestSiteID($testSiteID);
      
      return array_map(function ($r) {
            return [
                'RefNumID'        => $r['RefNumID'],
                'NumRefType'      => $r['NumRefType'],
                'NumRefTypeLabel' => $r['NumRefType'] ? \App\Libraries\ValueSet::getLabel('numeric_ref_type', $r['NumRefType']) : '',
                'RangeType'       => $r['RangeType'],
                'RangeTypeLabel'  => $r['RangeType'] ? \App\Libraries\ValueSet::getLabel('range_type', $r['RangeType']) : '',
                'SpcType'         => $r['SpcType'],
                'Sex'             => $r['Sex'],
                'SexLabel'        => $r['Sex'] ? \App\Libraries\ValueSet::getLabel('gender', $r['Sex']) : '',
                'LowSign'         => $r['LowSign'],
                'LowSignLabel'    => $r['LowSign'] ? \App\Libraries\ValueSet::getLabel('math_sign', $r['LowSign']) : '',
                'HighSign'        => $r['HighSign'],
                'HighSignLabel'   => $r['HighSign'] ? \App\Libraries\ValueSet::getLabel('math_sign', $r['HighSign']) : '',
                'High'            => $r['High'] !== null ? (float) $r['High'] : null,
                'Low'             => $r['Low'] !== null ? (float) $r['Low'] : null,
                'AgeStart'        => $r['AgeStart'] !== null ? (int) $r['AgeStart'] : null,
                'AgeEnd'          => $r['AgeEnd'] !== null ? (int) $r['AgeEnd'] : null,
                'Flag'            => $r['Flag'],
                'Interpretation'  => $r['Interpretation'],
                'Notes'           => $r['Notes'],
            ];
        }, $rows ?? []);
    }

  /**
   * Disable all numeric 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 numeric reference ranges
   *
   * @param int $testSiteID
   * @param int $siteID
   * @param array $ranges
   * @return void
   */
    public function batchInsert($testSiteID, $siteID, $ranges)
    {
        foreach ($ranges as $index => $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',
                'NumRefType'    => $range['NumRefType'],
                'RangeType'     => $range['RangeType'],
                'Sex'           => $range['Sex'],
                'AgeStart'      => $ageStart,
                'AgeEnd'        => $ageEnd,
                'LowSign'       => !empty($range['LowSign']) ? $range['LowSign'] : null,
                'Low'           => !empty($range['Low']) ? (float) $range['Low'] : null,
                'HighSign'      => !empty($range['HighSign']) ? $range['HighSign'] : null,
                'High'          => !empty($range['High']) ? (float) $range['High'] : null,
                'Flag'          => $range['Flag'] ?? null,
                'Interpretation'=> $range['Interpretation'] ?? null,
                'Notes'         => $range['Notes'] ?? null,
                'Display'       => $index,
                'CreateDate'    => date('Y-m-d H:i:s'),
            ]);
        }
    }
}
