<?php

namespace App\Http\Controllers\Capture;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


use App\Models\Department;
use App\Models\Mongo;
use App\Models\Datetime;

class DashboardScreeningController extends Controller
{
    // public function __construct(Request $r){
    //     $this->department = "all";
    //     if (isset($r->department)) {
    //         $this->department = $r->department;
    //     }
    // }
    // public $department = "";

    public function index(Request $r)
    {


        $view['month_all']              = baseMONTH();
        $view['filter_procedure']       = Department::procedure(uid());
        $view['filter_room']            = Department::room(uid());
        $view['filter_scope']           = Department::scope(uid());
        $view['filter_prediagnostic']   = Mongo::table('prediagnostic')->get();
        $view['filter_medication']      = Mongo::table('dd_anesthesis')
            ->select('anesthesis_name')
            ->orderby('anesthesis_name')
            ->distinct()
            ->get();
        $view['hospital']               = get_hospital();
        $view = $this->search($view, $r);

        // รับค่าวันที่จากผู้ใช้ (GET parameter) หากไม่มี ให้ใช้วันที่ปัจจุบัน
        $date = $r->input('date', date('Y-m-d'));
        $view['casedayone_finish']  = $this->casedayfinish($date);
        $view['casedayone_all']     = $this->casedayall($date);
        $view['casedayone_cancer']  = $this->casedaycancer($date);
        $view['casedaytwo_finish']  = $this->casedayfinish($date);
        $view['casedaytwo_all']     = $this->casedayall($date);
        $view['casedaytwo_cancer']  = $this->casedaycancer($date);
        $view['ca_case']      = $this->case_ca($r);




        $view['today_notrecovery'] = Mongo::table('tb_case')
        ->where("appointment_date", date('Y-m-d'))
        ->where('statusjob', '!=', 'recovery')

        ->count();

        $view['average_timeuse'] = Mongo::table('tb_case')
        ->where("appointment_date", date('Y-m-d'))
        ->where('statusjob', 'recovery')
        ->avg('timeuse');
        $count_room = count($view['filter_room']);
        // dd($view['average_timeuse'] , $view['today_notrecovery']);
        $predictime = ($view['average_timeuse'] * $view['today_notrecovery']) / $count_room;
        if ($predictime < $view['average_timeuse']) {
            $view['today_predictime'] = intval($view['average_timeuse']);
        } else {
            $view['today_predictime'] = intval($predictime);
        }

        $view['today_timefinish'] = date('H:i:s', strtotime('+' . intval($view['today_predictime']) . ' minutes'));


        $this->timeuse();
        $count_room = count($view['filter_room']);

        $view['tb_room'] = Mongo::table("tb_room")
        ->where("room_type" , "capture")
        ->get();
        foreach ($view['tb_room'] as $room) {
            $view['tb_case'] = Mongo::table("tb_case")
            ->where("case_room" , strval($room['room_id']))
            ->get();
            $view['room_capture'][] = $room['room_name'];
            $view['room_capture_count'][] = count($view['tb_case']);
        }
        $view['department_hospital'] = Mongo::table('tb_department')
            ->where('department_name', 'like', 'โรงพยาบาล%')
            ->get();

        $hos_search = false;
        if($r->hospital != 'All' && $r->hospital != ''){
            $hos_search = true;
        }
        $view['hos_search'] = $hos_search;

        $view['provinces'] = Department::province();
        $view['all_case'] = $this->total_all_cases($r);
        $view['hospital_case'] = $this->hospital_case($r);



        return view('dashboardscreening.00_main', $view);
    }

    public function show($id, Request $r)
    {
        $view['mainurl'] = "dashboardstation";
        $view['month_all']              = baseMONTH();
        $view['filter_procedure']       = Department::procedure(uid());
        $view['filter_room']            = Department::room(uid());
        $view['filter_scope']           = Department::scope(uid());
        $view['filter_prediagnostic']   = Mongo::table('prediagnostic')->get();
        $view['filter_medication']      = Mongo::table('dd_anesthesis')
            ->select('anesthesis_name')
            ->orderby('anesthesis_name')
            ->distinct()
            ->get();
        $view['hospital']               = get_hospital();
        $view = $this->search($view, $id);

        $w[] = array('updatetime', '!=', "");
        if (isset($r->start_date)) {
            if ($r->start_date != 'All') {
                $w[] = array('case_dateregister', "like", $r->start_date . "%");
            }
        }
        if (isset($r->hoscode)) {
            if ($r->hoscode != 'All') {
                $w[] = array('hospitalcode', $r->hoscode);
            }
        }



        if ($id == 'diagnosis') {
            $view['diagnostic']         = $this->diagnostic($r, 300);
            return view('dashboardscreening.15_fulldiagnosis', $view);
        }
        if ($id == 'intervention') {
            $view['procedure_sub']      = $this->procedure_sub($r, 300);
            return view('dashboardscreening.16_fullintervention', $view);
        }
        if ($id == 'physician') {

            $view['physician'] = $this->physician($r , 100);
            return view('dashboardscreening.12_fullphysician', $view);
        }

        if ($id == 'polyp') {
            $view['polyp'] = $this->polyp($r , 100);
            return view('dashboardscreening.17_fullpolyp', $view);
        }
    }


    public function search($view, $r)
    {
        $alldate_show = [];

        if (isset($r->start_date) && isset($r->end_date) && $r->start_date != '' && $r->end_date != '') {
            $period = new \DatePeriod(
                new \DateTime($r->start_date),
                new \DateInterval('P1D'),
                (new \DateTime($r->end_date))->modify('+1 day')
            );
            foreach ($period as $date) {
                $alldate_show[] = $date->format('Y-m-d');
            }
        }

        $tb_case_filer = array();
        $total_all_cases = 0;
        $total_all_patients = 0;

        foreach ($alldate_show as $date) {
            $total_case = $this->casedayfinish($date);
            $total_all = $this->casedayall($date);
            $total_cancer = $this->casedaycancer($date);

            // เก็บค่าในแต่ละวัน
            $tb_case_filer[$date]['total_case'] = $total_case;
            $tb_case_filer[$date]['total_all'] = $total_all;
            $tb_case_filer[$date]['total_cancer'] = $total_cancer;

            // สะสมค่ารวม
            $total_all_cases += $total_case;
            $total_all_patients += $total_all;
        }


        // เพิ่มค่ารวมเข้าไปใน view data
        $view['tb_case_filer'] = $tb_case_filer;
        $view['total_all_cases'] = $total_all_cases;
        $view['total_all_patients'] = $total_all_patients;

        // 20_hospital

        $whos01[0]  = array('hospitalcode', "10736");

        $discharged[0] = array("statusjob", "recovery");


        // $w[] = array('updatetime', '!=', "");

        // if(isset($r->province)){
        //     $w[] = array('case_province_code', $r->province);

        // }



        // if (isset($r->start_date) && isset($r->end_date)) {
        //     $w[] = array('appointment_date', '>=', $r->start_date);
        //     $w[] = array('appointment_date', '<=', $r->end_date . "date('Y-m-d')");

        // }

        // if (isset($r->province)) {
        //     $w[] = array('case_province', $r->province);
        // }

        if (isset($r->hospital)) {
            $w[] = array('department', $r->hospital);
        }



        $w[] = array('updatetime', '!=', "");




        if(isset($r->province)){
            $w[] = array('case_province_code', $r->province);


        }
        // dd($r->province);
        if (isset($r->start_date) && isset($r->end_date)) {
            $w[] = array('appointment_date', '>=', $r->start_date);
            $w[] = array('appointment_date', '<=', $r->end_date);
        } elseif (isset($r->start_date)) {
            $w[] = array('appointment_date', '>=', $r->start_date);
            $w[] = array('appointment_date', '<=', date('Y-m-d'));
        }



        // dd($r->all());


        $view['hospital_case'] = $this->hospital_case($r);
        $view = $this->get_casestation($view ,$w);
        $view['hospital01_count']   = Mongo::table('tb_case')->where($whos01)->count();
        $view['all_case'] = $this->total_all_cases($r);
        $view['search_start_date'] = @$r->start_date;
        $view['search_end_date'] = @$r->end_date;
        $view['search_province'] = @$r->province;
        $view['search_hospital'] = @$r->hospital;

        $view['bowel']              = $this->bowel($r);
        // dd($view);
        $view['diagnostic']         = $this->diagnostic($r);
        // dd($view);
        $view['polyp']              = $this->polyp($r);
        $view['procedure_sub']      = $this->procedure_sub($r);
        $view['physician']          = $this->physician($r);
        $view['ca_case'] = $this->case_ca($r);
        // dd($view['physician']);
        // $view['hos02_cancel'] = $this->possiblecolorectalcancer($w,$whos02);
        // $view['hos03_cancel'] = $this->possiblecolorectalcancer($w,$whos03);

        return $view;
    }


    public function case_ca($r)
    {
        $query = $this->query($r);

        // Count cases with cancer diagnoses
        $count = $query->whereIn('diagnostic', ["CA colon", "CA Cecum", "CA Rectum"])
                      ->count();

        return $count;
    }



    // 01_allcase.blade.php
    public function total_all_cases($r){
 
        $query = $this->query($r);

        $arr['total_all_cases'] = (clone $query)
            ->where('statusjob', 'recovery')
            ->count();

        $arr['total_all_patients'] = $query->count();

        return $arr;
    }


    // 20_hospital.balde.php
    public function hospital_case($r){
        // dd($r->all());
        $tb_case = Mongo::table('tb_case');
        $query = $tb_case;
        $view = [];

        if(isset($r->province) && $r->province != '') {
            $query = $query->where('case_province_code', $r->province)
                          ->orWhere('procedure_code', $r->province);
        }

        $query = $query->get();

        $department_filter = [];
        // เอาชื่อโรงพยาบาลแต่ละเข้าไปใน array
        foreach ($query as $key => $value) {
            if(isset($value['department'])) {
                $department_filter[] = $value['department'];
            }
        }
        $department_filter = array_unique($department_filter);



        foreach ($department_filter as $key => $hospital) {
           $tb_case = Mongo::table('tb_case')
           ->where('department', $hospital)
           ->count();
           $view[$hospital] = $tb_case;
        }

        return $view;
    }



    public function timeuse()
    {
        $tb_case = Mongo::table('tb_case')
            ->where('statusjob', 'recovery')
            ->where('time_start', '!=', null)
            ->where('time_end', '!=', null)
            ->where('timeuse', null)
            ->get();

        foreach ($tb_case as $case) {
            Datetime::timeuse($case['_id']);
        }
    }

    public function casedayfinish($date)
    {


        $count = 0;
        $count = Mongo::table("tb_case")
            ->where("appointment_date", $date)
            ->where("statusjob", "recovery")
            ->count();
        return $count;
    }

    public function casedayall($date)
    {
        $count = 0;
        $count = Mongo::table("tb_case")
            ->where("appointment_date", $date)
            ->count();
        return $count;
    }


    public function casedaycancer($date)
    {


        $count = 0;
        $count = Mongo::table('tb_case')
            ->where("appointment_date", $date)
            ->whereIn('diagnostic', ["CA colon", "CA Cecum", "CA Rectum"])
            ->count();
        return $count;
    }

    // 06_patientall.blade.php
    public function get_casestation($view ,$w)
    {


        $total = 0;
        $discharged = 0;
        foreach (isset($view['filter_room']) ? $view['filter_room'] : [] as $index => $room) {
            $room = (object) $room;
            $roomid = $room->room_id;
            $str = str_pad($index, 2, "0", STR_PAD_LEFT);

            $w1[0] = array('room', intval($roomid));
            $ow1[0] = array('room', strval($roomid));


        //   dd($w);

            $cases_count     = Mongo::table('tb_case')
            ->where($w1)
            ->orWhere($ow1)
            ->where($w)
            ->count();
            $cases_finished  = Mongo::table('tb_case')
                ->where(function ($query) use ($roomid) {
                    $query->where('room', intval($roomid))
                        ->orWhere('room', strval($roomid));
                })
                ->whereIn('statusjob', ['discharged', 'recovery'])
                ->count();
            $cases_unfinished = $cases_count - $cases_finished;

            $view['station']["hos$str" . "_gender"]['name'] = $room->room_name;
            $view['station']["hos$str" . "_gender"]['all'] = $cases_count;
            $view['station']["hos$str" . "_gender"]['finished'] = $cases_finished;
            $view['station']["hos$str" . "_gender"]['unfinished'] = $cases_unfinished;
            $total += $cases_count;
            $discharged += $cases_finished;
        }

        $view['case_count'] = Mongo::table('tb_case')->count();
        $view['case_countdischarged'] = Mongo::table('tb_case')->where("statusjob", "recovery")->count();
        return $view;
    }



    public function physician($r, $limit = 5)
    {
        $query = $this->query($r);
        // Get all unique doctors who have cases
        $doctors = $query->distinct()->get(['doctorname']);

        $view = [];
        // dd($doctors);
        foreach ($doctors as $doctor) {
            if ($doctor && $doctor != "นพ.พระนารายณ์ ลพบุรี") {

                $count = (clone $query)
                    ->where('doctorname', $doctor)
                    ->where('statusjob', 'recovery')
                    ->count();

                if ($count > 0) {
                    $ex = explode(' ', $doctor);
                    $view[$ex[0]] = $count;

                }
            }
        }
                // dd($ex);

        // Sort by count in descending order and take top 5
        arsort($view);

        // จะให้โชว์กี่คน ใน dashboard
        $view = array_slice($view, 0, $limit);

        return $view;
    }





    public function bowel($r)
    {

        $query = $this->query($r);
        // Clone query for each count to avoid query builder modifications affecting subsequent queries
        $excellent = (clone $query)->where('bowel', 'Excellent')->count();
        $good = (clone $query)->where('bowel', 'Good')->count();
        $fair = (clone $query)->where('bowel', 'Fair')->count();
        $poor = (clone $query)->where('bowel', 'Poor')->count();

        $view = [
            'Excellent' => $excellent,
            'Good' => $good,
            'Fair' => $fair,
            'Poor' => $poor
        ];

        // dd($view);
        return $view;
    }

    public function diagnostic($r, $limit_data = 5)
    {
        $query = $this->query($r);
        $colono = Mongo::table('tb_procedure')->where('code', 'gi002')->first();
        $view = [];

        foreach ($colono['icd10'] as $step01) {
            foreach ($step01 as $key => $value) {
                $view[$value['name']] = (clone $query)
                    ->where('diagnostic', 'like', '%' . $value['name'] . '%')
                    ->count();
            }
        }

        arsort($view);
        $view = array_slice($view, 0, $limit_data);
        return $view;
    }


   // 11_intervention.blade.php
   public function procedure_sub($r, $limit_data = 5)
   {

        $query = Mongo::table('tb_case');

        if (isset($r->hospital) && $r->hospital != 'All') {
            $query->where('department', $r->hospital);
        }
        if (isset($r->province) && $r->province != '') {
            $query->where('case_province_code', $r->province);
        }
        if (isset($r->start_date) && isset($r->end_date) && $r->start_date != '' && $r->end_date != '') {
            $query->where('appointment_date', '>=', $r->start_date);
            $query->where('appointment_date', '<=', $r->end_date);
        } elseif (isset($r->start_date) && $r->start_date != '') {
            $query->where('appointment_date', '>=', $r->start_date);
            $query->where('appointment_date', '<=', date('Y-m-d'));
        }

        $colono = Mongo::table('tb_procedure')->where('code', 'gi002')->first();
        $view = [];
        // dd($colono);
        foreach ($colono['icd9'] as $step01) {
            foreach ($step01 as $key => $value) {

                $view[$value['name']] = (clone $query)
                    ->where('procedure_sub', 'like', '%' . $value['name'] . '%')
                    ->count();
            }
        }

        arsort($view);
        $view = array_slice($view, 0, $limit_data);
        return $view;
   }



   public function query($r){
    $query = Mongo::table('tb_case');

    if (isset($r->hospital) && $r->hospital != 'All') {
        $query->where('department', $r->hospital);
    }
    if (isset($r->province) && $r->province != '') {
        $query->where('case_province_code', $r->province);
    }
    if (isset($r->start_date) && isset($r->end_date) && $r->start_date != '' && $r->end_date != '') {
        $query->where('appointment_date', '>=', $r->start_date);
        $query->where('appointment_date', '<=', $r->end_date);
    } elseif (isset($r->start_date) && $r->start_date != '') {
        $query->where('appointment_date', '>=', $r->start_date);
        $query->where('appointment_date', '<=', date('Y-m-d'));
    }


    return $query;
   }



    public function polyp($r , $limit_data = 5)
    {
        $query = $this->query($r);

        $hospital = Mongo::table('tb_department')
        ->where("department_name", "like", "%โรงพยาบาล%");

        if (isset($r->province) && $r->province != '') {
            $hospital->where('department_province_code', $r->province);
        }
        if (isset($r->hospital) && $r->hospital != 'All') {
            $hospital->where('department_name', $r->hospital);
        }
        if (isset($r->start_date) && isset($r->end_date) && $r->start_date != '' && $r->end_date != '') {
            $hospital->where('appointment_date', '>=', $r->start_date);
            $hospital->where('appointment_date', '<=', $r->end_date);
        } elseif (isset($r->start_date) && $r->start_date != '') {
            $hospital->where('appointment_date', '>=', $r->start_date);
            $hospital->where('appointment_date', '<=', date('Y-m-d'));
        }


        $hospital = $hospital->get();


        $poly_hos = [];

        foreach ($hospital as $hos) {
            $hospital_code = $hos['department_name'];

            // Count polyp cases
            $polyp_count = (clone $query)
                ->where('department', $hospital_code)
                ->whereIn('diagnostic', ["Rectal polyp", "Anal polyp", "Colonic polyp"])
                ->count();

            // Count polypectomy cases
            $polypectomy_count = (clone $query)
                ->where('department', $hospital_code)
                ->whereIn('procedure_sub', ["Polypectomy"])
                ->count();

            $poly_hos[$hospital_code] = [
                'polyp' => $polyp_count,
                'polypectomy' => $polypectomy_count
            ];
        }

        arsort($poly_hos);
        $poly_hos = array_slice($poly_hos, 0, $limit_data);


        return $poly_hos;

    }



    public function store(Request $r)
    {
        // dd($r->all());
        $w[0]       = array('report_cid', '>', 0);
        $procedure  = array();
        if (isset($r->filter_procedure)) {
            array_push($procedure, $r->filter_procedure);
        } else {
            $proce      = Department::procedure(uid());
            foreach ($proce as $p) {
                $p = (object) $p;
                array_push($procedure, $p->name);
            }
        }
        $arr        = array();
        $month_all  = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
        $year_all   = yearALL();
        if (checkNULL($r->year)) {
            $w[0]  = array('report_appointment_year', $r->year);
        }
        if (checkNULL($r->month)) {
            $w[1]  = array('report_appointment_month', $r->month);
        }
        if (checkNULL($r->procedure)) {
            $w[2]  = array('report_procedure', $r->procedure);
        }
        if (checkNULL($r->age)) {
            $w[3]  = array('report_age', $r->age);
        }
        if (checkNULL($r->room)) {
            $w[4]  = array('report_room', $r->room);
        }
        if (checkNULL($r->icd10)) {
            $w[5]  = array('report_diagnostic', 'like', '%' . $r->icd10 . '%');
        }
        if (checkNULL($r->icd9)) {
            $w[6]  = array('report_procedure_icd9', 'like', '%' . $r->icd9 . '%');
        }
        if (checkNULL($r->scope)) {
            $w[7]  = array('report_scope', 'like', '%' . $r->scope . '%');
        }
        if (checkNULL($r->prediagnostic)) {
            $str   = explode('...', $r->prediagnostic);
            $w[8]  = array('report_prediagnosis', 'like', '%' . $str[0] . '%');
        }
        if (checkNULL($r->medication)) {
            $w[9]  = array('report_medication', 'like', '%' . $r->medication . '%');
        }
        if (checkNULL($r->finding)) {
            $w[10] = array('report_finding', 'like', '%' . $r->finding . '%');
        }

        $year                   = $this->year($w, $r, $procedure);
        $month                  = $this->month($w, $r, $procedure);
        $arr['data_procedure']  = $this->procedure($w, $r, $procedure);
        $arr['age']             = $this->age_normal($w, $r, $procedure);
        $arr['gender']          = $this->gender($w, $r, $procedure);
        $arr['room']            = $this->room($w, $r, $procedure);
        $icd10                  = $this->icd10($w, $r, $procedure);
        $icd9                   = $this->icd9($w, $r, $procedure);
        $scope                  = $this->scope($w, $r, $procedure);
        $prediagnostic_other    = $this->prediagnostic_other($w, $r, $procedure);
        $arr['allcase']         = $this->allcase($w, $r, $procedure);
        $arr['allpatient']      = $this->allpatient($w, $r, $procedure);
        $arr['alldoctor']       = count(Department::user('doctor'));
        $arr['allnurse']        = count(Department::user('nurse'));
        $arr['allroom']         = count(Department::room(uid()));
        $medication             = $this->medication($w, $r, $procedure);
        $arr['finding']         = $this->finding($w, $r, $procedure);

        $i = 0;
        foreach ($year_all as $m) {
            $arr['year'][$i]['country']  = $m;
            $arr['year'][$i]['visits']   = 0;
            foreach ($year as $key => $val) {
                if ($key == $m) {
                    $arr['year'][$i]['visits'] = $val;
                }
            }
            $i++;
        }


        $i = 0;
        foreach ($month_all as $m) {
            $arr['month'][$i]['country']  = $m;
            $arr['month'][$i]['visits']   = 0;
            foreach ($month as $key => $val) {
                if ($key == $m) {

                    if ($val == 0) {
                        $arr['month'][$i]['visits'] = 0;
                    } else {
                        $arr['month'][$i]['visits'] = $val;
                    }
                }
            }
            $i++;
        }

        $i = 0;
        foreach ($icd10 as $key => $val) {
            if ($i < 5) {
                $arr['icd10_show5'][$i]['category']  = $key;
                $arr['icd10_show5'][$i]['value']   = $val;
            }
            $arr['icd10_showall'][$i]['country'] = $key;
            $arr['icd10_showall'][$i]['visits'] = $val;
            $i++;
        }

        $i = 0;
        foreach ($icd9 as $key => $val) {
            if ($i < 5) {
                $arr['icd9_show5'][$i]['category']  = $key;
                $arr['icd9_show5'][$i]['value']   = $val;
            }
            $arr['icd9_showall'][$i]['country']  = $key;
            $arr['icd9_showall'][$i]['visits']   = $val;
            $i++;
        }

        $i = 0;
        $color = array("#84e0db", "#56bbb5", "#3e9e9d", "#1f827d", "#065852", "#354749");
        foreach ($medication as $key => $val) {
            if ($i < 5) {
                $arr['medication_show5'][$i]['country']     = $key;
                $arr['medication_show5'][$i]['value']      = $val;
                $arr['medication_show5'][$i]['color']      = $color[$i];
            }
            $arr['medication_showall'][$i]['country']  = $key;
            $arr['medication_showall'][$i]['value']   = $val;
            $i++;
        }

        $i = 0;
        foreach ($scope as $key => $val) {
            if ($i < 5) {
                $arr['scope_show5'][$i]['country']  = $key;
                $arr['scope_show5'][$i]['visits']   = $val;
            }
            $arr['scope_showall'][$i]['country']  = $key;
            $arr['scope_showall'][$i]['visits']   = $val;
            $i++;
        }


        $json = jsonEncode($arr);
        echo $json;
    }



}
