<?php

namespace common\components;


use common\models\AutopsyDiagnosis;
use common\models\CaseAutopsy;
use common\models\CaseDish;
use common\models\CaseFish;
use common\models\CaseFlow;
use common\models\CaseFrozen;
use common\models\CaseHpv;
use common\models\CaseMolecular;
use common\models\CaseNecropsy;
use common\models\ConstServiceCharge;
use common\models\ConstHospital;
use common\models\CaseSurgical;
use common\models\CaseStaining;
use common\models\CaseNonGyn;
use common\models\CasePap;
use common\models\CenterApprove;
use common\models\ConstStatus;
use common\models\CoPathologist;
use common\models\CytoGeneralCategorization2;
use common\models\CytoHpvDiagnosis;
use common\models\CytoNonGynDiagnosis;
use common\models\CytoPapDiagnosis;
use common\models\CytoPapTestMethod;
use common\models\CytoSpecimenAdequacy2;
use common\models\CytoSpecimenAdequacy3;
use common\models\DishDiagnosis;
use common\models\FinanceServiceCharge;
use common\models\FishDiagnosis;
use common\models\FlowDiagnosis;
use common\models\FrozenDiagnosis;
use common\models\HisRequestTestList;
use common\models\HisResultList;
use common\models\HistoStaining;
use common\models\HospitalImport;
use common\models\HospitalServiceCharge;
use common\models\ImmunoStaining;
use common\models\LabReq;
use common\models\LabResult;
use common\models\MolecularDiagnosis;
use common\models\NecropsyDiagnosis;
use common\models\SurgicalDiagnosis;
use common\models\PathologistRemark;
use common\models\SendHis;
use common\models\SendReportHis;
use common\models\SysConfig;
use common\models\UserLog;
use DateInterval;
use DateTime;
use Yii;
use yii\base\Component;
use yii\db\Expression;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\httpclient\Client;

class Pathology extends Component
{

    /**
     * Get Hospital Price function
     *
     * @param integer $hospital_id
     * @param integer $charge_id
     * @return void
     */
    public function getHosPrice($hospital_id, $charge_id)
    {
        $charge = ConstServiceCharge::findOne(['id' => $charge_id]);
        $hospital = ConstHospital::findOne(['id' => $hospital_id]);
        if (!$charge || !$hospital) {
            return 0;
        }
        $hospital_charge = HospitalServiceCharge::findOne(['const_hospital_id' => $hospital->id, 'const_service_charge_id' => $charge->id, 'status' => 1]);

        if ($hospital_charge) {
            return $hospital_charge->price;
        }
        return $charge->price;
    }

    /**
     * หาเดือนไทยตามตัวเลข
     * @param string $number
     * @return string
     */
    public function getMonthNameThai($month_no)
    {
        $month_thai = array(
            '0' => '-',
            '1' => 'มกราคม',
            '2' => 'กุมภาพันธ์',
            '3' => 'มีนาคม',
            '4' => 'เมษายน',
            '5' => 'พฤษภาคม',
            '6' => 'มิถุนายน',
            '7' => 'กรกฎาคม',
            '8' => 'สิงหาคม',
            '9' => 'กันยายน',
            '10' => 'ตุลาคม',
            '11' => 'พฤศจิกายน',
            '12' => 'ธันวาคม'
        );
        return $month_thai[$month_no];
    }

    /**
     * Get Hospital Price function
     *
     * @param integer $hospital_id
     * @param integer $charge_id
     * @return void
     */
    public function getHosDF($hospital_id, $charge_id)
    {
        $charge = ConstServiceCharge::findOne(['id' => $charge_id]);
        $hospital = ConstHospital::findOne(['id' => $hospital_id]);
        if (!$charge || !$hospital) {
            return 0;
        }
        $hospital_charge = HospitalServiceCharge::findOne(['const_hospital_id' => $hospital->id, 'const_service_charge_id' => $charge->id, 'status' => 1]);

        if ($hospital_charge) {
            return $hospital_charge->df;
        }
        return $charge->df;
    }

    /**
     * @param $prefix
     * @return false|string
     */
    public function getImedCaseType($case)
    {
        if ($case == 'S') { // Surgical
            return 'surgical';
        }
        if ($case == 'O') { // Surgical Outlab
            return 'surgical';
        }
        if ($case == 'N') { // Non-Gyn
            return 'non-gyn';
        }
        if ($case == 'B') { // BAL
            return 'non-gyn';
        }
        if ($case == 'F') { // FNA
            return 'non-gyn';
        }
        if ($case == 'P') { // Pap Smear
            return 'pap';
        }
        if ($case == 'C') { // Co-test
            return 'pap';
        }
        if ($case == 'H') { // HPV
            return 'pap';
        }
        if ($case == 'L') { // LBC
            return 'pap';
        }
        return false;
    }

    /**
     * @param $id_case
     * @return false|string
     */
    public function getCaseType($id_case)
    {
        $case = $id_case !== null ? substr($id_case, 0, 1) : '';

        if ($case == 'S') { // Surgical
            return 'surgical';
        }
        if ($case == 'O') { // Surgical Outlab
            return 'surgical';
        }
        if ($case == 'I') { // Surgical Outlab
            return 'surgical';
        }
        if ($case == 'M') { // Surgical Outlab
            return 'surgical';
        }
        if ($case == 'N') { // Non-Gyn
            return 'non-gyn';
        }
        if ($case == 'B') { // BAL
            return 'non-gyn';
        }
        if ($case == 'F') { // FNA
            return 'non-gyn';
        }
        if ($case == 'P') { // Pap Smear
            return 'pap';
        }
        if ($case == 'C') { // Co-test
            return 'pap';
        }
        if ($case == 'H') { // HPV
            return 'pap';
        }
        if ($case == 'L') { // LBC
            return 'pap';
        }

        return false;
    }

    /**
     * @param $id_case
     * @return CaseNonGyn|CasePap|CaseSurgical|void|null
     */
    public function getCase($id_case)
    {
        $case_type = $this->getCaseType($id_case);
        if ($case_type === 'surgical') {
            return CaseSurgical::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'non-gyn') {
            return CaseNonGyn::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'pap') {
            return CasePap::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'frozen') {
            return CaseFrozen::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'fish') {
            return CaseFish::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'dish') {
            return CaseDish::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'autopsy') {
            return CaseAutopsy::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'flow') {
            return CaseFlow::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'molecular') {
            return CaseMolecular::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'necropsy') {
            return CaseNecropsy::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'hpv') {
            return CaseHpv::findOne(['id_case' => $id_case]);
        }
    }

    /**
     * หาว่าเป็นโรงพยาบาลรัฐหรือเอกชนแบบไม่มีรูปแบบ
     * @param unknown $p
     * @return string
     */
    public function getPrivateText($p)
    {
        return $p == 0 ? 'รัฐบาล' : 'เอกชน';
    }

    /**
     * @param $p
     * @return string|null
     */
    public function getPrivate($p)
    {
        if ($p == 0) {
            $b = '<span class="badge bg-success">รัฐบาล</span>';
        } else if ($p == 1) {
            $b = '<span class="badge bg-danger">เอกชน</span>';
        } else if ($p == 2) {
            $b = '<span class="badge bg-primary">กรม</span>';
        } else {
            $b = null;
        }

        return $b;
    }

    public function formatHl7DatetimeDiagAt($datetimme)
    {
        $dateTime = DateTime::createFromFormat('d/m/Y H:i:s', $datetimme);
        $formattedDate = $dateTime->format('YmdHis');
        return $formattedDate;
    }
    public function formatHl7Datetime($datetime)
    {
        $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
        if ($dateTime === false) {
            return null; // หรือ throw Exception ก็ได้
        }
        return $dateTime->format('YmdHis'); // HL7 format
    }

    function birthToHl7Date($dateString)
    {
        if (empty($dateString)) {
            return '';
        }

        $formats = ['Y-m-d', 'd-m-Y', 'd/m/Y'];
        foreach ($formats as $format) {
            $dt = DateTime::createFromFormat($format, $dateString);
            if ($dt !== false) {
                return $dt->format('Ymd');
            }
        }
        return '';
    }

    /**
     * เก็บปลายเดือนหรือจ่ายเงินสด
     * @param unknown $c
     * @return string
     */
    public function getIsCash($c)
    {
        return $c == 0 ? 'เก็บปลายเดือน' : 'ชำระเงินสด';
    }

    /**
     * จัด Format DateTime ให้เป็น Y-m-d H:i:s จาก format 25/12/2023 12:45:00
     * @param $attribute
     * @return string
     */
    public function engDateTime($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{1,2}\s?\/\s?\d{1,2}\s?\/\s?\d{4}\s?\w*)/', $attribute)) {
            if (stripos($attribute, ':') !== false) {
                $dt = explode(' ', $attribute);
                $time = ' ' . trim($dt[1]);
            } else {
                $dt[0] = $attribute;
                $time = '';
            }

            $data = preg_split('/(\s?\/\s?)/', $dt[0]);
            $y = (int)$data[2];
            //$y = $y - 543;
            $collect_at = $y . '-' . $data[1] . '-' . $data[0] . $time;
        }
        return $collect_at;
    }

    /**
     * จัด Format DateTime ให้เป็น Y-m-d H:i:s จาก format 25/12/2023 12:45:00
     * @param $attribute
     * @return string
     */
    public function engDate($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{1,2}\s?\/\s?\d{1,2}\s?\/\s?\d{4}\s?\w*)/', $attribute)) {
            if (stripos($attribute, ':') !== false) {
                $dt = explode(' ', $attribute);
                $time = ' ' . trim($dt[1]);
            } else {
                $dt[0] = $attribute;
                $time = '';
            }

            $data = preg_split('/(\s?\/\s?)/', $dt[0]);
            $y = (int)$data[2];
            //$y = $y - 543;
            $collect_at = $y . '-' . $data[1] . '-' . $data[0];
        }
        return $collect_at;
    }

    /**
     * จัด Format DateTime ให้เป็น Y-m-d จาก format 25/12/2023 12:45:00
     * @param $attribute
     * @return string
     */
    public function engToDateOnly($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/', $attribute)) {
            if (stripos($attribute, ':') !== false) {
                $dt = explode(' ', $attribute);
                $time = ' ' . trim($dt[1]);
            } else {
                $dt[0] = $attribute;
                $time = '';
            }

            $data = preg_split('/(\s?\/\s?)/', $dt[0]);
            $y = (int)$data[2];
            //$y = $y - 543;
            $collect_at = $y . '-' . $data[1] . '-' . $data[0];
        }
        return $collect_at;
    }

    /**
     * จัด Format DateTime ให้เป็นแบบ 03/05/2023 00:00:00
     * @param $attribute
     * @return string|null
     */
    public function thaiDateTime($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\s?\w*)/', $attribute)) {

            if ($attribute == '0000-00-00 00:00:00') {
                $collect_at = null;
            } else {
                $check_date = explode('.', $attribute);
                if (isset($check_date[0])) {


                    $dt = explode(' ', $check_date[0]);
                    //$dt = explode(' ', $dt_t[0]);
                    if ($dt[1] == '00:00:00') {
                        $dt[1] = ' 00:00:00';
                    } else {
                        $dt[1] = ' ' . $dt[1];
                    }

                    $data = explode('-', $dt[0]);
                    $y = (int)$data[0];
                    //$y = $y;
                    $collect_at = $data[2] . '/' . $data[1] . '/' . $y . $dt[1];
                } //check date
            }
        }
        return $collect_at;
    }

    function calculateAge($birthdate)
    {
        // $birthdate ต้องอยู่ในรูปแบบ Y-m-d เช่น "1985-09-07"
        $today = new DateTime(); // วันที่ปัจจุบัน
        $birth = new DateTime($birthdate);

        // หาความต่างของวัน
        $diff = $today->diff($birth);

        return $diff->y; // คืนค่าเป็นจำนวนปี
    }

    /**
     * จัด Format DateTime ให้เป็นแบบ 03/05/2023 จาก Y-m-d H:i:s
     * @param $attribute
     * @return string|null
     */
    public function thaiDate($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/', $attribute)) {

            if ($attribute == '0000-00-00 00:00:00') {
                $collect_at = null;
            } else {
                $dt = explode(' ', $attribute);
                //$dt = explode(' ', $dt_t[0]);
                if ($dt[1] == '00:00:00') {
                    $dt[1] = ' 00:00:00';
                } else {
                    $dt[1] = ' ' . $dt[1];
                }

                $data = explode('-', $dt[0]);
                $y = (int)$data[0];
                //$y = $y;
                $collect_at = $data[2] . '/' . $data[1] . '/' . $y;
            }
        }
        return $collect_at;
    }


    /**
     * จัดรูปแบบวันที่เป็น 25/12/2023 แบบไม่มีเวลา จาก format 25/12/2023 12:45:00
     * @param $attribute
     * @return string|null
     */
    public function thaiToDateOnly($attribute)
    {
        $collect_at = $attribute;
        if (!empty($attribute) && preg_match('/(\d{1,2}\s?\/\s?\d{1,2}\s?\/\s?\d{4}\s?\w*)/', $attribute)) {

            if ($attribute == '00/00/0000 00:00:00') {
                $collect_at = null;
            } else {
                $dt = explode(' ', $attribute);
                $collect_at = $dt[0];
            }
        }
        return $collect_at;
    }

    public function thaiToDateTime($value, $withSeconds = true): string
    {
        if (empty($value) || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
            return '-';
        }
        $ts = is_numeric($value) ? (int)$value : strtotime($value);
        if ($ts === false) return (string)$value;

        $date = date('d/m/', $ts) . (date('Y', $ts) + 543);
        $time = $withSeconds ? date(' H:i:s', $ts) : date(' H:i', $ts);
        return $date . $time;
    }

    /**
     * รับวันที่รูปแบบไทย (เช่น 25/12/2568 หรือ 25/12/2568 16:28:10)
     * คืนค่าเป็นคริสตศักราชรูปแบบ "Y/m/d" หรือ "Y/m/d H:i:s"
     */
    public function thaiDateToEngSlash($value, bool $withSeconds = true): string
    {
        if (empty($value) || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
            return '-';
        }

        // กันเลขไทย
        $value = strtr((string)$value, ['๐' => '0', '๑' => '1', '๒' => '2', '๓' => '3', '๔' => '4', '๕' => '5', '๖' => '6', '๗' => '7', '๘' => '8', '๙' => '9']);

        // ถ้าเป็น DateTime / timestamp
        if ($value instanceof \DateTimeInterface) {
            $dt = (clone $value);
        } elseif (is_numeric($value)) {
            $dt = (new \DateTime())->setTimestamp((int)$value);
        } else {
            $dt = null;
            // จับ d/m/Y (+เวลา)
            if (preg_match('/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/', trim($value), $m)) {
                $d = (int)$m[1];
                $mo = (int)$m[2];
                $y = (int)$m[3];
                if ($y >= 2400) $y -= 543; // พ.ศ. -> ค.ศ.
                $h = isset($m[4]) ? (int)$m[4] : 0;
                $i = isset($m[5]) ? (int)$m[5] : 0;
                $s = isset($m[6]) ? (int)$m[6] : 0;
                $dt = new \DateTime(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $y, $mo, $d, $h, $i, $s));
            } else {
                try {
                    $dt = new \DateTime($value);
                    // ถ้าปีน่าจะเป็น พ.ศ. ให้หัก
                    $y = (int)$dt->format('Y');
                    if ($y >= 2400) {
                        $dt->setDate($y - 543, (int)$dt->format('m'), (int)$dt->format('d'));
                    }
                } catch (\Exception $e) {
                    return '-';
                }
            }
        }

        $thaiYear = (int)$dt->format('Y') + 543;
        $datePart = $dt->format('d/m/') . $thaiYear;
        $timePart = $withSeconds ? $dt->format(' H:i:s') : $dt->format(' H:i');
        return $datePart . $timePart;
    }

    /**
     * Undocumented function
     * จัดรูปแบบวันที่เป็น 2025/12/25 แบบไม่มีเวลา จาก format 25/12/2568
     * @param [type] $date
     * @return void
     */
    public function thaiDateOnly($value)
    {
        if (empty($value) || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
            return '-';
        }

        // รองรับหลายรูปแบบวันที่ทั่วไป
        $fmts = ['Y-m-d H:i:s', 'Y-m-d', 'd/m/Y H:i:s', 'd/m/Y'];
        $dt = $value instanceof \DateTimeInterface ? $value : null;

        if (!$dt) {
            foreach ($fmts as $f) {
                $dt = \DateTime::createFromFormat($f, $value);
                if ($dt instanceof \DateTimeInterface) break;
            }
            // ถ้ายัง parse ไม่ได้ ลองปล่อยให้ DateTime เดา
            if (!$dt) {
                try {
                    $dt = new \DateTime($value);
                } catch (\Exception $e) {
                    return '-';
                }
            }
        }

        $thaiYear = (int)$dt->format('Y') + 543;
        return $dt->format('d/m/') . $thaiYear; // เช่น 13/09/2568
    }

    /**
     * @param $number
     * @return string|null
     */
    public function getGender($number)
    {
        if ($number == 'M') {
            return 'ชาย';
        } else
            if ($number == 'F') {
            return 'หญิง';
        } else {
            return null;
        }
    }

    /*
     * Return ไม่ใช่ / ใช่ จาก 0,1
     */
    public function getYesNo($number)
    {
        if ($number == 0) {
            return 'ไม่ใช่';
        } else
            if ($number == 1) {
            return 'ใช่';
        } else {
            return null;
        }
    }

    public function getBlock($id_case)
    {
        $case_type = substr($id_case, 0, 1);

        if ($case_type == 'surgical') {
            $model = CaseSurgical::findOne(['id_case' => $id_case]);
            return $model->section_label;
        }
        if ($case_type == 'staining') {
            $model = CaseStaining::findOne(['id_case' => $id_case]);
            return $model->block_ex;
        }
    }

    public function getSurgicalNext($id_case)
    {
        $model = CaseSurgical::findOne(['id_case' => $id_case]);
        $surgical = CaseSurgical::find()->where(['>', 'id', $model->id])->andWhere(['status_id' => 1])->orderBy(['id' => SORT_ASC])->one();
        if ($surgical) {
            return $surgical->id_case;
        } else {
            return null;
        }
    }

    public function getSurgicalPrev($id_case)
    {
        $model = CaseSurgical::findOne(['id_case' => $id_case]);
        $surgical = CaseSurgical::find()->where(['<', 'id', $model->id])->andWhere(['status_id' => 1])->orderBy(['id' => SORT_DESC])->one();
        if ($surgical) {
            return $surgical->id_case;
        } else {
            return null;
        }
    }

    /**
     * @param object|null $model
     * @param bool $badge
     * @return string
     */
    public function getExpress($model, $badge = true)
    {
        // Check if $model is valid and has the necessary properties
        if ($model && isset($model->is_express) && $model->is_express == 1) {

            $mt = ['' => '', '3' => 'ผลด่วน 3 วัน', '5' => 'ผลด่วน 5 วัน', '7' => 'ผลด่วน 7 วัน'];

            if ($badge) {
                return '<span class="badge bg-danger">'
                    . $mt[$model->express_day]
                    . (!empty($model->express_at)
                        ? ' <small>(' . Yii::$app->pathology->thaiToDateOnly($model->express_at) . ')</small>'
                        : '')
                    . '</span>';
            } else {
                return !empty($model->express_at)
                    ? 'ขอผลด่วน <small>(' . Yii::$app->pathology->thaiToDateOnly($model->express_at) . ')</small>'
                    : '';
            }
        }
        return '';
    }

    /**
     * @param object|null $model
     * @param bool $badge
     * @return string
     */
    public function getExpressAutopsy($model, $badge = true)
    {
        // Check if $model is valid and has the necessary properties
        if ($model && isset($model->is_express) && $model->is_express == 1) {

            $mt = ['' => '', '1' => 'ผลด่วน 1 เดือน', '3' => 'ผลด่วน 3 เดือน'];

            if ($badge) {
                return '<span class="badge bg-danger">'
                    . $mt[$model->express_day]
                    . (!empty($model->express_at)
                        ? ' <small>(' . Yii::$app->pathology->thaiToDateOnly($model->express_at) . ')</small>'
                        : '')
                    . '</span>';
            } else {
                return !empty($model->express_at)
                    ? 'ขอผลด่วน <small>(' . Yii::$app->pathology->thaiToDateOnly($model->express_at) . ')</small>'
                    : '';
            }
        }
        return '';
    }

    /*public function getExpress($model, $badge = true)
    {
        //if($model->is_critical_diagnosis == 1) {
        if ($model->is_express == 1) {

            if ($badge == true) {
                $mt = ['' => '', '3' => 'ผลด่วน 3 วัน', '5' => 'ผลด่วน 5 วัน', '7' => 'ผลด่วน 7 วัน'];
                return ('<span class="badge bg-danger">' . $mt[$model->express_day] . ' ' . (!empty($model->express_at) ? '<small>(' . Yii::$app->pathology->thaiToDateOnly($model->express_at) . ')</small>' : '') . '</span>');
            } else {
                return !empty($model->express_at) ? 'ขอผลด่วน <small>(' . $model->express_at . ')</small>' : '';
            }
        }
        return '';
    }*/

    /**  Cut name if name have (...)
     *
     * @param string $realname
     *
     * @return string $name
     *
     * @example Q::subStringName("นางรัชตา (ดวงตรา) ใสกระจ่าง (คงมั่น)");
     *
     */
    public function subStringName($realname)
    {
        //        $user_id = 11;
        $name_full = "";
        $name = "";
        /* --------------------------from ID--------------------------------- */
        //        $model = User::model()->findByPk((int) $user_id);
        //        if (sizeof($model) > 0) {
        //            $name_full = $model->realname;
        //        }
        //        echo "<br />name_full: " . $name_full;
        /* --------------------------end from ID---------------------------- */
        $name_full = $realname;

        $full = strlen($name_full);
        $loop = true;
        $name = $name_full;
        while ($loop) {
            $sub_1 = strpos($name, '(', 0);
            $sub_2 = strpos($name, ')', 0);
            if ($sub_1 != "" && $sub_2 != "") {
                //                echo "<br />sub_1: " . $sub_1;
                //                echo "<br />sub_2: " . $sub_2;

                $n_1 = substr($name, 0, ($sub_1) - 1);
                $n_2 = substr($name, $sub_2 + 1, $full);
                //                echo "<br />n_1: " . $n_1;
                //                echo "<br />n_2: " . $n_2;

                if ($n_1 != "" && $n_2 != "") {
                    $name = $n_1 . " " . $n_2;
                } else if ($n_1 != "" && $n_2 == "") {
                    $name = $n_1;
                } else if ($n_1 == "" && $n_2 != "") {
                    $name = $n_2;
                }

                //                echo "<br /> --".$name."--<br /><br />";

                $loop = true;
            } else {
                //                $name = "";
                $loop = false;
            }
        } //end  while ($loop) {
        //        echo "<br />name: " . $name;

        return $name;
    }

    /*
     * แสดง request url หากมี file จริงค่อยแสดง
     */
    public function getRequest($id_case)
    {
        $case_type = substr($id_case, 0, 1);

        if ($case_type === 'surgical') {
            $case = CaseSurgical::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'non-gyn') {
            $case = CaseNonGyn::findOne(['id_case' => $id_case]);
        }
        if ($case_type === 'pap') {
            $case = CasePap::findOne(['id_case' => $id_case]);
        }

        if ($case_type === 'frozen') {
            $case = CaseFrozen::findOne(['id_case' => $id_case]);
        }
        if (!empty($case->files)) {
            return explode(',', $case->files);
        }
        /*if (file_exists(Yii::getAlias('@webroot') . '/uploads/requests/' . $id_case . '.pdf')) {
            return Html::a('<span class="glyphicon glyphicon-file"></span> ใบส่งตรวจ', Yii::getAlias('@web') . '/uploads/requests/' . $id_case . '.pdf', ['class' => 'linksWithTarget btn btn-info ' . $btn, 'target' => '_blank']);
        }*/
        return false;
    }

    public function getCaseDate($id_case, $role = NULL)
    {
        $model = Yii::$app->pathology->getCase($id_case);
        $case_type = Yii::$app->pathology->getCaseType($id_case);
        $return = null;
        if ($model && $model->status_id < 18) {

            $sql = "
            SELECT COUNT(*) AS cnt_dateoff
            FROM hr_day_off 
            WHERE (off_at BETWEEN '" . $this->engDate($model->receive_at) . "' AND NOW()) AND (DAYNAME(off_at) <> 'Saturday') AND (DAYNAME(off_at) <> 'Sunday')
            ";
            $data = Yii::$app->db->createCommand($sql)->queryOne();

            $data_cnt = isset($data['cnt_dateoff']) ? $data['cnt_dateoff'] : 0;
            $date1 = new DateTime(isset($model->receive_at) ? $this->engDate($model->receive_at) : '');
            $date2 = new DateTime();
            $diff = $date2->diff($date1); //->format("%a");
            $date = $diff->days;
            $count_weekend = $model->receive_at
                ? $this->countWeekendDays(strtotime($this->engDate($model->receive_at)), time())
                : 0;
            $date = $date - $count_weekend - $data_cnt;

            $remark = "";
            if ($date > 4 and $role == "patho") { // remark button
                $remark = $this->PathoRemark($id_case, $model->status_id);
                if (!$remark) {
                    $remarkbutton = Html::a('<i class="fa fa-exclamation-circle"></i> แจ้งวันที่ออกผล', ['/pathologist/do/patho-remark', 'id_case' => $id_case], ['class' => 'btn btn-sm  btn-default']) . "<br>";
                } else {
                    $remarkbutton = "";
                }
                $remark = "<small><br>" . $remarkbutton . Html::a($remark, ['/pathologist/do/patho-remark', 'id_case' => $id_case]) . "</small>";
            }

            if ($case_type == 'surgical') {
                $immuno = ImmunoStaining::findOne(['id_case' => $id_case]);
                $histo = HistoStaining::findOne(['id_case' => $id_case]);

                $surgical = CaseSurgical::findOne(['id_case' => $id_case]);
                if ($surgical->bone == 1) {
                    if ($date == 12) {
                        $return = '<span class="text-info"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                    } else if ($date == 13) {
                        $return = '<span class="text-warning"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                    } else if ($date > 13) {
                        $return = '<span class="red"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span> ' . $remark;
                    }
                }

                if ($immuno || $histo) {
                    if ($date == 5) {
                        $return = '<span class="text-info"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน(ย้อม)"></span> ' . $date . ' วัน(ย้อม)</span>';
                    } else if ($date == 6) {
                        $return = '<span class="text-warning"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน(ย้อม)"></span> ' . $date . ' วัน(ย้อม)</span>';
                    } else if ($date > 6) {
                        $return = '<span class="red"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน(ย้อม)"></span> ' . $date . ' วัน(ย้อม)</span> ' . $remark;
                    }
                } else {
                    if ($date == 3) {
                        $return = '<span class="text-info"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                    } else if ($date == 4) {
                        $return = '<span class="text-warning"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                    } else if ($date > 4) {
                        $return = '<span class="text-danger"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span> ' . $remark;
                    }
                }
            } //sn

            if ($case_type == 'non-gyn' || $case_type == 'pap') {
                //return $date;
                if ($date == 3) {
                    $return = '<span class="text-info"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                } else if ($date == 5) {
                    $return = '<span class="text-warning"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                } else if ($date > 5) {
                    $return = '<span class="text-danger"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span> ' . $remark;
                } /*else {
                    $return = '<span class="text-danger"><span class="fa fa-circle" data-toggle="tooltip" data-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span> ' . $remark;
                }*/
            } //cyto
        }
        return $return;
    }


    /**
     * @param $model
     * @return string
     */
    public function getOut($model, $amount = true)
    {
        $sql = "
    SELECT COUNT(balance) AS cnt
    FROM parcel_name
    WHERE balance < 2
";
        $data = Yii::$app->db->createCommand($sql)->queryOne();

        // Check if the condition is met
        if ($data['cnt'] > 0) {
            // Check if $amount is true
            if ($amount == true) {
                return !empty($model->balance) ? '<span class="badge bg-danger">ปริมาณเหลือขั้นต่ำ</span>' : '';
            }
        }
    }

    public function getCaseDateReport($id_case, $role = NULL)
    {
        $model = Yii::$app->pathology->getCase($id_case);
        $case_type = Yii::$app->pathology->getCaseType($id_case);

        if (!$model) {
            return false;
        }
        $return = null;
        if ($model->status_id < 18) {

            $sql = "
            SELECT COUNT(*) AS cnt_dateoff
            FROM hr_day_off
            WHERE (off_at BETWEEN '" . $this->engDateTime($model->register_at) . "' AND CURRENT_DATE)
            AND (DAYOFWEEK(off_at) <> 1) -- Exclude Sunday (1)
            AND (DAYOFWEEK(off_at) <> 7) -- Exclude Saturday (7)            
            ";
            /*
            $sql = "
            SELECT COUNT(*) AS cnt_dateoff
            FROM hr_day_off
            WHERE (off_at BETWEEN '" . $this->engDateTime($model->register_at) . "' AND '" . $this->engDateTime($model->pathologist_at) . "')
            AND DAYOFWEEK(off_at) NOT IN (1, 7)  -- Exclude Sunday (1) and Saturday (7)
            ";
            */
            $data = Yii::$app->db->createCommand($sql)->queryOne();

            $data_cnt = isset($data['cnt_dateoff']) ? $data['cnt_dateoff'] : 0;
            $date1 = new DateTime(isset($model->register_at) ? $this->engDateTime($model->register_at) : '');
            $date2 = new DateTime(isset($model->pathologist_at) ? $this->engDateTime($model->pathologist_at) : '');
            $date = $date2->diff($date1)->format("%a");
            $count_weekend = $this->countWeekendDays(strtotime($this->engDateTime($model->register_at)), time());
            $date = $date - $count_weekend - $data_cnt;

            if ($case_type == 'non-gyn' || $case_type == 'pap') {
                if ($date == 4) {
                    $return = '<span class="text-info"><span class="fa fa-circle" data-bs-toggle="tooltip" data-bs-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                } else if ($date == 5) {
                    $return = '<span class="text-warning"><span class="fa fa-circle" data-bs-toggle="tooltip" data-bs-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span>';
                } else if ($date > 5) {
                    $return = '<span class="text-danger"><span class="fa fa-circle" data-bs-toggle="tooltip" data-bs-placement="top" title="' . $date . ' วัน"></span> ' . $date . ' วัน</span> ';
                }
            } //cyto
        }
        return $return;
    }

    public function getCaseDateAutopsy($id_case, $role = NULL)
    {
        $model = Yii::$app->pathology->getCase($id_case);
        $case_type = Yii::$app->pathology->getCaseType($id_case);

        if (!$model) {
            return false;
        }
        $return = null;
        if ($model->status_id < 18) {

            $date1 = new DateTime($this->engDateTime($model->register_at));

            $targetDate = clone $date1;
            $targetDate->add(new DateInterval('P91D'));
            $diff = $targetDate->diff(new DateTime());
            $date = $diff->format('%a');

            if ($date >= 0) {
                if ($date <= 91 && $date >= 0) {
                    $return = '<span class="text-danger"><span class="fa fa-circle" data-bs-toggle="tooltip" data-bs-placement="top" title="' . $date . ' วัน"></span> ' . 'ครบกำหนดออกผลภายใน ' . $date . ' วัน</span> ';
                }

                sleep(1); // wait for 1 second before updating the countdown
            }
        }
        return $return;
    }

    public function PathoRemark($id_case, $status_id)
    {
        $model = PathologistRemark::findOne(['id_case' => '' . $id_case . '']);
        if ($model and $status_id != 16) {
            return "<span class='text text-danger'>ผลออก " . $model->report_maybe . " <br>" . $model->remark . "</span>";
        }
    }

    public function countWeekendDays($start, $end)
    {
        // $start in timestamp
        // $end in timestamp


        $iter = 24 * 60 * 60; // whole day in seconds
        $count = 0; // keep a count of Sats & Suns

        for ($i = $start; $i <= $end; $i = $i + $iter) {
            if (Date('D', $i) == 'Sat' || Date('D', $i) == 'Sun') {
                $count++;
            }
        }
        return $count;
    }

    //find ** from gross
    public function isFindText($text = '', $find = '')
    {
        if (!empty($text) && !empty($find)) {
            return strpos($text, $find);
        }
        return false;
    }

    public function getPrefix($id_case)
    {
        return substr($id_case, 0, 2);
    }

    /**
     * @param $status_id
     * @return void
     */
    public function getStatus($status_id)
    {
        $model = ConstStatus::findOne($status_id);
        if ($model->id == 20) {
            return '<span class="badge bg-danger">' . $model->status . '</span>';
        }
        if ($model->id == 19) {
            return '<span class="badge bg-danger">' . $model->status . '</span>';
        }
        if ($model->id == 18) {
            return '<span class="badge bg-success">' . $model->status . '</span>';
        }
        if ($model->id == 17) {
            return '<span class="badge bg-success">' . $model->status . '</span>';
        }
        if ($model->id == 16) {
            return '<span class="badge bg-info">' . $model->status . '</span>';
        }
        if ($model->id == 15) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }
        if ($model->id == 14) {
            return '<span class="badge bg-primary">' . $model->status . '</span>';
        }
        if ($model->id == 13) {
            return '<span class="badge bg-danger">' . $model->status . '</span>';
        }
        if ($model->id == 12) {
            return '<span class="badge bg-info">' . $model->status . '</span>';
        }
        if ($model->id == 11) {
            return '<span class="badge bg-success">' . $model->status . '</span>';
        }
        if ($model->id == 10) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }
        if ($model->id == 9) {
            return '<span class="badge bg-success">' . $model->status . '</span>';
        }
        if ($model->id == 8) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }
        if ($model->id == 7) {
            return '<span class="badge bg-info" style="background-color: #7366ff">' . $model->status . '</span>';
        }
        if ($model->id == 6) {
            return '<span class="badge bg-primary">' . $model->status . '</span>';
        }
        if ($model->id == 5) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }
        if ($model->id == 4) {
            return '<span class="badge bg-success">' . $model->status . '</span>';
        }
        if ($model->id == 3) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }
        if ($model->id == 2) {
            return '<span class="badge bg-warning">' . $model->status . '</span>';
        }

        if ($model->id == 1) {
            return '<span class="badge bg-danger">' . $model->status . '</span>';
        }
        return $model->status;
    }


    public function getCaseTypeReq($case)
    {
        if ($case == 'S') { // Surgical
            return 'surgical';
        }
        if ($case == 'N') { // Non-Gyn
            return 'non-gyn';
        }
        if ($case == 'B') { // BAL
            return 'non-gyn';
        }
        if ($case == 'F') { // FNA
            return 'non-gyn';
        }
        if ($case == 'P') { // Pap Smear
            return 'pap';
        }
        if ($case == 'C') { // Co-test
            return 'pap';
        }
        if ($case == 'H') { // HPV
            return 'pap';
        }
        if ($case == 'L') { // LBC
            return 'pap';
        }
        return false;
    }

    /**
     * @param $report_type
     * @return int|void
     */
    public function getSurgicalDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'opinion') {
            return 10;
        }
        if ($report_type == 'outlab') {
            return 11;
        }
        if ($report_type == 'consult_outlab') {
            return 12;
        }
    }

    /**
     * @param $report_type
     * @return int|void
     */
    public function getNonGynDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'opinion') {
            return 10;
        }
        if ($report_type == 'outlab') {
            return 11;
        }
        if ($report_type == 'consult_outlab') {
            return 12;
        }
    }

    /**
     * @param $report_type
     * @return int|void
     */
    public function getPapDiagnosisStatusId($report_type)
    {

        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'opinion') {
            return 10;
        }
        if ($report_type == 'outlab') {
            return 11;
        }
        if ($report_type == 'consult_outlab') {
            return 12;
        }
    }

    public function getFrozenDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'outlab') {
            return 10;
        }
    }

    public function getDishDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'outlab') {
            return 10;
        }
    }

    public function getAutopsyDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'opinion') {
            return 10;
        }
        if ($report_type == 'outlab') {
            return 11;
        }
        if ($report_type == 'consult_outlab') {
            return 12;
        }
    }

    public function getMolecularDiagnosisStatusId($report_type)
    {
        if ($report_type == 'preliminary') {
            return 4;
        }
        if ($report_type == 'final') {
            return 5;
        }
        if ($report_type == 'addendum') {
            return 6;
        }
        if ($report_type == 'corrected') {
            return 7;
        }
        if ($report_type == 'revised') {
            return 8;
        }
        if ($report_type == 'consult') {
            return 9;
        }
        if ($report_type == 'outlab') {
            return 10;
        }
    }

    /**
     * @param $id_case
     * @return bool|void
     */
    public function getCritical($id_case)
    {
        $critical = false;

        $case_type = $this->getCaseType($id_case);
        if ($case_type == 'surgical') {
            $diag = SurgicalDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'non-gyn') {
            $diag = CytoNonGynDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'pap') {
            $diag = CytoPapDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'frozen') {
            $diag = FrozenDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'dish') {
            $diag = FrozenDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'fish') {
            $diag = FishDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'flow') {
            $diag = FlowDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'molecular') {
            $diag = MolecularDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'autopsy') {
            $diag = AutopsyDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'necropsy') {
            $diag = NecropsyDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }

        if ($case_type == 'hpv') {
            $diag = HpvDiagnosis::findOne(['id_case' => $id_case, 'is_critical_diagnosis' => 1]);
            return isset($diag) ? true : false;
        }
    }

    /**
     * @param $id_case
     * @return void
     */
    public function getHn($id_case)
    {
        $hn = false;
        $case_type = $this->getCaseType($id_case);
        if ($case_type == 'surgical') {
            $h_n = CaseSurgical::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'non-gyn') {
            $h_n = CaseNonGyn::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'pap') {
            $h_n = CasePap::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'frozen') {
            $h_n = CaseFrozen::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'fish') {
            $h_n = CaseFish::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'dish') {
            $h_n = CaseDish::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'molecular') {
            $h_n = CaseMolecular::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'flow') {
            $h_n = FlowDiagnosis::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'autopsy') {
            $h_n = AutopsyDiagnosis::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }

        if ($case_type == 'necropsy') {
            $h_n = NecropsyDiagnosis::findOne(['id_case' => $id_case, 'h_n' => $id_case->h_n]);
            return isset($h_n) ? true : false;
        }
    }


    /*
     * รับค่าจากการ Search จาก 03/10/2559 (d/m/Y) แปลงเป็น 2016-10-03 (Y-m-d)
     * @return Y-m-d format
     */
    public function searchDate($date)
    {
        if (empty($date)) {
            return null;
        }
        $data = preg_split('/(\s?\/\s?)/', $date);
        $y = (int)$data[2];
        //$y = $y - 543;
        return $y . '-' . $data[1] . '-' . $data[0];
    }

    public function searchDateStart($date)
    {
        if (empty($date)) {
            return null;
        }
        $data = preg_split('/(\s?\/\s?)/', $date);
        $y = (int)$data[2];
        //$y = $y - 543;
        return $y . '-' . $data[1] . '-' . $data[0] . ' 00:00:00';
    }

    public function searchDateEnd($date)
    {
        if (empty($date)) {
            return null;
        }
        $data = preg_split('/(\s?\/\s?)/', $date);
        $y = (int)$data[2];
        // $y = $y - 543;
        return $y . '-' . $data[1] . '-' . $data[0] . ' 23:59:59';
    }

    /*
     * แปลงค่าจากเดือนตัวเลขเป็นเดือนข้อความ
     */
    public function monthToString($month)
    {
        $mo = ['1' => 'มกราคม', '2' => 'กุมภาพันธ์', '3' => 'มีนาคม', '4' => 'เมษายน', '5' => 'พฤษภาคม', '6' => 'มิถุนายน', '7' => 'กรกฎาคม', '8' => 'สิงหาคม', '9' => 'กันยายน', '10' => 'ตุลาคม', '11' => 'พฤศจิกายน', '12' => 'ธันวาคม'];

        return $mo[$month];
    }

    public function getOldReport($imed_ln)
    {
        $pattern = '/([A-Z])(\d+)/';

        preg_match($pattern, $imed_ln, $matches);
        $text = $matches[1];
        $number = $matches[2];

        $case_type = Yii::$app->pathology->getImedCaseType($text);
        //return $case_type;
        //$directory = (Yii::getAlias('@webroot') . '/report/' . $case_type); // Replace with the actual directory path
        $directory_file = (Yii::getAlias('@web') . '/report/' . $case_type); // Replace with the actual directory path
        //$pattern = '/^'. $id_case . ' /i'; // Replace with your desired name pattern (regular expression
        //1S530000821
        //$prefix = substr($imed_ln, 1, 3);
        //$suffix = (int)substr($imed_ln, 4);
        //$output = $prefix . "-" .
        //    str_pad($suffix, 5, "0", STR_PAD_LEFT); // Add "-"
        return $directory_file . '/' . $imed_ln . '.pdf';


        /*$pdfFiles = FileHelper::findFiles($directory, [
            'only' => ['*.pdf'], // Only search for PDF files
            'filter' => function ($path) use ($output, $directory_file) {
                $filename = basename($path);
                if ($filename === $output) {
                    return Html::a('<i data-feather="file-text" style="width: 14px; margin-bottom: -7px"></i> View Report', $directory_file . $output . '.pdf', ['class' => 'btn btn-sm btn-info', 'target' => '_blank']);
                }
            },
        ]);*/
    }


    public function getGenderHis($gender)
    {
        if ($gender == 'M') {
            return 1;
        } else if ($gender == 'F') {
            return 2;
        } else {
            return 0;
        }
    }
    /**
     * request his hn
     *
     * @param [type] $id_case
     * @return void
     */
    public function requestHisHn($id_case)
    {
        $case_type = $this->getCaseType($id_case);
        $case = $this->getCase($id_case);

        /**
         * ส่งข้อมูลผู้ป่วยไปที่ HIS
         *
        POST:: http://172.16.64.22:3439/patho/pathoPatient/newHN
        headers :: Authorization
        bodyData = {
            "prename" :  "นาย", // คำนำหน้าชื่อผู้ป่วย
            "firstname" :  "ทดสอบ4", // ชื่อผู้ป่วย
            "lastname" :  "พยาธิลงทะเบียน4", // นามสกุลผู้ป่วย
            "citizencardno" :  "1066467024972", // หมายเลขประชาชนผู้ป่วย
            "birthdatetime" :  "1980-07-01 00:00:00", // วันเดือนปีที่เกิดผู้ป่วย
            "sex" :  "1", // รหัสเพศผู้ป่วย
            "house" :  "ที่อยู่ทดสอบ45", // เลขที่บ้าน
            "moo" :  "หมู่ทดสอบ45", // เลขที่หมู่/ชุมชน
            "soy" :  "ซอยทดสอบ45", // ชื่อตรอก/ซอย
            "road" :  "ถนนทดสอบ45", // ชื่อถนน
            "tambon" :  "220102", // รหัสตำบล
            "amphur" :  "220100", // รหัสอำเภอ
            "province" :  "220000", // รหัสจังหวัด
            "postcode" :  "22000", // รหัสไปรษณีย์
            "phone" :  "999666999", // หมายเลขโทรศัพท์ผู้ป่วย
            "email" :  "อีเมลทดสอบ", // ที่อยู่จดหมายอิเลคทรอนิค
            "marriage" :  "2", // สภาพสมรส
            "occupation" :  "403", // อาชีพ
            "religious" :  "1", // ศาสนา
            "race" :  "99", // เชิ้อชาติ
            "citizenship" :  "99" // สัญชาติ
        }
         */

        if ($case) {
            // Target URL for the POST request
            $targetUrl = 'http://172.16.64.22:3439/patho/pathoPatient/newHN';

            // Data to be sent in the POST request
            $postData = [
                'prename' =>  $case->title->name, // คำนำหน้าชื่อผู้ป่วย
                'firstname' =>  $case->given_name, // ชื่อผู้ป่วย
                'lastname' =>  $case->surname, // นามสกุลผู้ป่วย
                'citizencardno' =>  str_replace('-', '', $case->id_card), // หมายเลขประชาชนผู้ป่วย
                'birthdatetime' =>  $this->engDate($case->birthdate), // วันเดือนปีที่เกิดผู้ป่วย
                'sex' =>  $this->getGenderHis($case->gender), // รหัสเพศผู้ป่วย
                'house' =>  $case->house, // เลขที่บ้าน
                "moo" =>  $case->moo, // เลขที่หมู่/ชุมชน
                "soy" =>  $case->soy, // ชื่อตรอก/ซอย
                "road" =>  $case->road, // ชื่อถนน
                "tambon" =>  $case->tambon, // รหัสตำบล
                "amphur" =>  $case->amphur, // รหัสอำเภอ
                "province" =>  $case->province, // รหัสจังหวัด
                "postcode" =>  $case->postcode, // รหัสไปรษณีย์
                "phone" =>  $case->phone, // หมายเลขโทรศัพท์ผู้ป่วย
                "email" =>  $case->email, // ที่อยู่จดหมายอิเลคทรอนิค
                "marriage" =>  $case->marriage, // สภาพสมรส
                "occupation" =>  $case->occupation, // อาชีพ
                "religious" =>  $case->religious, // ศาสนา
                "race" =>  $case->race, // เชิ้อชาติ
                "citizenship" =>  $case->citizenship // สัญชาติ
            ];

            // Custom headers for the request
            $headers = [
                'Content-Type: application/json', // Adjust the content type accordingly
                'Authorization: ' . Yii::$app->params['HISSecret'] . '' // Include any other headers you need
            ];

            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $targetUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute cURL session and get the response
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                ///echo 'Curl error: ' . curl_error($ch);
                error_log('Curl error: ' . curl_error($ch));
                return false;
            }

            // Close cURL session
            curl_close($ch);

            // Process the response
            //echo $response;
            error_log($response);
            return true;
        }
        return false;
    }

    /**
     * ส่งข้อมูลไปเข้าคิวรอส่ง HIS Report
     *
     * @param integer $approve_id
     * @param string $id_case
     * @param string $report_type
     * @param integer $diagnosis_id
     * @return boolean
     */
    public function sendHis($approve_id, $id_case, $report_type, $diagnosis_id)
    {
        $model = new SendHis();
        $model->approve_id = $approve_id;
        $model->id_case = $id_case;
        $model->report_type = $report_type;
        $model->diagnosis_id = $diagnosis_id;
        if ($model->save()) {
            return true;
        }

        return false;
    }

    /**
     * ส่งข้อมูลผลการตรวจไปยัง HIS
     *
     * @param integer $approve_id
     * @param string $id_case
     * @param integer $diagnosis_id
     * @return boolean
     */
    public function requestHisReport($approve_id, $id_case, $diagnosis_id)
    {
        $case_type = $this->getCaseType($id_case);
        $case = $this->getCase($id_case);

        $release = CenterApprove::findOne($approve_id);
        $hospital_import = HospitalImport::find()->where(['id_case' => $case->id_case])->orderBy(['id' => SORT_DESC])->one();

        if ($case) {
            if ($case_type == 'surgical') {
                $diagnosis = SurgicalDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = SurgicalDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'non-gyn') {
                $diagnosis = CytoNonGynDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = CytoNonGynDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'pap') {
                $diagnosis = CytoPapDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = CytoPapDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'frozen') {
                $diagnosis = FrozenDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = FrozenDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'dish') {
                $diagnosis = DishDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = DishDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'fish') {
                $diagnosis = FishDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = FishDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'flow') {
                $diagnosis = FlowDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = FlowDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'molecular') {
                $diagnosis = MolecularDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = MolecularDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'autopsy') {
                $diagnosis = AutopsyDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = AutopsyDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }
            if ($case_type == 'necropsy') {
                $diagnosis = NecropsyDiagnosis::findOne($diagnosis_id);
                $diagnosis_count = NecropsyDiagnosis::find()->where(['id_case' => $case->id_case])->count();
            }

            // Target URL for the POST request
            $targetUrl = 'http://172.16.64.22:3439/patho/pathoReport/result';

            // Data to be sent in the POST request
            $postData = [
                'cid' => str_replace('-', '', $case->id_card),
                'title_code' => $case->title->code,
                'first_name' => $case->given_name,
                'last_name' => $case->surname,
                'birthdate' => $this->engDate($case->birthdate),
                'age' => $case->age,
                'age_unit' => $case->age_unit,
                'report_type' => $diagnosis->report_type,
                'id_case' => $id_case,
                'ln' => $case->his_ln,
                'o_n' => $hospital_import->o_n,
                'approve_at' => isset($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : (isset($diagnosis->cytotech1_at) ? $this->engDateTime($diagnosis->cytotech1_at) : (isset($diagnosis->cytotech2_at) ? $this->engDateTime($diagnosis->cytotech2_at) : '')),
                'approve_by' => isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : (isset($diagnosis->cytotech1) ? $diagnosis->cytotech1->code : (isset($diagnosis->cytotech2) ? $diagnosis->cytotech2->code : '')),
                'release_at' => $this->engDateTime($release->release_at),
                'release_by' => $release->releaseBy->code,
                'sequence' => $diagnosis_count == 0 ? 1 : $diagnosis_count + 1,
                'link_all' => 'http://10.10.20.111/api/his/report-all?id_case=' . $case->id_case,
                'link_report' => 'http://10.10.20.111/api/his/report-case?id_case=' . $case->id_case . '&report_type=' . $diagnosis->report_type . '&diagnosis_id=' . $diagnosis->id
            ];

            // Custom headers for the request
            $headers = [
                'Content-Type: application/json', // Adjust the content type accordingly
                'Authorization: ' . Yii::$app->params['HISSecret'] . '' // Include any other headers you need
            ];

            $postDataJson = json_encode($postData);

            error_log($postDataJson);

            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $targetUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson); //http_build_query($postData));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute cURL session and get the response
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                ///echo 'Curl error: ' . curl_error($ch);
                error_log('Curl error: ' . curl_error($ch));
                return false;
            }

            // Close cURL session
            curl_close($ch);

            // Process the response
            //echo $response;
            error_log($response);

            $send_his = SendHis::find()->where(['approve_id' => $approve_id, 'id_case' => $id_case, 'report_type' => $diagnosis['report_type'], 'diagnosis_id' => $diagnosis_id])->andWhere(['is', 'is_send', new Expression('NULL')])->one();
            if (!$send_his) {
                Yii::$app->db->createCommand("INSERT INTO send_his (approve_id, id_case, report_type, diagnosis_id, is_send, send_at, response) 
                VALUES (:approve_id, :id_case, :report_type, :diagnosis_id, :is_send, :send_at, :response)", [
                    ':approve_id' => $approve_id,
                    ':id_case' => $id_case,
                    ':report_type' => $diagnosis['report_type'],
                    ':diagnosis_id' => $diagnosis_id,
                    ':is_send' => 1,
                    ':send_at' => date('Y-m-d H:i:s'),
                    ':response' => $response
                ])->execute();
            } else {
                Yii::$app->db->createCommand("
                    UPDATE send_his 
                    SET 
                        is_send = :is_send, 
                        send_at = :send_at, 
                        response = :response
                    WHERE approve_id = :approve_id AND id_case = :id_case AND report_type = :report_type AND diagnosis_id = :diagnosis_id", [
                    ':approve_id' => $approve_id,
                    ':id_case' => $id_case,
                    ':report_type' => $diagnosis['report_type'],
                    ':diagnosis_id' => $diagnosis_id,
                    ':is_send' => 1,
                    ':send_at' => date('Y-m-d H:i:s'),
                    ':response' => $response,
                ])->execute();
            }


            return true;
        }

        return false;
    }


    /**
     * ส่งข้อมูล Order Item ไปยัง HIS
     *
     * @param string $id_case
     * @param integer $order_id
     * @param string $action
     * @return boolean
     */
    public function requestHisOrderItem($id_case, $order_id, $action)
    {
        $case_type = $this->getCaseType($id_case);
        $case = $this->getCase($id_case);

        $hospital_import = HospitalImport::findOne($case->id_case);

        if ($case) {
            $charge = FinanceServiceCharge::findOne($order_id);
            $order_item = ConstServiceCharge::findOne($charge->charge_id);

            $count_charge = FinanceServiceCharge::find()->where(['id_case' => $case->id_case, 'charge_id' => $charge->charge_id])->count();

            /*if($action == 'create') {
                $charge_sq = $count_charge == 0 ? 1 : $count_charge + 1;
            } else {
                $charge_sq = $charge->sequence;
            }*/
            // Target URL for the POST request
            $targetUrl = 'http://xxx.xxx.xxx.xxx/api/endpoint';

            // Data to be sent in the POST request
            $postData = [
                'action' => $action,
                'id_case' => $id_case,
                'ln' => $case->his_ln,
                'on' => $hospital_import->o_n,
                'order_code' => $order_item->code,
                //'sequence' => $charge_sq
            ];

            // Custom headers for the request
            $headers = [
                'Content-Type: application/json', // Adjust the content type accordingly
                'Authorization: ' . Yii::$app->params['HISSecret'] . '' // Include any other headers you need
            ];

            // Initialize cURL session
            $ch = curl_init();

            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $targetUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Execute cURL session and get the response
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                ///echo 'Curl error: ' . curl_error($ch);
                error_log('Curl error: ' . curl_error($ch));
                return false;
            }

            // Close cURL session
            curl_close($ch);

            // Process the response
            //echo $response;
            error_log($response);
            return true;
        }

        return false;
    }

    public function isMobile()
    {
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

        // Check for Android
        if (strpos($userAgent, 'android') !== false) {
            return 'Android';
        }
        // Check for iOS (iPhone, iPod)
        elseif (strpos($userAgent, 'iphone') !== false || strpos($userAgent, 'ipod') !== false) {
            return 'iOS';
        }
        // Check for iPadOS
        elseif (strpos($userAgent, 'ipad') !== false || (strpos($userAgent, 'macintosh') !== false && strpos($userAgent, 'mobile') !== false)) {
            return 'iPadOS';
        } else {
            return false;
        }
    }

    public function sayHello()
    {
        // ดึงเวลาปัจจุบันเป็นชั่วโมง (รูปแบบ 24 ชั่วโมง)
        $currentHour = date('H');

        // ตรวจสอบช่วงเวลาและแสดงคำทักทาย
        if ($currentHour >= 5 && $currentHour < 12) {
            return "สวัสดีตอนเช้า!";
        } elseif ($currentHour >= 12 && $currentHour < 18) {
            return "สวัสดีตอนบ่าย!";
        } elseif ($currentHour >= 18 && $currentHour < 22) {
            return "สวัสดีตอนเย็นค่ะ!";
        } else {
            return "สวัสดีตอนดึก!";
        }
    }

    public function setLog($type, $description, $ref_id, $table_name)
    {

        //die();
        $ip = $this->getClientIP(); //$_SERVER['REMOTE_ADDR'];
        $log = new UserLog();
        $log->log_type = $type;
        $log->description = $description;
        $log->ref_id = $ref_id;
        $log->table_name = $table_name;
        $log->ip = $ip;
        $log->save();
        /*if($log->save()) {

        }else{
            var_dump($log->getFirstErrors());
            die();
        }*/
    }

    public function getClientIP()
    {
        // ตรวจสอบจาก HTTP_X_FORWARDED_FOR ก่อนในกรณีมี Proxy
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            // ถ้าไม่มี proxy ใช้ค่า REMOTE_ADDR
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = 'UNKNOWN';
        }

        return $ip;
    }

    public function getAge($birthDate)
    {
        if (empty($birthDate)) {
            return '';
        }
        // Create DateTime object from the input date
        $birthDateObj = new DateTime(date('Y-m-d', strtotime(Yii::$app->pathology->engDate($birthDate))));

        // Get the current date
        $currentDate = new DateTime();

        // Calculate the difference between the current date and the birth date
        $age = $currentDate->diff($birthDateObj);

        // Return the age in years
        return $age->y;
    }

    public function hisCaseType($type)
    {
        if ($type == 'L409') {
            return 'surgical';
        }
        if ($type == 'L410') {
            return 'pap';
        }
        if ($type == 'L401') {
            return 'non-gyn';
        }
    }

    /**
     * Sanitize file name
     *
     * @param string $filename
     * @return string
     */
    public function sanitizeFileName($filename)
    {
        // แปลงชื่อไฟล์ให้เป็นตัวพิมพ์เล็ก
        //$filename = strtolower($filename);

        // แยกชื่อไฟล์และนามสกุล
        $fileParts = pathinfo($filename);
        $name = $fileParts['filename'];
        $extension = isset($fileParts['extension']) ? $fileParts['extension'] : '';

        // แทนที่ช่องว่างด้วยขีดล่าง (_)
        $name = str_replace(' ', '_', $name);

        // กำจัดอักขระที่ไม่ใช่ตัวอักษร, ตัวเลข, ขีดกลาง และขีดล่าง แล้วแทนที่ด้วย _
        $name = preg_replace('/[^a-z0-9_\-]/', '_', $name);

        // กำจัด _ ที่ซ้ำกัน
        $name = preg_replace('/_+/', '_', $name);

        // ประกอบชื่อไฟล์ใหม่และต่อด้วยนามสกุลเดิม
        return $extension ? $name . '.' . $extension : $name;
    }

    /**
     * Send result by user code
     *
     * @param string $id_case
     * @return void
     */
    public function sendHisReceiveByUserCode($id_case)
    {
        $case = Yii::$app->pathology->getCase($id_case);
        $lab_req = LabReq::find()->where(['REQUESTNO' => $case->his_ln])->one();
        if ($lab_req) {
            $lab_req->RECEIVESPECIMENBYUSERCODE = $case->registerBy->code;
            $lab_req->RECEIVESPECIMENDATETIME = date('Y-m-d H:i:s');
            if ($lab_req->save()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * send his patho number
     *
     * @param string $id_case
     * @return void
     */
    public function sendHisPathoNumber($id_case)
    {
        $case = Yii::$app->pathology->getCase($id_case);
        $lab_req = LabReq::find()->where(['REQUESTNO' => $case->his_ln])->one();
        if ($lab_req) { //&& empty($lab_req->SURGICALNO)
            $lab_req->SURGICALNO = $case->id_case;
            if ($lab_req->save()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * send report to HIS
     *
     * @param string $id_case
     * @param integer $diagnosis_id
     * @return void
     */
    public function sendReportToHIS($id_case, $diagnosis_id)
    {
        $case = Yii::$app->pathology->getCase($id_case);
        $case_type = Yii::$app->pathology->getCaseType($id_case);

        if ($case) {
            $lab_req = LabReq::find()->where(['REQUESTNO' => $case->his_ln, 'HN' => $case->h_n])->one();

            //$report_types = ['consult-outlab', 'outlab', 'revised', 'corrected', 'addendum', 'final', 'preliminary'];

            if ($case_type == 'surgical' && $lab_req) {
                $diagnosis = SurgicalDiagnosis::findOne($diagnosis_id);
                if (empty($lab_req->GROSSDESCRIPTION) || $diagnosis->report_type != 'outlab') {
                    $lab_req->GROSSDESCRIPTION = $this->cleanHTML($diagnosis->gross_description);
                }
                if (empty($lab_req->MICROSCOPICFINDINGS) || $diagnosis->report_type != 'outlab') {
                    $lab_req->MICROSCOPICFINDINGS = $this->cleanHTML($diagnosis->microscopic_description);
                }
                //if (empty($lab_req->DIAGNOSISDESCRIPTION)) {

                /*if($check_revised) {
                    //remove final in array
                    $report_types = array_diff($report_types, ['final']);
                    $report_types = array_values($report_types); // รีเซ็ต key ให้เป็น 0-based
                }*/

                $dx = '';
                //foreach($report_type){

                foreach (
                    SurgicalDiagnosis::find()
                        ->where(['id_case' => $case->id_case])
                        ->andWhere(['>', 'status_id', 3])
                        //->andWhere(['report_type' => $report_type])
                        ->orderBy(['id' => SORT_ASC])->all() as $diagnosis
                ) {
                    $check_revised = SurgicalDiagnosis::findOne(['id_case' => $diagnosis->id_case, 'report_type' => 'revised', 'surgical_diagnosis_id' => $diagnosis->id,  'pathologist_at' => $diagnosis->pathologist_at]);

                    if ($check_revised) {

                        //$dx .= $this->cleanHTML('*****' . $diagnosis->report_type . '*****<br><br>' . $diagnosis->diagnosis . "<br>******<br><br>");
                        //$dx .= ucfirst($check_revised->report_type) . ' Report : ' . $check_revised->pathologist_at . '<br>';
                        $dx .= ucfirst($check_revised->report_type) . ' Report : ' .
                            /*($check_revised->report_type == 'outlab' ? 
                            'See full report at Scan >> LAB Patho' . $check_revised->pathologist_at : 
                            $check_revised->pathologist_at) . '<br>';*/
                            $result = ($check_revised->report_type == 'outlab' || $check_revised->report_type == 'consult-outlab')
                            ? 'See full report at Scan >> LAB Patho' . $check_revised->pathologist_at
                            : $check_revised->pathologist_at . '<br>';
                        echo $result . '<br>';
                        if ($check_revised->is_critical_diagnosis == 1) {
                            $dx .= 'Critical Report<br>';
                        }
                        $dx .= $check_revised->diagnosis;
                        $dx .= '<br><br>Electronically signed out by : ' . $check_revised->pathologist->report_name . ' on ' . $check_revised->pathologist_at;
                        if ($check_revised->is_co_pathologist == 1 && !empty($check_revised->co_pathologist_id)) {
                            /*foreach(CoPathologist::find()->where(['id_case' => $check_revised->id_case])->all() as $co_pathologist){
                                    $dx .= '<br>Co-Pathologist: ' . $co_pathologist->pathologistCo->report_name;
                                }*/
                            $dx .= '<br>Co-Pathologist: ' . $check_revised->pathologistCo->report_name;
                        }
                        $dx .= '<br><br>';
                    } else {
                        //$dx .= ucfirst($diagnosis->report_type) . ' Report : ' . $diagnosis->pathologist_at . '<br>';
                        $dx .= ucfirst($diagnosis->report_type) . ' Report : ' .
                            $result = ($diagnosis->report_type == 'outlab' || $diagnosis->report_type == 'consult-outlab')
                            ? 'See full report at Scan >> LAB Patho' . $diagnosis->pathologist_at
                            : $diagnosis->pathologist_at . '<br>';
                        echo $result . '<br>';
                        /*($diagnosis->report_type == 'outlab' ? 
                            'See full report at Scan >> LAB Patho' . $diagnosis->pathologist_at : 
                            $diagnosis->pathologist_at) . '<br>';*/
                        if ($diagnosis->is_critical_diagnosis == 1) {
                            $dx .= 'Critical Report<br>';
                        }
                        $dx .= $diagnosis->diagnosis;
                        $dx .= '<br><br>Electronically signed out by : ' . $diagnosis->pathologist->report_name . ' on ' . $diagnosis->pathologist_at;
                        if ($diagnosis->is_co_pathologist == 1 && !empty($diagnosis->co_pathologist_id)) {
                            /* foreach(CoPathologist::find()->where(['id_case' => $diagnosis->id_case])->all() as $co_pathologist){
                                    $dx .= '<br>Co-Pathologist: ' . $co_pathologist->pathologistCo->report_name;
                                }*/
                            $dx .= '<br>Co-Pathologist: ' . $diagnosis->pathologistCo->report_name;
                        }
                        $dx .= '<br><br>';
                    }
                }
                //}
                $lab_req->DIAGNOSISDESCRIPTION = $this->cleanHTML($dx); //$this->cleanHTML('*****' . $diagnosis->report_type . '*****<br><br>' . $diagnosis->diagnosis . "<br>******<br>");
                //}
                if (empty($lab_req->SURGICALNO)) {
                    $lab_req->SURGICALNO = $case->id_case;
                }
                $lab_req->RESULTREADY = 1;
                $lab_req->RESULTREADYDATETIME = $diagnosis->pathologist_at;

                // Save send report to SSB log
                $send_report_his = new SendReportHis();
                $send_report_his->id_case = $case->id_case;
                $send_report_his->report_type = $diagnosis->report_type;
                $send_report_his->send_at = date('Y-m-d H:i:s');
                $send_report_his->send_by = Yii::$app->user->getId();
                $send_report_his->diagnosis_id = $diagnosis->id;

                if ($lab_req->save()) {
                    if (!empty($case->his_ln)) {
                        LabResult::updateAll(
                            [
                                'APPROVEDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                'TECHNICIANUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                                'RESULTDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                'RESULTBYUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                            ],
                            ['REQUESTNO' => $case->his_ln]
                        );
                    }
                    error_log('HIS Success: ' . $case->id_case . '_' . $diagnosis->report_type);

                    $send_report_his->response = 'Success';
                    return true;
                } else {
                    error_log('HIS Error: ' . $case->id_case . '_' . $diagnosis->report_type);

                    $send_report_his->response = 'Failed';
                    return false;
                }

                $send_report_his->save();
            } // Surgical

            if ($case_type == 'non-gyn' && $lab_req) {

                $diagnosis = CytoNonGynDiagnosis::findOne($diagnosis_id);
                if (empty($lab_req->GROSSDESCRIPTION) || $diagnosis->report_type != 'outlab') {
                    $lab_req->GROSSDESCRIPTION = $this->cleanHTML($diagnosis->gross_description);
                }
                if (empty($lab_req->MICROSCOPICFINDINGS) || $diagnosis->report_type != 'outlab') {
                    $lab_req->MICROSCOPICFINDINGS = $this->cleanHTML($diagnosis->microscopic_description);
                }
                $dx = '';

                /*if($check_revised) {
                    //remove final in array
                    $report_types = array_diff($report_types, ['final']);
                    $report_types = array_values($report_types); // รีเซ็ต key ให้เป็น 0-based
                }*/

                //foreach($report_types as $report_type){
                foreach (
                    CytoNonGynDiagnosis::find()
                        ->where(['id_case' => $case->id_case])
                        ->andWhere(['>', 'status_id', 3])
                        //->andWhere(['report_type' => $report_type])
                        ->orderBy(['id' => SORT_ASC])->all() as $diagnosis
                ) {
                    $check_revised = CytoNonGynDiagnosis::findOne(['id_case' => $diagnosis->id_case, 'report_type' => 'revised', 'cyto_non_gyn_diagnosis_id' => $diagnosis->id, 'pathologist_at' => $diagnosis->pathologist_at]);

                    if ($check_revised) {
                        //$dx .= $this->cleanHTML('*****' . $diagnosis->report_type . '*****<br><br>' . $diagnosis->diagnosis . "<br>******<br><br>");
                        //$dx .= ucfirst($check_revised->report_type) . ' Report : ' . $check_revised->pathologist_at . '<br>';
                        $dx .= ucfirst($check_revised->report_type) . ' Report : ' .
                            $result = ($check_revised->report_type == 'outlab' || $check_revised->report_type == 'consult-outlab')
                            ? 'See full report at Scan >> LAB Patho' . $check_revised->pathologist_at
                            : $check_revised->pathologist_at . '<br>';
                        echo $result . '<br>';
                        if ($check_revised->is_critical_diagnosis == 1) {
                            $dx .= 'Critical Report<br>';
                        }
                        $dx .= $check_revised->diagnosis;
                        $dx .= '<br><br>Electronically signed out by : ' . $check_revised->pathologist->report_name . ' on ' . $check_revised->pathologist_at;
                        if ($check_revised->is_co_pathologist == 1 && !empty($check_revised->co_pathologist_id)) {
                            $dx .= '<br>Co-Pathologist: ' . $check_revised->pathologistCo->report_name;
                        }
                        $dx .= '<br><br>';
                    } else {
                        //$dx .= $this->cleanHTML('*****' . $diagnosis->report_type . '*****<br><br>' . $diagnosis->diagnosis . "<br>******<br><br>");
                        //$dx .= ucfirst($diagnosis->report_type) . ' Report : ' . $diagnosis->pathologist_at . '<br>';
                        $dx .= ucfirst($diagnosis->report_type) . ' Report : ' .
                            $result = ($diagnosis->report_type == 'outlab' || $diagnosis->report_type == 'consult-outlab')
                            ? 'See full report at Scan >> LAB Patho' . $diagnosis->pathologist_at
                            : $diagnosis->pathologist_at . '<br>';
                        echo $result . '<br>';
                        if ($diagnosis->is_critical_diagnosis == 1) {
                            $dx .= 'Critical Report<br>';
                        }
                        $dx .= $diagnosis->diagnosis;
                        $dx .= '<br><br>Electronically signed out by : ' . $diagnosis->pathologist->report_name . ' on ' . $diagnosis->pathologist_at;
                        if (isset($diagnosis->is_co_pathologist) && $diagnosis->is_co_pathologist == 1 && !empty($diagnosis->co_pathologist_id)) {
                            $dx .= '<br>Co-Pathologist: ' . $diagnosis->pathologistCo->report_name;
                        }
                    }
                }

                //}
                $lab_req->DIAGNOSISDESCRIPTION = $this->cleanHTML($dx); //$this->cleanHTML('*****' . $diagnosis->report_type . '*****<br><br>' . $diagnosis->diagnosis . "<br>******<br>");
                //}
                if (empty($lab_req->SURGICALNO)) {
                    $lab_req->SURGICALNO = $case->id_case;
                }
                $lab_req->RESULTREADY = 1;
                $lab_req->RESULTREADYDATETIME = $diagnosis->pathologist_at;

                // Save send report to SSB log
                $send_report_his = new SendReportHis();
                $send_report_his->id_case = $case->id_case;
                $send_report_his->report_type = $diagnosis->report_type;
                $send_report_his->send_at = date('Y-m-d H:i:s');
                $send_report_his->send_by = Yii::$app->user->getId();
                $send_report_his->diagnosis_id = $diagnosis->id;


                if ($lab_req->save()) {
                    if (!empty($case->his_ln)) {
                        LabResult::updateAll(
                            [
                                'APPROVEDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                'TECHNICIANUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                                'RESULTDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                'RESULTBYUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                            ],
                            ['REQUESTNO' => $case->his_ln]
                        );
                    }
                    error_log('HIS Success: ' . $case->id_case . '_' . $diagnosis->report_type);
                    $send_report_his->response = 'Success';

                    return true;
                } else {
                    error_log('HIS Error: ' . $case->id_case . '_' . $diagnosis->report_type);
                    $send_report_his->response = 'Failed';

                    return false;
                }

                $send_report_his->save();
            } // Non-Gyn

            if (($case_type == 'pap' || $case_type == 'hpv') && $lab_req) {
                $diagnosis = CytoPapDiagnosis::findOne($diagnosis_id);
                $pap_his_charge = SysConfig::findOne(['CTRLCODE' => 20067, 'CODE' => $lab_req->labResult->LABCODE]);


                if ($pap_his_charge && $pap_his_charge->CODE == 'G27') { // HPV
                    $case = CaseHpv::findOne(['his_ln' => $lab_req->REQUESTNO]);
                    $diagnosis = CytoHpvDiagnosis::findOne($diagnosis_id);

                    $dx = 'Source of Specimen:';
                    $dx .= isset($diagnosis->hpvSpecimen) ? $diagnosis->hpvSpecimen->name : '';
                    $dx .= '<br><br>';
                    $dx .= 'Test Method:';
                    $test_method = CytoPapTestMethod::findOne($diagnosis->hpv_test_method_id);
                    $dx .= isset($test_method) ? $test_method->name : '';
                    if (!empty($diagnosis->hpv_test_method)) {
                        $dx .= '<br />' . $diagnosis->hpv_test_method;
                    }
                    $dx .= '<br><br>';
                    $dx .= 'Result of HPV test:';
                    $dx .= isset($diagnosis->hpvTest) ? $diagnosis->hpvTest->name_report : '';
                    $dx .= '<br>';
                    if (!empty($diagnosis->hpv_test)) {
                        $dx .= ((isset($diagnosis->hpvTest) ? '<br />' : '') . $diagnosis->hpv_test);
                    }

                    if (!empty($diagnosis->hpv_type) || !empty($diagnosis->hpv_type_id)) {
                        $dx .= '<br><br>Result of HPV type:';
                        if (!empty($diagnosis->hpv_type_id)) {
                            $dx .= isset($diagnosis->hpvType) ? $diagnosis->hpvType->name_report : '';
                        }
                        if (!empty($diagnosis->hpv_type)) {
                            $dx .= $diagnosis->hpv_type;
                        }
                    }

                    $dx .= '<br><br>Note:';
                    $dx .= isset($diagnosis->hpvNote) ? $diagnosis->hpvNote->name : '';
                    if (!empty($diagnosis->hpv_note)) {
                        $dx .= '<br />' . $diagnosis->hpv_note;
                    }

                    $lab_req->DIAGNOSISDESCRIPTION = $this->cleanHTML($dx);


                    // Save send report to SSB log
                    $send_report_his = new SendReportHis();
                    $send_report_his->id_case = $case->id_case;
                    $send_report_his->report_type = $diagnosis->report_type;
                    $send_report_his->send_at = date('Y-m-d H:i:s');
                    $send_report_his->send_by = Yii::$app->user->getId();
                    $send_report_his->diagnosis_id = $diagnosis->id;

                    if ($lab_req->save()) {
                        if (!empty($case->his_ln)) {
                            LabResult::updateAll(
                                [
                                    'APPROVEDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                    'TECHNICIANUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                                    'RESULTDATETIME' => !empty($diagnosis->pathologist_at) ? $this->engDateTime($diagnosis->pathologist_at) : '',
                                    'RESULTBYUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : ''),
                                ],
                                ['REQUESTNO' => $case->his_ln]
                            );
                        }
                        error_log('HIS Success: ' . $case->id_case . '_' . $diagnosis->report_type);
                        $send_report_his->response = 'Success';
                        return true;
                    } else {
                        error_log('HIS Error: ' . $case->id_case . '_' . $diagnosis->report_type);
                        $send_report_his->response = 'Failed';
                        return false;
                    }
                    $send_report_his->save();


                    // End HPV
                } else if ($pap_his_charge && $pap_his_charge->CODE == 'G26') { // HPV && GYN
                    $case_hpv = CaseHpv::findOne(['his_ln' => $lab_req->REQUESTNO]);
                    $case_pap = CasePap::findOne(['his_ln' => $lab_req->REQUESTNO]);

                    $diagnosis_hpv = CytoHpvDiagnosis::findOne($diagnosis_id);
                    $diagnosis_pap = CytoPapDiagnosis::findOne($diagnosis_id);

                    $dx = '';
                    if ($diagnosis_hpv) {
                        $dx .= 'Source of Specimen:';
                        $dx .= isset($diagnosis_hpv->hpvSpecimen) ? $diagnosis_hpv->hpvSpecimen->name : '';
                        $dx .= '<br><br>';
                        $dx .= 'Test Method:';
                        $test_method = CytoPapTestMethod::findOne($diagnosis_hpv->hpv_test_method_id);
                        $dx .= isset($test_method) ? $test_method->name : '';
                        if (!empty($diagnosis_hpv->hpv_test_method)) {
                            $dx .= '<br />' . $diagnosis_hpv->hpv_test_method;
                        }
                        $dx .= '<br><br>';
                        $dx .= 'Result of HPV test:';
                        $dx .= isset($diagnosis_hpv->hpvTest) ? $diagnosis_hpv->hpvTest->name_report : '';
                        $dx .= '<br>';
                        if (!empty($diagnosis_hpv->hpv_test)) {
                            $dx .= ((isset($diagnosis_hpv->hpvTest) ? '<br />' : '') . $diagnosis_hpv->hpv_test);
                        }

                        if (!empty($diagnosis_hpv->hpv_type) || !empty($diagnosis_hpv->hpv_type_id)) {
                            $dx .= '<br><br>Result of HPV type:';
                            if (!empty($diagnosis_hpv->hpv_type_id)) {
                                $dx .= isset($diagnosis_hpv->hpvType) ? $diagnosis_hpv->hpvType->name_report : '';
                            }
                            if (!empty($diagnosis_hpv->hpv_type)) {
                                $dx .= $diagnosis_hpv->hpv_type;
                            }
                        }

                        $dx .= '<br><br>Note:';
                        $dx .= isset($diagnosis_hpv->hpvNote) ? $diagnosis_hpv->hpvNote->name : '';
                        if (!empty($diagnosis_hpv->hpv_note)) {
                            $dx .= '<br />' . $diagnosis_hpv->hpv_note;
                        }
                    } // Diagnosis HPV

                    if ($diagnosis_pap) {
                        $dx .= '<br><br>Cytology Test (The Bethesda System 2014)<br>';
                        $dx .= 'SPECIMEN TYPE:' . (isset($case->specimenType) ? $case->specimenType->name : '-') . '<br>';
                        $dx .= '<br>SPECIMEN ADEQUACY:<br>' . (isset($diagnosis_pap->specimenAdequacy1) ? ($diagnosis_pap->specimenAdequacy1->name == '-' ? null : $diagnosis_pap->specimenAdequacy1->name) : null) . '<br>';
                        if (!empty($diagnosis_pap->specimenAdequacy2)) {
                            $dx .= (isset($diagnosis_pap->specimenAdequacy2) ? ($diagnosis_pap->specimenAdequacy2->name == '-' ? null : $diagnosis_pap->specimenAdequacy2->name) : null) . '<br>';
                        }
                        if (!empty($diagnosis_pap->specimen_adequacy_4)) {
                            //$case_pap->specimen_adequacy_3 = unserialize($case_pap->specimen_adequacy_3);

                            $p = 1;
                            $inter = CytoSpecimenAdequacy2::find()->filterWhere(['in', 'id', $diagnosis_pap->specimen_adequacy_4])->count();
                            foreach (CytoSpecimenAdequacy2::find()->filterWhere(['in', 'id', $diagnosis_pap->specimen_adequacy_4])->all() as $item) {
                                $dx .= $item->name . ($p < $inter ? '<br />' : '');
                            }
                        }

                        $dx .= $diagnosis_pap->adequacy_other;

                        $dx .= '<br><br>GENERAL CATEGORIZATION:<br>';
                        if (!empty($diagnosis_pap->generalCategorization1)) {
                            $dx .= (isset($diagnosis_pap->generalCategorization1) ? $diagnosis_pap->generalCategorization1->name : null) . '<br>';
                        }
                        if (!empty($diagnosis_pap->categorization_other)) {
                            $dx .= 'Other malignant neoplasms : ' . $diagnosis_pap->categorization_other;
                            $dx . '<br />';
                        }
                        if (!empty($diagnosis_pap->general_categorization_2) && !empty($diagnosis_pap->general_categorization_2)) {

                            $p = 1;
                            $inter = CytoGeneralCategorization2::find()->filterWhere(['in', 'id', $diagnosis_pap->general_categorization_2])->count();
                            $neo = false;
                            foreach (CytoGeneralCategorization2::find()->filterWhere(['in', 'id', $diagnosis_pap->general_categorization_2])->all() as $item) {
                                $dx .= '&nbsp; -' . $item->report . ($p < $inter ? '<br />' : '');
                            }
                        }

                        if (!empty($diagnosis_pap->specimen_adequacy_3)) {

                            $p = 1;
                            $inter = CytoSpecimenAdequacy3::find()->filterWhere(['in', 'id', $diagnosis_pap->specimen_adequacy_3])->count();
                            $or = 0;
                            $nonNeo = false;
                            $reactive = false;
                            $output = ''; // Variable to store the output

                            foreach (CytoSpecimenAdequacy3::find()->filterWhere(['in', 'id', $diagnosis_pap->specimen_adequacy_3])->all() as $item) {
                                $or++;

                                if (
                                    $item->id <= 5 && $item->id = 17
                                ) {
                                    if ($or === 1) {
                                        $output .= '<br>' . '&nbsp; Organism' . ': ' . $item->name;
                                    } else {
                                        $output .= ', ' . $item->name;
                                    }
                                }

                                if (
                                    $item->id >= 6 && $item->id <= 10
                                ) {
                                    if (!$nonNeo) {
                                        $output .= '<br>' . '&nbsp; -Non-neoplastic Findings' . ': ' . $item->name;
                                        $nonNeo = true;
                                    } else {
                                        $output .= ', ' . $item->name;
                                    }
                                } elseif ($item->id >= 11 && $item->id <= 16) {
                                    if (!$reactive) {
                                        $output .= '<br>' . '&nbsp; -Reactive cellular change associated with' . ': ' . $item->name;
                                        $reactive = true;
                                    } else {
                                        $output .= ', ' . $item->name;
                                    }
                                }
                            }

                            // Output the final result
                            $dx .= rtrim($output, ','); // Remove the trailing comma

                        }

                        if (!$diagnosis_pap->is_no_comment && !empty($diagnosis_pap->suggestion)) {
                            $dx .= isset($diagnosis_pap->cytoSuggestion) ? $diagnosis_pap->cytoSuggestion->name . '<br>' : null;
                            $dx .= $diagnosis_pap->suggestion . '<br>';
                        }
                    } // Diagnosis GYN

                    $lab_req->DIAGNOSISDESCRIPTION = $this->cleanHTML($dx);

                    //if (empty($lab_req->SURGICALNO)) {
                    $lab_req->SURGICALNO = $case_pap->id_case;
                    //}
                    //$lab_req->DIAGNOSISDESCRIPTION = $dx;

                    $lab_req->RESULTREADY = 1;
                    $lab_req->RESULTREADYDATETIME = !empty($diagnosis_pap->pathologist_id) ? $diagnosis_pap->pathologist_at : $diagnosis_pap->cytotech1_at;


                    // Save send report to SSB log
                    $send_report_his = new SendReportHis();
                    $send_report_his->id_case = $case_pap->id_case;
                    $send_report_his->report_type = $diagnosis_pap->report_type;
                    $send_report_his->send_at = date('Y-m-d H:i:s');
                    $send_report_his->send_by = Yii::$app->user->getId();
                    $send_report_his->diagnosis_id = $diagnosis_pap->id;

                    if ($lab_req->save()) {
                        if (!empty($case->his_ln)) {
                            LabResult::updateAll(
                                [
                                    'APPROVEDATETIME' => !empty($diagnosis_pap->pathologist_id) ? $this->engDateTime($diagnosis_pap->pathologist_at) : $this->engDateTime($diagnosis_pap->cytotech1_at),
                                    'TECHNICIANUSERCODE' => (isset($diagnosis_pap->pathologist) ? $diagnosis_pap->pathologist->code : $diagnosis_pap->cytotech1->code),
                                    'RESULTDATETIME' => !empty($diagnosis_pap->pathologist_id) ? $this->engDateTime($diagnosis_pap->pathologist_at) : $this->engDateTime($diagnosis_pap->cytotech1_at),
                                    'RESULTBYUSERCODE' => (isset($diagnosis_pap->pathologist) ? $diagnosis_pap->pathologist->code : $diagnosis_pap->cytotech1->code),
                                ],
                                ['REQUESTNO' => $case_pap->his_ln]
                            );
                        }
                        error_log('HIS Success: ' . $case_pap->id_case . '_' . $diagnosis_pap->report_type);
                        $send_report_his->response = 'Success';
                        return true;
                    } else {
                        error_log('HIS Error: ' . $case_pap->id_case . '_' . $diagnosis_pap->report_type);
                        $send_report_his->response = 'Failed';
                        return false;
                    }

                    $send_report_his->save();

                    // End HPV && GYN
                } else { //GYN
                    $case = CasePap::findOne(['his_ln' => $lab_req->REQUESTNO]);
                    $diagnosis = CytoPapDiagnosis::findOne($diagnosis_id);

                    $dx = 'Cytology Test (The Bethesda System 2014)<br>';
                    $dx .= 'SPECIMEN TYPE:' . (isset($case->specimenType) ? $case->specimenType->name : '-') . '<br>';
                    $dx .= '<br>SPECIMEN ADEQUACY:<br>' . (isset($diagnosis->specimenAdequacy1) ? ($diagnosis->specimenAdequacy1->name == '-' ? null : $diagnosis->specimenAdequacy1->name) : null) . '<br>';
                    if (!empty($diagnosis->specimenAdequacy2)) {
                        $dx .= (isset($diagnosis->specimenAdequacy2) ? ($diagnosis->specimenAdequacy2->name == '-' ? null : $diagnosis->specimenAdequacy2->name) : null) . '<br>';
                    }
                    if (!empty($diagnosis->specimen_adequacy_4)) {
                        //$case_pap->specimen_adequacy_3 = unserialize($case_pap->specimen_adequacy_3);

                        $p = 1;
                        $inter = CytoSpecimenAdequacy2::find()->filterWhere(['in', 'id', $diagnosis->specimen_adequacy_4])->count();
                        foreach (CytoSpecimenAdequacy2::find()->filterWhere(['in', 'id', $diagnosis->specimen_adequacy_4])->all() as $item) {
                            $dx .= $item->name . ($p < $inter ? '<br />' : '');
                        }
                    }

                    $dx .= $diagnosis->adequacy_other;

                    $dx .= '<br><br>GENERAL CATEGORIZATION:<br>';
                    if (!empty($diagnosis->generalCategorization1)) {
                        $dx .= (isset($diagnosis->generalCategorization1) ? $diagnosis->generalCategorization1->name : null) . '<br>';
                    }
                    if (!empty($diagnosis->categorization_other)) {
                        $dx .= 'Other malignant neoplasms : ' . $diagnosis->categorization_other;
                        $dx . '<br />';
                    }
                    if (!empty($diagnosis->general_categorization_2) && !empty($diagnosis->general_categorization_2)) {

                        $p = 1;
                        $inter = CytoGeneralCategorization2::find()->filterWhere(['in', 'id', $diagnosis->general_categorization_2])->count();
                        $neo = false;
                        foreach (CytoGeneralCategorization2::find()->filterWhere(['in', 'id', $diagnosis->general_categorization_2])->all() as $item) {
                            $dx .= '&nbsp; -' . $item->report . ($p < $inter ? '<br />' : '');
                        }
                    }

                    if (!empty($diagnosis->specimen_adequacy_3)) {

                        $p = 1;
                        $inter = CytoSpecimenAdequacy3::find()->filterWhere(['in', 'id', $diagnosis->specimen_adequacy_3])->count();
                        $or = 0;
                        $nonNeo = false;
                        $reactive = false;
                        $output = ''; // Variable to store the output

                        foreach (CytoSpecimenAdequacy3::find()->filterWhere(['in', 'id', $diagnosis->specimen_adequacy_3])->all() as $item) {
                            $or++;

                            if (
                                $item->id <= 5 && $item->id = 17
                            ) {
                                if ($or === 1) {
                                    $output .= '<br>' . '&nbsp; Organism' . ': ' . $item->name;
                                } else {
                                    $output .= ', ' . $item->name;
                                }
                            }

                            if (
                                $item->id >= 6 && $item->id <= 10
                            ) {
                                if (!$nonNeo) {
                                    $output .= '<br>' . '&nbsp; -Non-neoplastic Findings' . ': ' . $item->name;
                                    $nonNeo = true;
                                } else {
                                    $output .= ', ' . $item->name;
                                }
                            } elseif ($item->id >= 11 && $item->id <= 16) {
                                if (!$reactive) {
                                    $output .= '<br>' . '&nbsp; -Reactive cellular change associated with' . ': ' . $item->name;
                                    $reactive = true;
                                } else {
                                    $output .= ', ' . $item->name;
                                }
                            }
                        }

                        // Output the final result
                        $dx .= rtrim($output, ','); // Remove the trailing comma

                    }

                    if (!$diagnosis->is_no_comment && !empty($diagnosis->suggestion)) {
                        $dx .= isset($diagnosis->cytoSuggestion) ? $diagnosis->cytoSuggestion->name . '<br>' : null;
                        $dx .= $diagnosis->suggestion . '<br>';
                    }

                    $lab_req->DIAGNOSISDESCRIPTION = $this->cleanHTML($dx);
                    //End GYN

                    if (empty($lab_req->SURGICALNO)) {
                        $lab_req->SURGICALNO = $case->id_case;
                    }
                    //$lab_req->DIAGNOSISDESCRIPTION = $dx;

                    $lab_req->RESULTREADY = 1;
                    $lab_req->RESULTREADYDATETIME = !empty($diagnosis->pathologist_id) ? $diagnosis->pathologist_at : $diagnosis->cytotech1_at;


                    // Save send report to SSB log
                    $send_report_his = new SendReportHis();
                    $send_report_his->id_case = $case->id_case;
                    $send_report_his->report_type = $diagnosis->report_type;
                    $send_report_his->send_at = date('Y-m-d H:i:s');
                    $send_report_his->send_by = Yii::$app->user->getId();
                    $send_report_his->diagnosis_id = $diagnosis->id;


                    if ($lab_req->save()) {
                        if (!empty($case->his_ln)) {
                            LabResult::updateAll(
                                [
                                    'APPROVEDATETIME' => !empty($diagnosis->pathologist_id) ? $this->engDateTime($diagnosis->pathologist_at) : $this->engDateTime($diagnosis->cytotech1_at),
                                    'TECHNICIANUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : $diagnosis->cytotech1->code),
                                    'RESULTDATETIME' => !empty($diagnosis->pathologist_id) ? $this->engDateTime($diagnosis->pathologist_at) : $this->engDateTime($diagnosis->cytotech1_at),
                                    'RESULTBYUSERCODE' => (isset($diagnosis->pathologist) ? $diagnosis->pathologist->code : $diagnosis->cytotech1->code),
                                ],
                                ['REQUESTNO' => $case->his_ln]
                            );
                        }
                        error_log('HIS Success: ' . $case->id_case . '_' . $diagnosis->report_type);
                        $send_report_his->response = 'Success';
                        return true;
                    } else {
                        error_log('HIS Error: ' . $case->id_case . '_' . $diagnosis->report_type);
                        $send_report_his->response = 'Failed';
                        return false;
                    }

                    $send_report_his->save();
                } // GYN


            } // Pap


            return false;
        }

        return false;
    }


    /**
     * clean HTML content
     *
     * @param string $htmlContent
     * @return string
     */
    public function cleanHTML($htmlContent)
    {
        $htmlContent = str_replace(['<br/>', '<br />'], '<br>', $htmlContent);
        $htmlContent = str_replace(['&nbsp;'], ' ', $htmlContent);
        // Replace HTML tags and decode entities
        $plainText = strip_tags($htmlContent, '<br>');
        $plainText = html_entity_decode($plainText);

        // Replace <br> with Windows newline (\r\n)
        $plainText = str_replace(['<br>', '<br />', '<br/>'], "\r\n", $plainText);

        // Trim and remove extra spaces
        $plainText = preg_replace('/[ \t]+/', ' ', $plainText);
        $plainText = trim($plainText);

        return $plainText;
    }


    /* public function createRequestOrderHttpClient(
        array $testCodeParam,
        array $testNameParam,
        array $requestSeqParam,
        array $existingTestCodes,
        array $meta,
        string $endpointUrl
    ): array {
        // ป้องกันความยาวไม่เท่ากัน
        if (count($testCodeParam) !== count($testNameParam) || count($testCodeParam) !== count($requestSeqParam)) {
            Yii::error('Input arrays length mismatch for testCode/testName/testSeq', __METHOD__);
            return ['ok' => false, 'status' => null, 'body' => null, 'error' => 'Input arrays length mismatch'];
        }

        // กรองเฉพาะ test codes ใหม่
        $labDetail = [];
        for ($i = 0; $i < count($testCodeParam); $i++) {
            if (!in_array($testCodeParam[$i], $existingTestCodes, true)) {
                $labDetail[] = [
                    'testid'  => (string)$testCodeParam[$i],
                    'testname' => (string)$testNameParam[$i],
                    'testseq' => (string)$requestSeqParam[$i],
                ];
            }
        }

        if (empty($labDetail)) {
            Yii::info('No new test codes to send', __METHOD__);
            return ['ok' => true, 'status' => 204, 'body' => null, 'error' => null]; // 204 = no content
        }

        $payload = [
            'patcustid'   => (string)($meta['patcustid']   ?? ''),
            'patname'     => (string)($meta['patname']     ?? ''),
            'pattitle'    => (string)($meta['pattitle']    ?? ''),
            'patage'      => ($meta['dob'] ?? '') ? $this->calculateAgeNew((string)$meta['dob']) : '',
            'patsex'      => (string)($meta['sex']         ?? ''),
            'labno'       => (string)($meta['labno']       ?? ''),
            'hn'          => (string)($meta['hn']          ?? ''),
            'dob'         => (string)($meta['dob']         ?? ''),     // YYYY-mm-dd
            'reqdate'     => (string)($meta['reqdate']     ?? ''),     // YYYY-mm-dd HH:ii:ss
            'patward'     => (string)($meta['patward']     ?? ''),
            'doctor'      => (string)($meta['doctor']      ?? ''),
            'right'       => (string)($meta['right']       ?? ''),
            'requestname' => (string)($meta['requestname'] ?? ''),
            'lab_detail'  => $labDetail,
        ];

        $client = new Client([
            'transport' => 'yii\httpclient\CurlTransport',
            'requestConfig' => [
                'format' => Client::FORMAT_JSON,
                'headers' => [
                    'Content-Type' => 'application/json; charset=UTF-8',
                ],
            ],
            'responseConfig' => [
                'format' => Client::FORMAT_JSON,
            ],
        ]);

        Yii::info('Sending only new test codes: ' . json_encode($payload, JSON_UNESCAPED_UNICODE), __METHOD__);

        try {
            $response = $client->createRequest()
                ->setMethod('POST')
                ->setUrl($endpointUrl)
                ->setContent(json_encode($payload, JSON_UNESCAPED_UNICODE))
                ->send();

            if ($response->isOk) {
                Yii::info('Response OK: ' . $response->content, __METHOD__);
                return ['ok' => true, 'status' => $response->statusCode, 'body' => $response->content, 'error' => null];
            }

            // ไม่ OK
            Yii::error(sprintf('HTTP error %d: %s', $response->statusCode, $response->content), __METHOD__);
            return ['ok' => false, 'status' => $response->statusCode, 'body' => $response->content, 'error' => 'HTTP error'];
        } catch (\yii\httpclient\Exception $e) {
            Yii::error($e->getMessage(), __METHOD__);
            return ['ok' => false, 'status' => null, 'body' => null, 'error' => $e->getMessage()];
        } catch (\Throwable $e) {
            Yii::error($e, __METHOD__);
            return ['ok' => false, 'status' => null, 'body' => null, 'error' => $e->getMessage()];
        }
    }*/


    public static function createRequestOrderCurl($hisRequest)
    {

        $i = 1;
        foreach (HisRequestTestList::find()->where(['HisRequestID' => $hisRequest->ID])->all() as $TestList) {
            $labDetail[] = [
                'testid'   => (string)$TestList->TestCode,
                'testname' => (string)$TestList->TestName,
                'testseq' => $i++,
            ];
        }

        // 2) เตรียม payload
        $birthday = $hisRequest->DateOfBirth;
        $birthday_converted = self::toYmdExplode($hisRequest->DateOfBirth);
        $payload = [
            'patcustid'   => (string)$hisRequest->CustomerCode,
            'patcustid'   => (string)$hisRequest->CustomerCode,
            'patname'     => trim($hisRequest->FirstName . ' ' . $hisRequest->LastName),
            'pattitle'    => (string)$hisRequest->PrefixName,
            'patage'      => $birthday !== '' ? (string)self::calculateAgeNew($birthday) : '',
            'patsex'      => (string)$hisRequest->Sex,
            'labno'       => (string)$hisRequest->LabNo,
            'hn'          => (string)$hisRequest->HN,
            'dob'         => $birthday_converted,
            //'reqdate'     => (string)$hisRequest->RequestDate, // ควรเป็น 'YYYY-mm-dd HH:ii:ss'
            'reqdate'     => (string)self::convertDate($hisRequest->RequestDate), // ควรเป็น 'YYYY-mm-dd HH:ii:ss'
            'patward'     => (string)$hisRequest->WardName,
            'doctor'      => (string)$hisRequest->DoctorName,
            'right'       => (string)$hisRequest->RightsName,
            'requestname' => (string)$hisRequest->RequestBy,
            'lab_detail'  => $labDetail,
        ];

        //var_dump($birthday);

        /*var_dump($payload);
        die();*/

        error_log('[HisRequest] payload = ' . Json::encode($payload));

        //error_log('[HisRequest] payload(print_r) = ' . print_r($payload, true));
        //Yii::info('Sending only new test codes: ' . Json::encode($payload, JSON_UNESCAPED_UNICODE), __METHOD__);

        // 4) Fallback: ใช้ native cURL
        try {
            $ch = curl_init('https://report.prolab.co.th/api/create_prolab_lab_API_order.php');
            $json = Json::encode($payload, JSON_UNESCAPED_UNICODE);

            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=UTF-8'],
                CURLOPT_POSTFIELDS     => $json,
                CURLOPT_RETURNTRANSFER => true,
                // หากเป็น cert self-signed และคุณยอมรับความเสี่ยง ให้ปลดคอมเมนต์สองบรรทัดล่างนี้
                // CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_TIMEOUT        => 30,
            ]);

            $body   = curl_exec($ch);
            $errno  = curl_errno($ch);
            $error  = curl_error($ch);
            //$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($errno) {
                //Yii::error("cURL error: ($errno) $error", __METHOD__);
                //return ['Error' => false, 'status' => null, 'body' => null, 'error' => $error];
                error_log('Error: ' . $errno . ' - ' . $error);
            }
            //error_log('Error: ' . $payload);
            error_log('Curl Error: ' . $errno);
            error_log('Curl Error: ' . $error);
            // พยายาม decode เป็น JSON ถ้าทำได้
            //$decoded = null;
            if (is_string($body) && $body !== '') {
                $decoded = Json::decode($body, true);
                return $decoded;
                //error_log('Error: ' . $body);
            }
        } catch (\Throwable $e) {
            error_log('Error: ' . $e->getMessage());
        }
    }

    static function convertDateTime(?string $input): ?string
    {
        if ($input === null) return null;

        $input = trim($input);
        if ($input === '') return null;

        // แปลงแบบเข้มงวดตามฟอร์แมตที่กำหนด
        $dt = DateTime::createFromFormat('d/m/Y H:i:s', $input);

        // ตรวจสอบ error/warning จากการ parse
        $errors = DateTime::getLastErrors();
        if (!$dt || $errors['warning_count'] > 0 || $errors['error_count'] > 0) {
            return null;
        }

        return $dt->format('Y-m-d H:i:s');
    }

    function convertDate(?string $input): ?string
    {
        if ($input === null || trim($input) === '') {
            return null;
        }

        $dt = DateTime::createFromFormat('d/m/Y H:i:s', trim($input));
        $errors = DateTime::getLastErrors();
        if (!$dt || $errors['warning_count'] > 0 || $errors['error_count'] > 0) {
            return null;
        }

        return $dt->format('Y-m-d');
    }

    static function toYmdExplode(string $s): string
    {
        $s = trim($s);
        if ($s === '' || $s === '00/00/0000') return '';

        $parts = explode('/', $s); // ['13','07','1965']
        if (count($parts) !== 3) return '';

        [$dd, $mm, $yyyy] = $parts;

        // เติม 0 ให้ครบ 2 หลัก และเช็คปี 4 หลัก
        if (strlen($yyyy) !== 4) return '';
        $dd = str_pad($dd, 2, '0', STR_PAD_LEFT);
        $mm = str_pad($mm, 2, '0', STR_PAD_LEFT);

        return $yyyy . $mm . $dd; // 19650713
    }

    /**
     * แปลงวันเกิดจากหลายรูปแบบให้เป็น Y-m-d (CE) ด้วย explode()/สลับตำแหน่ง
     * - รองรับ: d/m/Y, d-m-Y, Y-m-d, Y/m/d
     * - รองรับ พ.ศ. (>=2400) → ลบ 543 เป็น ค.ศ.
     * - ถ้าอินพุตว่าง/ไม่ตรงรูปแบบ/วันที่ไม่จริง → คืน ''
     */
    private static function normalizeDobToIso(string $s): string
    {
        $s = trim($s);
        if ($s === '' || $s === '0000-00-00' || $s === '00/00/0000') {
            return '';
        }

        // ตัดเวลาทิ้งถ้ามี
        $s = explode(' ', $s)[0];

        // ให้ตัวคั่นเป็น '/' ตัวเดียวเพื่อแยกง่าย
        $s = str_replace('-', '/', $s);
        $p = explode('/', $s);
        if (count($p) !== 3) {
            return '';
        }

        // แยก 2 โหมด: d/m/Y หรือ Y/m/d
        if (strlen($p[0]) === 4) {
            // Y/m/d
            $yyyy = (int)$p[0];
            $mm   = (int)$p[1];
            $dd   = (int)$p[2];
        } else {
            // d/m/Y
            $dd   = (int)$p[0];
            $mm   = (int)$p[1];
            $yyyy = (int)$p[2];
        }

        // รองรับปี พ.ศ. → แปลงเป็น ค.ศ.
        if ($yyyy >= 2400) {
            $yyyy -= 543;
        }

        // ตรวจความถูกต้องของวันที่
        if (!checkdate($mm, $dd, $yyyy)) {
            return '';
        }

        return sprintf('%04d-%02d-%02d', $yyyy, $mm, $dd); // Y-m-d
    }

    /**
     * คำนวณอายุจากวันเกิด (รับหลายรูปแบบ เช่น 13/07/1965) → จำนวนปีเป็น string
     * ถ้าอินพุตไม่ถูกต้อง → คืน ''
     */
    private static function calculateAgeNew(string $dob): string
    {
        try {
            $iso = self::normalizeDobToIso($dob); // แปลงให้เป็น Y-m-d ก่อน
            if ($iso === '') {
                \Yii::warning('Invalid DOB for age calc: ' . $dob, __METHOD__);
                return '';
            }

            $birth = new \DateTime($iso);
            $now   = new \DateTime('today'); // ใช้ timezone ตาม PHP ของคุณ
            $diff  = $birth->diff($now);
            return (string)$diff->y;
        } catch (\Throwable $e) {
            \Yii::warning('DOB parse error: ' . $dob . ' => ' . $e->getMessage(), __METHOD__);
            return '';
        }
    }
}
