<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\Surveillance;
use App\Models\SurveillanceCase;
use App\Models\CaseLabResult;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DataRetrievalService
{

    public function getSurveillanceData()
    {
        try{
            $toDate = now();
            $this->getSARICases(now()->subDays(config('app.lookback_days.SARI'))->toDateString(), $toDate);  // done
            $this->getILICases(now()->subDays(config('app.lookback_days.ILI'))->toDateString(), $toDate);  // done
            $this->getLBMCases(now()->subDays(config('app.lookback_days.LBM'))->toDateString(), $toDate); // done
            $this->getAFICases(now()->subDays(config('app.lookback_days.AFI'))->toDateString(), $toDate); // done
            //$this->getNSDCases(now()->subDays(config('app.lookback_days.NDS'))->toDateString(), $toDate);
            $this->getSEQCases(now()->subDays(config('app.lookback_days.SEQ'))->toDateString(), $toDate); // done
            Log::channel('jobs')->info($toDate->toDateString(). ' Service Reload Data Successfully Ran');
            return true;
        }
        catch (\Exception $e){
            Log::channel('jobs')->error($e->getMessage());
            return false;
        }

    }


    public function getSARICases($dateFrom, $dateTo=NULL)
    {
        $cond = "";
        $cond .= " and patient.patdate >= '".date('Y-m-d', strtotime($dateFrom))."' ";
        $cond .= (!empty($dateTo)) ? " and patient.patdate <='".date('Y-m-d', strtotime($dateTo))."' ":"";
        $sari_cases = DB::connection('mysql_nphl')
            ->select("
                       SELECT
                            patient.labcode,
                            patient.patdate,
                            patient.isnewcase,
                            l.labname_en,
                            l.labaddress_en,
                            1 as surveillance_id,
                            niphc0_nphl.get_epi_period(patient.patdate, 'Y') as year_data,
                            niphc0_nphl.get_epi_period(patient.patdate, 'W') as week_data,
                            patient.patage,
                            patient.patsex,
                            NULL as is_alive,
                            p.proname_en
                        FROM niphc0_nphl.`labopatients` patient
                        inner join niphc0_nphl.sari_patients sr_p on sr_p.patid = patient.patid
                        inner join niphc0_nphl.laboratory l on l.labid = patient.patsource
                        left join niphc0_nphl.province p on p.proid = patient.frompro
                        WHERE patient.patgroup =2
                        and patient.status = 1
                        ".$cond);

        $this->insert_surveillance_cases($sari_cases);


        $sari_case_results = DB::connection('mysql_nphl')->select("
                        SELECT
                            patient.labcode,
                            1 as surveillance_id,
                            if(trs.rtitle='Negatives', 0, 1) as is_positive,
                            if(trs.rtitle !='Negatives', concat('Influenza ',LEFT(UPPER(trs.rtitle),1)),'') pathogen_name,
                            if(trs.rtitle !='Negatives', trs.rtitle, '') as subtype,
                            'SARI Influenza Test' as indicator
                        FROM `labopatients` patient
                        inner join sari_patients sr_p on sr_p.patid = patient.patid
                        inner join test_patsample tps on tps.patientid = patient.patid
                        inner join test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
                        inner join test_pattestresult tptr on tptr.pstid = tpst.pstid
                        inner join test_resultselect trs on trs.rid = tptr.rsltid
                        WHERE patient.patgroup =2
                        and patient.status = 1
                        and tps.status = 1
                        and tpst.status = 1
                        and trs.status = 1
                        and tpst.labtestid in (775,216,239,238,212,220,340,381,382)
                        " .$cond. "
                        union

                        SELECT
                           patient.labcode,
                            1 as surveillance_id,
                            if(trs.rtitle='Negative', 0, 1) as is_positive,
                            if(trs.rtitle !='Negative', 'SARS-CoV-2', '') as pathogen_name,
                            '' as subtype,
                            'SARI Covid Test' as indicator
                        FROM `labopatients` patient
                        inner join sari_patients sr_p
                        on sr_p.patid = patient.patid
                        inner join test_patsample tps
                        on tps.patientid = patient.patid
                        inner join test_patsamtest tpst
                        on tpst.patsmid = tps.sampleid
                        and tpst.patid = tps.patientid
                        inner join test_pattestresult tptr on tptr.pstid = tpst.pstid
                        inner join test_resultselect trs on trs.rid = tptr.rsltid
                        WHERE patient.patgroup =2
                        and patient.status = 1
                        and tps.status = 1
                        and tpst.status = 1
                        and trs.status = 1
                        and tpst.labtestid in (651,652,653,654,650)
                        and trs.rtitle !='Pending'
                        " .$cond);

        $this->insert_surveillance_case_lab_results($sari_case_results);

    }

    public function getILICases($dateFrom, $dateTo = NULL)
    {
        $cond = "";
        $cond .= " and patient.patdate >= '".date('Y-m-d', strtotime($dateFrom))."' ";
        $cond .= (!empty($dateTo)) ? " and patient.patdate <='".date('Y-m-d', strtotime($dateTo))."' ":"";
        $ili_cases = DB::connection('mysql_nphl')
            ->select("
                SELECT
                    patient.labcode,
                    patient.patdate,
                    patient.isnewcase,
                    l.labname_en,
                    l.labaddress_en,
                    2 as surveillance_id,
                    niphc0_nphl.get_epi_period(patient.patdate, 'Y') as year_data,
                    niphc0_nphl.get_epi_period(patient.patdate, 'W') as week_data,
                    patient.patage,
                    patient.patsex,
                    NULL as is_alive,
                    p.proname_en
                FROM niphc0_nphl.`labopatients` patient
                inner join niphc0_nphl.ili_patients sr_p on sr_p.patid = patient.patid
                inner join niphc0_nphl.laboratory l on l.labid = patient.patsource
                left join niphc0_nphl.province p on p.proid = patient.frompro
                WHERE patient.patgroup =3
                and patient.status = 1
                ".$cond
            );


        $this->insert_surveillance_cases($ili_cases);

        $ili_case_results = DB::connection('mysql_nphl')
            ->select("
            SELECT
            distinct
            patient.labcode,
            2 as surveillance_id,
            if(trs.rtitle='Negatives', 0, 1) as is_positive,
            if(trs.rtitle !='Negatives', concat('Influenza ',LEFT(UPPER(trs.rtitle),1)),'') pathogen_name,
            if(trs.rtitle !='Negatives', trs.rtitle, '') as subtype,
            'ILI Influenza Test' as indicator
            FROM niphc0_nphl.`labopatients` patient
            inner join niphc0_nphl.ili_patients sr_p on sr_p.patid = patient.patid
            inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
            inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
            inner join niphc0_nphl.test_pattestresult tptr on tptr.pstid = tpst.pstid
            inner join niphc0_nphl.test_resultselect trs on trs.rid = tptr.rsltid
            WHERE patient.patgroup = 3
            and patient.status = 1
            and tps.status = 1
            and tpst.status = 1
            and trs.status = 1
            and tpst.labtestid in (775,216,239,238,212,220,340,381,382)
            ".$cond."

            union

            SELECT
            DISTINCT
            patient.labcode,
            2 as surveillance_id,
            if(trs.rtitle='Negative', 0, 1) as is_positive,
            if(trs.rtitle !='Negative', 'SARS-CoV-2', '') as pathogen_name,
            '' as subtype,
            'ILI Covid Test' as indicator
            FROM niphc0_nphl.`labopatients` patient
            inner join niphc0_nphl.ili_patients sr_p on sr_p.patid = patient.patid
            inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
            inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
            inner join niphc0_nphl.test_pattestresult tptr on tptr.pstid = tpst.pstid
            inner join niphc0_nphl.test_resultselect trs on trs.rid = tptr.rsltid
            WHERE patient.patgroup = 3
            and patient.status = 1
            and tps.status = 1
            and tpst.status = 1
            and trs.status = 1
            and tpst.labtestid in (651,652,653,654,650)
            and trs.rtitle !='Pending'
            ".$cond);

        $this->insert_surveillance_case_lab_results($ili_case_results);

    }

    public function getLBMCases($dateFrom, $dateTo = NULL)
    {
        $cond = "";
        $cond .= " and patient.patdate >= '".date('Y-m-d', strtotime($dateFrom))."' ";
        $cond .= (!empty($dateTo)) ? " and patient.patdate <='".date('Y-m-d', strtotime($dateTo))."' ":"";
        $lbm_cases = DB::connection('mysql_nphl')
            ->select("
                SELECT
                    patient.labcode,
                    patient.patdate,
                    patient.isnewcase,
                    l.labname_en,
                    l.labaddress_en,
                    3 as surveillance_id,
                    niphc0_nphl.get_epi_period(patient.patdate, 'Y') year_data,
                    niphc0_nphl.get_epi_period(patient.patdate, 'W') week_data,
                    patient.patage,
                    patient.patsex,
                    NULL as is_alive,
                    p.proname_en
                FROM niphc0_nphl.`labopatients` patient
                inner join niphc0_nphl.lbms_patients on lbms_patients.patid = patient.patid
                left join niphc0_nphl.province p on p.proid = patient.frompro
                inner join niphc0_nphl.laboratory l on l.labid = patient.patsource
                WHERE patient.patgroup = 17
                and patient.status = 1
                    ".$cond);

        $this->insert_surveillance_cases($lbm_cases);

        $lbm_case_results = DB::connection('mysql_nphl')
            ->select("
                SELECT
                distinct
                patient.labcode,
                3 as surveillance_id,
                if(trs.rtitle='Negatives', 0, 1) as is_positive,
                if(trs.rtitle !='Negatives', concat('Influenza ',LEFT(UPPER(trs.rtitle),1)),'') pathogen_name,
                if(trs.rtitle !='Negatives', trs.rtitle, '') as subtype,
                'LBM Influenza Test' as indicator
                FROM niphc0_nphl.`labopatients` patient
                inner join niphc0_nphl.lbms_patients sr_p on sr_p.patid = patient.patid
                inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
                inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
                inner join niphc0_nphl.test_pattestresult tptr on tptr.pstid = tpst.pstid
                inner join niphc0_nphl.test_resultselect trs on trs.rid = tptr.rsltid
                WHERE patient.patgroup = 17
                and patient.status = 1
                and tps.status = 1
                and tpst.status = 1
                and trs.status = 1
                and tpst.labtestid in (775,216,239,238,212,220,340,381,382)
                ".$cond."
                union

                SELECT
                DISTINCT
                patient.labcode,
                3 as surveillance_id,
                if(trs.rtitle='Negative', 0, 1) as is_positive,
                if(trs.rtitle !='Negative', 'SARS-CoV-2', '') as pathogen_name,
                '' as subtype,
                'LBM Covid Test' as indicator
                FROM niphc0_nphl.`labopatients` patient
                inner join niphc0_nphl.lbms_patients sr_p on sr_p.patid = patient.patid
                inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
                inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
                inner join niphc0_nphl.test_pattestresult tptr on tptr.pstid = tpst.pstid
                inner join niphc0_nphl.test_resultselect trs on trs.rid = tptr.rsltid
                WHERE patient.patgroup = 17
                and patient.status = 1
                and tps.status = 1
                and tpst.status = 1
                and trs.status = 1
                and tpst.labtestid in (651,652,653,654,650)
                and trs.rtitle !='Pending'
                ".$cond);

        $this->insert_surveillance_case_lab_results($lbm_case_results);

    }

    public function getAFICases($dateFrom, $dateTo = NULL)
    {
        $cond = "";
        $cond .= " and afi_lab_result.results_date >= '".date('Y-m-d', strtotime($dateFrom))."' ";
        $cond .= (!empty($dateTo)) ? " and afi_lab_result.results_date <='".date('Y-m-d', strtotime($dateTo))."' ":"";
        $afi_cases = DB::connection('mysql_afi')
            ->select("
                SELECT
                    afi_lab_result.sample_code as labcode,
                    afi_lab_result.results_date as patdate,
                    1 as isnewcase,
                    afi_case.sentinel_site as labname_en,
                    '' as labaddress_en,
                    4 as surveillance_id,
                    niphc0_nphl.get_epi_period(afi_lab_result.results_date, 'Y') as year_data,
                    niphc0_nphl.get_epi_period(afi_lab_result.results_date, 'W') as week_data,
                    ifnull(DATEDIFF(afi_case.date_of_interview, date_of_birth),180) as patage,
                    if(afi_case.sex='Male','M','F') as patsex,
                    NULL as is_alive,
                    p.proname_en as proname_en
                FROM afi_db.`afi_tbl_afiform` as afi_case
                left join afi_db.afi_tbl_result afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                left join niphc0_nphl.province p on p.proid = afi_case.residence_province
                where
                afi_case.afi_event is NOT null
                and afi_lab_result.results_date is not null " .$cond);

        $this->insert_surveillance_cases($afi_cases);

        $afi_lab_results = DB::connection('mysql_afi')
            ->select(
                "SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.influenza_result='Positive',1,0) as is_positive,
                        if(afi_lab_result.influenza_result='Positive', concat('Influenza ',LEFT(UPPER(JSON_UNQUOTE(JSON_EXTRACT(afi_lab_result.influenza_subtypes, '$[0].id'))),1)),'') pathogen_name,
                        if(afi_lab_result.influenza_result='Positive', REPLACE(UPPER(JSON_UNQUOTE(JSON_EXTRACT(afi_lab_result.influenza_subtypes, '$[0].id'))),'_','/'),'') as subtype,
                        'AFI Influenza Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.influenza_result in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        union

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.sarscov2_result='Positive',1,0) as is_positive,
                        if(afi_lab_result.sarscov2_result='Positive', 'SARS-CoV-2','') pathogen_name,
                        '' as subtype,
                        'AFI Covid Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.sarscov2_result in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        union

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.dengue_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.dengue_pcr='Positive', 'Dengue','') pathogen_name,
                        '' as subtype,
                        'AFI Dengue PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.dengue_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        union

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.chikungunya_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.chikungunya_pcr='Positive', 'Chikungunya','') pathogen_name,
                        '' as subtype,
                        'AFI Chikungunya PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.chikungunya_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        union

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.leptospira_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.leptospira_pcr='Positive', 'Leptospira','') pathogen_name,
                        '' as subtype,
                        'AFI Leptospira PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.leptospira_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        union

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.plasmodium_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.plasmodium_pcr='Positive', 'Plasmodium','') pathogen_name,
                        '' as subtype,
                        'AFI Plasmodium PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.plasmodium_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.rickettsia_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.rickettsia_pcr='Positive', 'Rickettsia','') pathogen_name,
                        '' as subtype,
                        'AFI Rickettsia PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.rickettsia_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.salmonella_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.salmonella_pcr='Positive', 'Salmonella','') pathogen_name,
                        '' as subtype,
                        'AFI Salmonella PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.salmonella_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.westnile_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.westnile_pcr='Positive', 'Westnile Nile','') pathogen_name,
                        '' as subtype,
                        'AFI Westnile PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.westnile_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.zika_pcr='Positive',1,0) as is_positive,
                        if(afi_lab_result.zika_pcr='Positive', 'ZIKA','') pathogen_name,
                        '' as subtype,
                        'AFI ZIKA PCR Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.zika_pcr in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        # SERUM

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.chikungunya_serum='Positive',1,0) as is_positive,
                        if(afi_lab_result.chikungunya_serum='Positive', 'Chikungunya','') pathogen_name,
                        '' as subtype,
                        'AFI Chikungunya Serum Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.chikungunya_serum in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.dengue_serum='Positive',1,0) as is_positive,
                        if(afi_lab_result.dengue_serum='Positive', 'Dengue','') pathogen_name,
                        '' as subtype,
                        'AFI Dengue Serum Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.dengue_serum in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.westnile_serum='Positive',1,0) as is_positive,
                        if(afi_lab_result.westnile_serum='Positive', 'Westnile','') pathogen_name,
                        '' as subtype,
                        'AFI Westnile Serum Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.westnile_serum in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.zika_serum='Positive',1,0) as is_positive,
                        if(afi_lab_result.zika_serum='Positive', 'ZIKA','') pathogen_name,
                        '' as subtype,
                        'AFI ZIKA Serum Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.zika_serum in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond."

                        UNION

                        SELECT
                        afi_lab_result.sample_code as labcode,
                        4 as surveillance_id,
                        if(afi_lab_result.je_virus='Positive',1,0) as is_positive,
                        if(afi_lab_result.je_virus='Positive', 'Japanese Encephalitis','') pathogen_name,
                        '' as subtype,
                        'AFI Japanese Encephalitis Test' as indicator
                        FROM afi_db.`afi_tbl_afiform` as afi_case
                        INNER join afi_db.afi_tbl_result as afi_lab_result on afi_lab_result.unique_afi_id = afi_case.unique_afi_id
                        where afi_lab_result.sample_code is not null
                        and afi_lab_result.je_virus in('Negative', 'Positive')
                        and afi_case.afi_event is NOT null
                        and afi_lab_result.results_date is not null ".$cond
            );

        $this->insert_surveillance_case_lab_results($afi_lab_results);
    }

    public function getNSDCases($dateFrom, $dateTo = NULL)
    {
        return [];
    }

    public function getSEQCases($dateFrom, $dateTo = NULL)
    {
        $cond = "";
        $cond .= " and patient.patdate >= '".date('Y-m-d', strtotime($dateFrom))."' ";
        $cond .= (!empty($dateTo)) ? " and patient.patdate <='".date('Y-m-d', strtotime($dateTo))."' ":"";
        $seq_cases = DB::connection('mysql_nphl')
            ->select("
            SELECT DISTINCT
                patient.labcode,
                patient.patdate,
                patient.isnewcase,
                l.labname_en,
                l.labaddress_en,
                6 as surveillance_id,
                niphc0_nphl.get_epi_period(patient.patdate, 'Y') as year_data,
                niphc0_nphl.get_epi_period(patient.patdate, 'W') as week_data,
                patient.patage,
                patient.patsex,
                NULL as is_alive,
                pro.proname_en
                from niphc0_nphl.sq_batch sqb
                inner join niphc0_nphl.sq_sub_batch sqsb on sqsb.bt_id = sqb.bt_id
                inner join niphc0_nphl.labopatients patient on patient.patid = sqsb.patid
                inner join niphc0_nphl.laboratory l on l.labid = patient.patsource
                inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
                inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
                left join niphc0_nphl.province pro on pro.proid = patient.frompro
                where patient.status = 1
                and tpst.labtestid IN ( 659, 662, 666, 667, 668 )
            " . $cond);

        $this->insert_surveillance_cases($seq_cases);

        $seq_lab_results = DB::connection('mysql_nphl')
            ->select("
                SELECT DISTINCT
                    patient.labcode,
                    6 as surveillance_id,
                    1 is_positive,
                    ifnull(sqsb.seqlineage,'N/A') as pathogen_name,
                    trs.rtitle as subtype,
                    concat('Sequencing Test ', case when patgroup=2 then 'SARI' when patgroup=3 then 'ILI' when  patgroup=19 then 'COVID-19' else '' end) as indicator
                from niphc0_nphl.sq_batch sqb
                inner join niphc0_nphl.sq_sub_batch sqsb on sqsb.bt_id = sqb.bt_id
                inner join niphc0_nphl.labopatients patient on patient.patid = sqsb.patid
                inner join niphc0_nphl.test_patsample tps on tps.patientid = patient.patid
                inner join niphc0_nphl.test_patsamtest tpst on tpst.patsmid = tps.sampleid and tpst.patid = tps.patientid
                inner join niphc0_nphl.test_pattestresult tptr on tptr.pstid = tpst.pstid
                inner join niphc0_nphl.test_resultselect trs on trs.rid = tptr.rsltid
                where patient.status = 1
                and tpst.labtestid IN ( 659, 662, 666, 667, 668 )
                and trs.rtitle not in ('Inconclusive', 'In Progress')
            " . $cond);

        $this->insert_surveillance_case_lab_results($seq_lab_results);

    }

    private function insert_surveillance_cases($cases){

        $case_data = [];
        foreach ($cases as $case) {
            $case_data[] = [
                'lab_code'          => $case->labcode,
                'case_date'          => $case->patdate,
                'is_newcase'        => $case->isnewcase,
                'sentinel_site_name'       => $case->labname_en,
                'site_province_name'    => $case->labaddress_en,
                'surveillance_id'  => $case->surveillance_id,
                'year_data'        => $case->year_data,
                'week_data'        => $case->week_data,
                'patient_age_inday'           => $case->patage,
                'patient_sex'           => $case->patsex,
                'is_alive'         => $case->is_alive,
                'patient_province'       => $case->proname_en
            ];
        }

        $case_chunks = array_chunk($case_data, 100);
        foreach ($case_chunks as $chunk) {
            DB::connection('mysql')->table('tmp_surveillance_cases')->upsert($chunk, [
                'lab_code',
                'surveillance_id'
            ], [
                'case_date',
                'is_newcase',
                'sentinel_site_name',
                'site_province_name',
                'year_data',
                'week_data',
                'patient_age_inday',
                'patient_sex',
                'is_alive',
                'patient_province'
            ]);
        }
    }

    private function insert_surveillance_case_lab_results($lab_results){
        $result_data = [];
        foreach ($lab_results as $lab_result) {
            $result_data[] = [
                'lab_code'          => $lab_result->labcode,
                'surveillance_id'  => $lab_result->surveillance_id,
                'is_positive'        => $lab_result->is_positive,
                'pathogen_name'        => $lab_result->pathogen_name,
                'subtype'           => $lab_result->subtype,
                'indicator'           => $lab_result->indicator
            ];
        }
        $result_chunks = array_chunk($result_data, 100);
        foreach ($result_chunks as $chunk) {
            DB::connection('mysql')->table('tmp_case_lab_results')->upsert($chunk,
                [
                    'lab_code',
                    'surveillance_id',
                    'indicator'
                ],
                [
                    'is_positive',
                    'pathogen_name',
                    'subtype'
                ]);
        }
    }

}
