<?php

namespace App\Http\Controllers\Endocapture;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Department;
use App\Models\Server;
use App\Models\Mongo;
use App\Exports\DataExport;
use Maatwebsite\Excel\Facades\Excel;
use MongoDB\BSON\Regex;

class ExportDataController extends Controller
{
    // public function __construct(Request $r){checklogin();}

    public function store(Request $r)
    {
        if (isset($r->event)) {
            $event  = $r->event;
            return $this->$event($r);
        }
    }

    public function index(Request $r)
    {
        // dd($r);
        if (Server::check_connection()) {
            return redirect(url('servererror'));
        }
        $serverconnect = @fsockopen(webconfig('server_name'), portnumber(), $errno, $errstr, 1);
        $view   = array();
        // dd($view);
        $view   = $this->query_data($r, $view);
        // dd($view);
        return $view;
    }




    public function indexfirst($r, $data = [])
    {
        $data['doctor']     = Department::server_user('doctor', uid());
        $data['nurse']      = Department::server_user('nurse', uid());
        $data['register']   = Department::server_user('register', uid());
        $data['procedure']  = Server::table('tb_procedure')->get();
        $data['scope']      = Server::table('tb_scope')->get();
        $data['allroom']    = Server::table('tb_room')->get();
        $data['department']    = Server::table('tb_department')->get();

        $data['users']      = Server::table('users')->where('user_type', '!=', 'endo')->get();

        $data['data2']      = $r;
        $data['icd9']       = $this->geticd9($r);  // intervention
        $data['icd10']      = $this->geticd10($r); // diagnosis
        $admin = getCONFIG('admin');
        $scope = getCONFIG('scope');
        $data['year_install'] = $admin->year_install;
        $data['is_phutshin'] = $scope->phutchin_scope ?? false;
        $data['users_modal'] = Server::table('users')->get();
        $data['data_limit']  = 250;

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

    public function query_data($r)
    {
        session_start();
        if (isset($_SESSION['inputall']) && $r->page) {
            $page = $r->page;
            $r = (object) $_SESSION['inputall'];
            $r->page = $page;
        } else {
            unset($_SESSION['inputall']);
        }
        try {
            $_SESSION['inputall'] = $r->all();
        } catch (\Throwable $th) {
            $_SESSION['inputall'] = $r;
        }
        $view = $this->indexfirst($r);
        $w[] = array("where", 'case_status', '!=', 90);
        if (checkNull(@$r->start_date)) {
            $start_date = @$r->start_date;
            $end_date = checkNull(@$r->end_date) ? @$r->end_date : date("Y-m-d");
            $w[] = array("whereBetween", 'appointment_date', $start_date, $end_date);
        }
        $w = $this->checksearch($r, $w, "procedure",    array("whereIn",    'case_procedurecode', @$r->procedure));
        $w = $this->checksearch($r, $w, "user",         array('whereIn',    'case_physicians01', @$r->user));
        $w = $this->checksearch($r, $w, "scope",        array('whereIn',    'scope', @$r->scope));
        $w = $this->checksearch($r, $w, "icd10",        array("whereIn",    'diagnostic', @$r->icd10));
        $w = $this->checksearch($r, $w, "icd9",         array("whereIn",    'proicd9', @$r->icd9));
        $w = $this->checksearch($r, $w, "indication",   array("whereIn",    'indication', @$r->indication));
        $w = $this->checksearch($r, $w, "department" ,  array("where" ,     'department' ,"=" , @$r->department));
        $w = $this->checksearch($r, $w, "user_type",    array("where",      'branch', "=", @$r->user_type));
        $w = $this->checksearch($r, $w, "room",         array("where",      'room', "=", intval(@$r->room)));
        $w2 = "";


        // dd($r,$w);

        if (checkNULL(@$r->keyword)) {

            $w2 = $r->keyword;
            $view['tb_case'] = Server::table("tb_case")
                ->whereArr($w)
                ->where(function ($query) use ($w2) {
                    $query->orWhere('title', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('case_hn', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('procedurename', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('case_history', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('indication', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('indication_other', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('medication_unit', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('medi_other', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('anesthesia', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('anesthesiaother', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('finding', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('overall_finding', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('diagnostic_text', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('overall_diagnosis', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('procedure_subtext', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('bowel_other', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('bowelpreparation', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('gastriccontent', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('specimen1', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('specimen2', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('specimen3', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('specimen4', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('box_rapid_pending', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('rapid_other', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('complication', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('technique_other', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('case_comment', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('assistant', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('urgent', 'regexp', new Regex($w2, 'i'))
                        ->orWhere('overall_procedure', 'regexp', new Regex($w2, 'i'));
                })
                ->paginate(500)->withQueryString();
        } else {
            $view['tb_case'] = Server::table("tb_case")->whereArr($w)->paginate(500)->withQueryString();
        }



        $view['case_count']     = $view['tb_case']->total();
        $view['download']       = ceil($view['case_count'] / 10000);
        $view['search']         = $_COOKIE['search'] ?? [];
        // $view['filter']         = @$r->all();
        $_SESSION['search']     = $w;
        $_SESSION['keyword']    = $w2;


        // dd($view);
        // dd($_COOKIE['search']);
        // dd( $_SESSION['search']);
        return view('exportdata/index', $view);
    }



    public function checksearch($r, $w, $text, $array)
    {
        if (isset($r->$text)) {
            $w[] = $array;
            $_COOKIE['search'][$text] = $r->$text;
        }
        return $w;
    }

    public function export() {}

    public function geticd($r)
    {
        $arr['icd9'] = $this->geticd9($r);
        $arr['icd10'] = $this->geticd10($r);
        return jsonEncode($arr);
    }

    public static function geticd9($r)
    {
        $w[] = array('icd9', '!=', null);
        $tb_procedure   = Server::table('tb_procedure')->where($w)->select('name', 'icd9')->get();
        if (isset($r->procedure)) {
            $tb_procedure = Server::table('tb_procedure')->where($w)->whereIn('name', $r->procedure)->select('name', 'icd9')->get();
        }

        $icd9        = [];
        foreach ($tb_procedure as $proc) {
            $proc = (object) $proc;
            if (!isset($proc->name) || !isset($proc->icd9)) {
                continue;
            }

            $icd9_proc = is_array($proc->icd9) ? $proc->icd9 : [];
            foreach ($icd9_proc as $key => $data) {
                if (isset($data)) {
                    for ($i = 0; $i < count($data); $i++) {
                        $name = $data[$i]['name'];
                        if (isset($name) && @$name . "" != "") {
                            $icd9[] = $name;
                        }
                    }
                }
            }
        }

        return $icd9;
    }




    public static function geticd10($r)
    {
        $w[] = array('icd10', '!=', null);
        $tb_procedure = Server::table('tb_procedure')->where($w)->select('name', 'icd10')->get();
        if (isset($r->procedure)) {
            $tb_procedure = Server::table('tb_procedure')->where($w)->whereIn('name', $r->procedure)->select('name', 'icd10')->get();
        }
        $icd10        = [];
        foreach ($tb_procedure as $proc) {
            $proc = (object) $proc;
            if (!isset($proc->name) || !isset($proc->icd10)) {
                continue;
            }
            $icd10_proc = is_array($proc->icd10) ? $proc->icd10 : [];
            foreach ($icd10_proc as $key => $data) {
                if (isset($data)) {
                    for ($i = 0; $i < count($data); $i++) {
                        $name = $data[$i]['name'];
                        if (isset($name) && @$name . "" != "") {
                            $icd10[] = $name;
                        }
                    }
                }
            }
        }
        return $icd10;
    }

    public function edit($id)
    {
        // dd($id);
        session_start();
        $_SESSION['download_start'] = $id * 10000;
        $end    = $_SESSION['download_start'] + 10000;
        $moss   = new DataExport;
        return Excel::download($moss, 'report' . $_SESSION['download_start'] . "_" . $end . ".xls");
    }
}
