<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;

// This is just to add ResponseTrait import - actual edit will be in LabelController

class SamplesController extends BaseController
{
  use ResponseTrait;

  public function show($input)
  {
    $db = \Config\Database::connect();

    $scannedSampleCode = '';
    
    if (strlen($input) == 10) {
      $accessnumber = $input;
    } else {
      $redacc = substr($input, 3, 5);
      $scannedSampleCode = substr($input, 0, 3);
      
      $sql = "SELECT TOP 1 SPR.SP_ACCESSNUMBER
        FROM SP_REQUESTS SPR
        WHERE SPR.SP_ACCESSNUMBER LIKE '%$redacc' AND YEAR(SPR.REQDATE) = YEAR(GETDATE())
        ORDER BY SPR.REQDATE DESC";
      $query = $db->query($sql);
      $row = $query->getRowArray();
      $accessnumber = $row['SP_ACCESSNUMBER'] ?? null;
      
      if (!$accessnumber) {
        return $this->response->setJSON(['data' => null]);
      }
    }

    $sql = "SELECT right(p.PATNUMBER,16) as [patnumber], ISNULL(p.FIRSTNAME,'') + ' ' + ISNULL(p.NAME,'') as [Name],
			case when format(p.BIRTHDATE,'MMdd')=format(spr.COLLECTIONDATE,'MMdd') then DATEDIFF(YEAR,p.BIRTHDATE, spr.COLLECTIONDATE)
			else FLOOR(DATEDIFF(DAY, p.BIRTHDATE, spr.COLLECTIONDATE) / 365.25) end ,
			[Gender] = case
				when p.SEX = 1 then 'M'
				when p.SEX = 2 then 'F'
				else ''
				end, spr.REQDATE, spo.COMMENTTEXT, dmg.DMG_CKTPNO, dmg.DMG_CPLACEOFBIRTH
			from SP_REQUESTS spr
				left join PATIENTS p on p.PATID=spr.PATID
				left join SP_REQUESTS_OCOM spo on spr.SP_ACCESSNUMBER=spo.SP_ACCESSNUMBER
				left join GDC_CMOD.dbo.TDL_DEMOGRAPHIC dmg on right(dmg.DMG_CPATNUMBER,15)=right(p.PATNUMBER,15)
			where spr.PATID=p.PATID and spr.SP_ACCESSNUMBER='$accessnumber'";
    $query = $db->query($sql);
    $results = $query->getRowArray();
    $data = [
      'patnumber' => $results["patnumber"],
      'age' => $results[""],
      'patname' => $results['Name'] ?? '',
      'reqdate' => $results['REQDATE'] ?? '',
      'gender' => $results['Gender'] ?? '',
      'placeofbirth' => $results['DMG_CPLACEOFBIRTH'] ?? '',
      'ktp' => $results['DMG_CKTPNO'] ?? '',
      'comment' => $results['COMMENTTEXT'] ?? '',
      'accessnumber' => $accessnumber,
      'scannedSampleCode' => $scannedSampleCode,
    ];

    $samples = [];
    $sql = "SELECT req.SAMPTYPEID, req.SAMPCODE, req.SHORTTEXT, tu.STATUS, st.TUBESTATUS
			from GDC_CMOD.dbo.v_sp_reqtube req
			left join GDC_CMOD.dbo.TUBES tu on req.SP_ACCESSNUMBER=tu.ACCESSNUMBER and req.SAMPCODE=tu.TUBENUMBER
			left join glendb.dbo.SP_TUBES st on st.SP_ACCESSNUMBER=req.SP_ACCESSNUMBER and req.SAMPCODE=st.SAMPLETYPE
			where req.SP_ACCESSNUMBER='$accessnumber'";
    $query = $db->query($sql);
    $results = $query->getResultArray();
    foreach ($results as $row) {
      $samples[] = [
        'samptypeid' => $row['SAMPTYPEID'] ?? null,
        'sampcode' => $row['SAMPCODE'] ?? null,
        'name' => $row['SHORTTEXT'] ?? '',
        'colstatus' => $row['STATUS'] ?? '',
        'tubestatus' => $row['TUBESTATUS'] ?? '',
      ];
    }
    $data['samples'] = $samples;

    $resp = ['data' => $data];

    return $this->response->setJSON($resp);
  }

  public function collect($accessnumber, $samplenumber)
  {
    $db = \Config\Database::connect();
    $userid = session('userid');
    $sql = "update GDC_CMOD.dbo.TUBES set USERID=?, STATUS='1', COLLECTIONDATE=getdate() where ACCESSNUMBER=? and TUBENUMBER=?";
    $db->query($sql, [$userid, $accessnumber, $samplenumber]);
    $sql = "INSERT INTO GDC_CMOD.dbo.AUDIT_TUBES(ACCESSNUMBER, TUBENUMBER, USERID, STATUS, LOGDATE)
      VALUES (?, ?, ?, '1', getdate())";
    $db->query($sql, [$accessnumber, $samplenumber, $userid]);
    return $this->respondCreated(['status' => 'success', 'message' => 'Data updated successfully', 'data' => "$accessnumber-$samplenumber"], 201);
  }

  public function uncollect($accessnumber, $samplenumber)
  {
    $db = \Config\Database::connect();
    $userid = session('userid');
    $sql = "update GDC_CMOD.dbo.TUBES set STATUS='0', COLLECTIONDATE=NULL where ACCESSNUMBER=? and TUBENUMBER=?";
    $db->query($sql, [$accessnumber, $samplenumber]);
    $sql = "INSERT INTO GDC_CMOD.dbo.AUDIT_TUBES(ACCESSNUMBER, TUBENUMBER, USERID, STATUS, LOGDATE)
      VALUES (?, ?, ?, '0', getdate())";
    $db->query($sql, [$accessnumber, $samplenumber, $userid]);
    return $this->respond(['status' => 'success', 'message' => 'Sample uncollected successfully', 'data' => "$accessnumber-$samplenumber"], 200);
  }

  public function unreceive($accessnumber, $samplenumber)
  {
    $db = \Config\Database::connect();
    
    // Get HOSTORDERNUMBER for Firebird updates
    $sql = "SELECT r.HOSTORDERNUMBER FROM glendb.dbo.SP_REQUESTS r WHERE r.SP_ACCESSNUMBER='$accessnumber'";
    $row = $db->query($sql)->getRowArray();
    $hon = $row['HOSTORDERNUMBER'] ?? '';
    
    // Get test codes for this sample
    $sql = "select r.EXTERNALORDERNUMBER, dt.TESTCODE, do.HISCODE from glendb.dbo.TESTS t
      left join glendb.dbo.DICT_TESTS dt on dt.TESTID=t.TESTID
      left join glendb.dbo.REQUESTS r on r.REQUESTID=t.REQUESTID
      left join glendb.dbo.DICT_TEST_SAMPLES dts on dts.TESTID=t.TESTID
      left join glendb.dbo.DICT_SAMPLES_TYPES ds on ds.SAMPTYPEID=dts.SAMPTYPEID
      left join GDC_CMOD.dbo.DICT_TESTS_ORDER do on do.TESTCODE=dt.TESTCODE
      where t.DEPTH=0
      and r.ACCESSNUMBER='$accessnumber' and ds.SAMPCODE='$samplenumber'";
    $rows = $db->query($sql)->getResultArray();
    $his_test = '';
    $lis_test = '';
    foreach ($rows as $row) {
      $testcode = $row['TESTCODE'];
      $hiscode = $row['HISCODE'];
      $his_test .= "'$hiscode',";
      $lis_test .= "'$testcode',";
    }
    $his_test = rtrim($his_test, ',');
    $lis_test = rtrim($lis_test, ',');
    
    // Update Firebird TDL_ORDERDT
    $conn = odbc_connect('GLENEAGLES', '', '');
    if ($his_test) {
      $sql = "UPDATE TDL_ORDERDT SET ODD_NRECEIVED=NULL, ODD_DTRECEIVE=NULL WHERE ODR_CNOLAB='$hon' AND ODD_CPRODUCTCODE IN ($his_test)";
      odbc_exec($conn, $sql);
    }
    
    // Audit logging
    $userid = session('userid') ?? 'system';
    $sql = "INSERT INTO GDC_CMOD.dbo.AUDIT_REQUESTS(ACCESSNUMBER, STEPDATE, STEPTYPE, USERID) 
      VALUES('$accessnumber', GETDATE(), 'UNRECV', '$userid')";
    $db->query($sql);
    
    // Update SP_TUBES
    $sql = "UPDATE SP_TUBES SET TUBESTATUS=0 WHERE SP_ACCESSNUMBER='$accessnumber' AND SAMPLETYPE='$samplenumber'";
    $db->query($sql);
    
    // Update SP_TESTS
    $sql = "UPDATE SP_TESTS SET SP_TESTSTATUS=NULL WHERE SP_ACCESSNUMBER='$accessnumber' AND SP_TESTCODE IN ($lis_test)";
    $db->query($sql);
    
    // Update REQUESTS_RECEIVE
    $sql = "UPDATE GDC_CMOD.dbo.REQUESTS_RECEIVE SET RECEIVESTATUS=NULL WHERE ACCESSNUMBER='$accessnumber'";
    $db->query($sql);
    
    return $this->respondCreated(['status' => 'success', 'message' => 'Sample unreceived successfully', 'data' => "$accessnumber-$samplenumber"], 201);
  }
}
