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

class ApiRequestsAuditController extends BaseController {
    use ResponseTrait;

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

        $result = [
            'accessnumber' => $accessnumber,
            'validation' => [],
            'sample_collection' => [],
            'tube_received' => [],
            'pdf_generation' => []
        ];

        $sqlAudit = "SELECT EVENT_TYPE, USERID, EVENT_AT, REASON
                     FROM GDC_CMOD.dbo.AUDIT_EVENTS
                     WHERE ACCESSNUMBER = ?
                     ORDER BY EVENT_AT ASC";
        $auditRows = $db->query($sqlAudit, [$accessnumber])->getResultArray();

        foreach ($auditRows as $row) {
            $isUnval = $row['EVENT_TYPE'] === 'UNVAL';
            $result['validation'][] = [
                'type' => $row['EVENT_TYPE'],
                'user' => trim($row['USERID']),
                'datetime' => $row['EVENT_AT'] ? date('Y-m-d H:i:s', strtotime($row['EVENT_AT'])) : null,
                'reason' => $isUnval ? trim($row['REASON']) : null
            ];
        }

        $sqlTube = "SELECT TUBENUMBER, USERID, STATUS, LOGDATE
                    FROM GDC_CMOD.dbo.AUDIT_TUBES
                    WHERE ACCESSNUMBER = ?
                    ORDER BY LOGDATE ASC";
        $tubeRows = $db->query($sqlTube, [$accessnumber])->getResultArray();

        foreach ($tubeRows as $row) {
            $action = $row['STATUS'] == 1 ? 'COLLECTED' : 'UNRECEIVED';
            $result['sample_collection'][] = [
                'tubenumber' => trim($row['TUBENUMBER']),
                'user' => trim($row['USERID']),
                'datetime' => $row['LOGDATE'] ? date('Y-m-d H:i:s', strtotime($row['LOGDATE'])) : null,
                'action' => $action
            ];
        }

        $sqlSpTubes = "SELECT SAMPLETYPE, TUBESTATUS, COLLECTIONDATE, LOGUSERID
                       FROM glendb.dbo.SP_TUBES
                       WHERE SP_ACCESSNUMBER = ? AND TUBESTATUS = 4
                       ORDER BY COLLECTIONDATE ASC";
        $spTubeRows = $db->query($sqlSpTubes, [$accessnumber])->getResultArray();

        foreach ($spTubeRows as $row) {
            $result['tube_received'][] = [
                'sampletype' => trim($row['SAMPLETYPE']),
                'tubestatus' => (int)$row['TUBESTATUS'],
                'datetime' => $row['COLLECTIONDATE'] ? date('Y-m-d H:i:s', strtotime($row['COLLECTIONDATE'])) : null,
                'user' => trim($row['LOGUSERID'])
            ];
        }

        $sqlRequests = "SELECT STEPTYPE, STEPDATE, STEPSTATUS
                        FROM GDC_CMOD.dbo.AUDIT_REQUESTS
                        WHERE ACCESSNUMBER = ? AND STEPTYPE IN ('PRINT', 'GEN_PDF', 'REGEN_PDF')
                        ORDER BY STEPDATE ASC";
        $requestRows = $db->query($sqlRequests, [$accessnumber])->getResultArray();

        foreach ($requestRows as $row) {
            $result['pdf_generation'][] = [
                'type' => $row['STEPTYPE'],
                'status' => trim($row['STEPSTATUS']),
                'datetime' => $row['STEPDATE'] ? date('Y-m-d H:i:s', strtotime($row['STEPDATE'])) : null,
                'user' => session()->get('userid')
            ];
        }

        return $this->respond(['status' => 'success', 'data' => $result]);
    }
}
