<?php
namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class LabelController extends BaseController
{
	use ResponseTrait;

    public function coll($reqnum, $printer = 'lab')
{
        $db = \Config\Database::connect();
        $userid = session()->get('userid') ?? 'system';
        
        $sql = "select p.PATNUMBER,
                [Name] = case 
                        when p.TITLEID is not null then ISNULL(p.FIRSTNAME,'') + ' ' + ISNULL(p.NAME,'') + ', ' + tx.SHORTTEXT
                        else ISNULL(p.FIRSTNAME,'') + ' ' + ISNULL(p.NAME,'')
                    end,
                format(p.BIRTHDATE,'dd/MMM/yyyy') as dob,
                age = case
                    when year(spr.COLLECTIONDATE) - year(p.BIRTHDATE) > 0 then (
                        case 
                        when format(p.BIRTHDATE,'MMdd')=format(spr.COLLECTIONDATE,'MMdd') then cast(DATEDIFF(YEAR,p.BIRTHDATE, spr.COLLECTIONDATE) as varchar) + 'Y'
                        else cast( DATEDIFF(hour,p.BIRTHDATE, spr.COLLECTIONDATE)/8766 as varchar) + 'Y' end 
                    )
                    when month(spr.COLLECTIONDATE) - month(p.BIRTHDATE) > 0 then cast( DATEDIFF(MM,p.BIRTHDATE,spr.COLLECTIONDATE) as varchar) + 'M'
                    else cast ( floor ( ( day(spr.COLLECTIONDATE) - day(p.BIRTHDATE) ) / 7) as varchar ) + 'W'
                end,
                [Gender] = case
                    when p.SEX = 1 then 'M'
                    when p.SEX = 2 then 'F'
                    else ''
                    end,
                spr.HOSTORDERNUMBER
                from SP_REQUESTS spr
                left join PATIENTS p on spr.PATID=p.PATID
                left join DICT_TEXTS tx on tx.TEXTID=p.TITLEID
                where spr.SP_ACCESSNUMBER='$reqnum'";
        $rows = $db->query($sql)->getResultArray();
        //print_r($rows);
        $row = $rows[0];
        $patnum = $row['PATNUMBER'];
        $patnum = substr($patnum, 14);
        //$patnum = str_pad(substr($row[0],5),17," ");
        $patname = $row['Name'];
        $dob = $row['dob'];
        $age = $row['age'];
        $sex = $row['Gender'];
        $hospnum = $row['HOSTORDERNUMBER'];
        $date = date("d/M/Y H:i");
        $bar = "[
N
OD
q400
Q224,24+0
I8,A,001
D10
A10,3,0,3,1,1,N,\"$patname\"
A10,27,0,2,1,1,N,\"$sex $dob $age\"
A225,27,0,3,1,1,N,\"$reqnum\"
B120,50,0,1,2,8,90,N,\"$reqnum\"
A80,150,0,2,2,1,N,\"$hospnum\"
A10,195,0,1,1,1,N,\"HIS : $hospnum\"
A190,190,0,2,1,1,N,\"$date\"
P1\n]";


        $printers = new \Config\Printers();
        $command = $printers->getCommand($printer);
        if ($command) {
            $handle = fopen("./file.txt", "w+");
            fwrite($handle, $bar);
            fclose($handle);
            exec($command);
            return $this->respond(['status' => 'success', 'message' => 'Label printed'], 200);
        }
        return $this->respond(['status' => 'error', 'message' => 'Invalid printer'], 400);
    }

    public function dispatch($reqnum, $samid, $printer = 'lab')
{
        $db = \Config\Database::connect();
        $userid = session()->get('userid') ?? 'system';
        
        $sql = "select p.PATNUMBER,
            [Name] = case 
                    when p.TITLEID is not null then ISNULL(p.FIRSTNAME,'') + ' ' + ISNULL(p.NAME,'') + ', ' + tx.SHORTTEXT
                    else ISNULL(p.FIRSTNAME,'') + ' ' + ISNULL(p.NAME,'')
                end,
            format(p.BIRTHDATE,'dd/MMM/yyyy') as dob,
            age = case
                when year(spr.COLLECTIONDATE) - year(p.BIRTHDATE) > 0 then (
                    case 
                    when format(p.BIRTHDATE,'MMdd')=format(spr.COLLECTIONDATE,'MMdd') then cast(DATEDIFF(YEAR,p.BIRTHDATE, spr.COLLECTIONDATE) as varchar) + 'Y'
                    else cast( DATEDIFF(hour,p.BIRTHDATE, spr.COLLECTIONDATE)/8766 as varchar) + 'Y' end 
                )
                when month(spr.COLLECTIONDATE) - month(p.BIRTHDATE) > 0 then cast( DATEDIFF(MM,p.BIRTHDATE,spr.COLLECTIONDATE) as varchar) + 'M'
                else cast ( floor ( ( day(spr.COLLECTIONDATE) - day(p.BIRTHDATE) ) / 7) as varchar ) + 'W'
            end,
            [Gender] = case
                when p.SEX = 1 then 'M'
                when p.SEX = 2 then 'F'
                else ''
                end,
            spr.HOSTORDERNUMBER
            from SP_REQUESTS spr
            left join PATIENTS p on spr.PATID=p.PATID
            left join DICT_TEXTS tx on tx.TEXTID=p.TITLEID
            where spr.SP_ACCESSNUMBER='$reqnum'";

        $rows = $db->query($sql)->getResultArray();
        $row = $rows[0];
        $patnum = $row['PATNUMBER'];
        $patnum = substr($patnum, 14);
        $patname = $row['Name'];
        $age = $row['age'];
        $sex = $row['Gender'];
        $hospnum = $row['HOSTORDERNUMBER'];

        $sql = "select SAMPCODE, SHORTTEXT, TESTS, TESTS1 from GDC_CMOD.dbo.v_sp_reqtube where SP_ACCESSNUMBER='$reqnum' and SAMPCODE='$samid'";
        $rows = $db->query($sql)->getResultArray();
        $row = $rows[0];
        $sampcode = $row['SAMPCODE'];
        $samptext = $row['SHORTTEXT'];
        $tests = $row['TESTS'];
        $tests1 = $row['TESTS1'];
        if ($tests == '') {
            $tests = $tests1;
        }
        $tubeid = $sampcode . substr("$reqnum", 5, 5);
        $date = date("d/M/Y H:i");

        $bar = "[
N
OD
q400
Q224,24+0
I8,A,001
D10
A10,3,0,3,1,1,N,\"$patname \"
A10,27,0,2,1,1,N,\"$sex $age\"
B130,50,0,1,2,8,90,N,\"$tubeid\"
A380,27,5,3,1,1,N,\"$tubeid\"
A10,80,0,2,1,2,R,\"$samptext\"
A10,150,0,2,1,1,N,\"$tests\"
A10,180,0,1,1,1,N,\"LIS : $reqnum\"
A10,195,0,1,1,1,N,\"HIS : $hospnum\"
A190,190,0,2,1,1,N,\"$date\"
P1
]";


        $printers = new \Config\Printers();
        $command = $printers->getCommand($printer);
        if ($command) {
            $handle = fopen("./file.txt", "w+");
            fwrite($handle, $bar);
            fclose($handle);
            exec($command);
            return $this->respond(['status' => 'success', 'message' => 'Label printed'], 200);
        }
        return $this->respond(['status' => 'error', 'message' => 'Invalid printer'], 400);
    }

    public function print_all($accessnumber, $printer = 'lab')
    {
        $db = \Config\Database::connect();
        $userid = session()->get('userid') ?? 'system';
        
        $this->coll($accessnumber, $printer);
        $sql = "select SAMPCODE from GDC_CMOD.dbo.v_sp_reqtube where SP_ACCESSNUMBER='$accessnumber'";
        $rows = $db->query($sql)->getResultArray();
        foreach ($rows as $row) {
            $sampcode = $row['SAMPCODE'];
            $this->dispatch($accessnumber, $sampcode, $printer);
        }
        return $this->respond(['status' => 'success', 'message' => 'All labels printed'], 200);
    }
}
