<?php

namespace App\Services;

use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class DataRetrievalService
{

    protected $apiBaseUrl;
    protected $apiUsername;
    protected $apiPassword;

    public function __construct()
    {
        $this->apiBaseUrl = config('services.nphl_api.url');
        $this->apiUsername = config('services.nphl_api.username');
        $this->apiPassword = config('services.nphl_api.password');
    }

    public function get($endpoint)
    {
        try {

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->apiBaseUrl . $endpoint);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_ENCODING, '');
            curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
            curl_setopt($ch, CURLOPT_TIMEOUT, 0);
            curl_setopt($ch, CURL_HTTP_VERSION_1_1, 0);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_USERPWD, $this->apiUsername . ":" . $this->apiPassword);
            $resp = curl_exec($ch);
            $b="";
            if($e = curl_error($ch)){
                $b= $e;
            }else{
                $b= $resp;
            }
            curl_close($ch);
            return $b;

        } catch (RequestException $e) {
            return [
                'error' => true,
                'message' => $e->getMessage(),
                'status' => optional($e->response)->status()
            ];
        }
    }


    public function getSurveillanceData()
    {
        try{
            $lookbackDays = config('app.lookback_days');
            $surveillances = DB::connection('mysql')->select("select * from surveillances");
            foreach ($surveillances as $surveillance){
                $surveillance_data = $this->get('api/labsurveil.php?surveillance_id='.$surveillance->id.'&start_date='.now()->subDays($lookbackDays[$surveillance->code])->toDateString());
                $data = json_decode(preg_replace('/^\x{FEFF}+/u', '', $surveillance_data));
                @$this->insert_surveillance_cases((array)$data->laboratory_cases);
                @$this->insert_surveillance_case_lab_results((array)$data->laboratory_results);

            }

            Log::channel('jobs')->info(now()->toDateString(). ' Service Reload Data Successfully Ran');
            return true;
        }
        catch (\Exception $e){
            Log::channel('jobs')->error($e->getMessage());
            return false;
        }

    }

    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, 500);
        foreach ($case_chunks as $chunk) {
            DB::connection('mysql')->table('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, 500);
        foreach ($result_chunks as $chunk) {
            DB::connection('mysql')->table('case_lab_results')->upsert($chunk,
                [
                    'lab_code',
                    'surveillance_id',
                    'indicator'
                ],
                [
                    'is_positive',
                    'pathogen_name',
                    'subtype'
                ]);
        }
    }

}
