<?php

require_once("imp/_imp.php");

class Controllers {

    //public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $time;
    public $today;
    public $patientid;

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

        //here name of controll to known
        $this->controllname = 'ivf_reports';
        $this->shcontrollname = 'ivf_reports';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        require_once("../../_library/plugins/classupload/uploadfunctions.php");

        //breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'ivf_reports'; //controller name or tab name
        $active[1] = 'ivf_reports'; //controller name
        // do name  // switch($do)
        switch ($acty) {
            case '':
                $active[2] = 'ivf_reportsadd';
                break;
            case 'show':
                $active[2] = 'ivf_reportsshow';
                break;
            default:
                $active[2] = 'ivf_reportsshow';
                break;
        }
        $this->active = $active;

        R::ext('xdispense', function ($type) {
            return R::getRedBean()->dispense($type);
        });

        //here will call all php pages
        require_once("_header.php");
        require_once("_patientdata.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
        require_once("fn_common.php"); //general functions

        $this->patientid = patientdata::patientid();

        //find loading time
        $this->time = microtime(true);
        $this->today = date('Y-m-d');
    }

    public function semen_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $semen_analysis = R::getAll('select semen_analysis.id  ,awusers.name as referred_dr_name  
                                                                , semen_analysis.semen_date  
                            from  semen_analysis 
                            LEFT JOIN  awusers ON         semen_analysis.h_doctor1 =awusers.user_id
                            where semen_analysis.deleted != 1 and semen_analysis.completed =  1 
                            and patient_id = ' . $patientid);

        $this->smarty->assign('semen_analysis', $semen_analysis);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/semen_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function semen_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $semen_analysis = R::findOne('semen_analysis', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($semen_analysis) <= 0) {
            //create new
            $patient = R::load('patients', $patientid);

            $semen_analysis = R::xdispense('semen_analysis');
            $semen_analysis->patient_id = $patientid;
            $semen_analysis->semen_date = $this->today;
            $semen_analysis->completed = 0;

            if ($patient->doctor1 > 0) {
                $semen_analysis->doctor1 = $patient->doctor1;
            }

            if ($patient->h_doctor1 > 0) {
                $semen_analysis->h_doctor1 = $patient->h_doctor1;
            }


            $semen_analysis->user_id = $_SESSION['user_id'];
            $semen_analysis_id = R::store($semen_analysis);
        } else {
            $semen_analysis_id = $semen_analysis->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'semen_analysis');
        $this->smarty->assign('show', 'semen_show');

        $this->loadSemen($semen_analysis_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/semen_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadSemen($semen_analysis_id) {

        $semen_analysis = R::getRow('select *  ,  clin.name as clinician_name 
            ,  embryologist.name as embryologist_name 
            
                from semen_analysis 
                left join   awusers   clin                       on   semen_analysis.clinician   =  clin.user_id 
                left join   awusers   embryologist       on   semen_analysis.embryologist   =  embryologist.user_id 
                
                where id = ' . $semen_analysis_id);

        $semen_analysis['semen_date'] = date('Y/m/d', strtotime($semen_analysis['semen_date']));
        $this->smarty->assign('semen_analysis', $semen_analysis);

        $this->smarty->assign('patientId', $semen_analysis['patient_id']);

        #############################  load section 1  => refer + semen ##############################

        $this->getReferredDr($semen_analysis['h_doctor1']);
        return $semen_analysis;
    }

    public function semen_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $semen_analysis_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadSemen($semen_analysis_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/semen_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function printSemenReport() {

        //check login
        autho::checkautho($this->hosturl);
        $semen_analysis_id = filter_input(INPUT_POST, 'id');

        $semen = $this->loadSemen($semen_analysis_id);
        $patient = R::load("patients", $semen['patient_id']);

        $this->smarty->assign('wifename', $patient->wifename);
        $this->smarty->assign('husbandname', $patient->husdandname);
        $this->smarty->assign('semenDate', date('d/m/Y', strtotime($semen['semen_date'])));

        $husbandage = $this->getPatientAgeEx($patient->husbanddateofbirth, $semen['semen_date']);
        $this->smarty->assign('husbandage', $husbandage);
        $this->smarty->display('ivf_reports/semen_print.html');
    }

    function getPatientAgeEx($birthDate, $completed_date) {
        $completed_date = date('Y-m-d', strtotime($completed_date));
        $date = new DateTime($completed_date);

        $dateWife = new DateTime($birthDate);

        if ($birthDate == '0000-00-00' || is_null($birthDate)) {
            $patAge = 0;
        } else {
            $interva2 = $date->diff($dateWife);
            $patAge = $interva2->y;
        }

        return $patAge;
    }

    ###########################################################

    public function cryopreservation_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $semen_cryopreservation = R::getAll('select semen_cryopreservation.id  ,awusers.name as referred_dr_name  
                                                                , semen_cryopreservation.semen_date  
                            from  semen_cryopreservation 
                            LEFT JOIN  awusers ON         semen_cryopreservation.h_doctor1 =awusers.user_id
                            where semen_cryopreservation.deleted != 1 and semen_cryopreservation.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('semen_cryopreservation', $semen_cryopreservation);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/cryopreservation_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function cryopreservation_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $semen_cryopreservation = R::findOne('semen_cryopreservation', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($semen_cryopreservation) <= 0) {
            //create new
            $patient = R::load('patients', $patientid);

            $semen_cryopreservation = R::xdispense('semen_cryopreservation');
            $semen_cryopreservation->patient_id = $patientid;
            $semen_cryopreservation->semen_date = $this->today;
            $semen_cryopreservation->completed = 0;
            $semen_cryopreservation->doctor1 = $patient->doctor1;
            $semen_cryopreservation->h_doctor1 = $patient->h_doctor1;
            $semen_cryopreservation->user_id = $_SESSION['user_id'];
            $semen_cryopreservation_id = R::store($semen_cryopreservation);
        } else {
            $semen_cryopreservation_id = $semen_cryopreservation->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'semen_cryopreservation');
        $this->smarty->assign('show', 'cryopreservation_show');

        $this->loadCryopreservation($semen_cryopreservation_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/cryopreservation_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadCryopreservation($semen_cryopreservation_id) {

        $semen_cryopreservation = R::getRow('select *  ,  clin.name as clinician_name 
            ,  embryologist.name as embryologist_name 
            
                from semen_cryopreservation 
                left join   awusers   clin                       on   semen_cryopreservation.clinician   =  clin.user_id 
                left join   awusers   embryologist       on   semen_cryopreservation.embryologist   =  embryologist.user_id 
                
                where id = ' . $semen_cryopreservation_id);

        $semen_cryopreservation['semen_date'] = date('Y/m/d', strtotime($semen_cryopreservation['semen_date']));
        $this->smarty->assign('semen_cryopreservation', $semen_cryopreservation);

        $this->smarty->assign('patientId', $semen_cryopreservation['patient_id']);

        #############################  load section 1  => refer + semen ##############################

        $this->getReferredDr($semen_cryopreservation['h_doctor1']);
    }

    public function cryopreservation_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $semen_cryopreservation_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadCryopreservation($semen_cryopreservation_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/cryopreservation_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function cryopreservation_print() {
        //check login
        autho::checkautho($this->hosturl);
        $patientId = filter_input(INPUT_POST, "patientid");

        $patientData = R::load("patients", $patientId);

        $wifename = $patientData->wifename;
        $husbandname = $patientData->husdandname;
        $husbandage = $patientData->husbandage;

        $this->smarty->assign('wifename', $wifename);
        $this->smarty->assign('husbandname', $husbandname);
        $this->smarty->assign('husbandage', $husbandage);

        $semen_cryopreservation_id = filter_input(INPUT_POST, "id");
        if ($semen_cryopreservation_id > 0) {
            $this->loadCryopreservation($semen_cryopreservation_id);
            $this->smarty->display('ivf_reports/cryopreservation_print.html');
        } else {
            echo -1;
        }
    }

    ###########################################################

    public function processing_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $semen_processing = R::getAll('select semen_processing.id  ,awusers.name as referred_dr_name  
                                                                , semen_processing.semen_date  
                            from  semen_processing 
                            LEFT JOIN  awusers ON         semen_processing.h_doctor1 =awusers.user_id
                            where semen_processing.deleted != 1 and semen_processing.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('semen_processing', $semen_processing);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/iui_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function processing_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $semen_processing = R::findOne('semen_processing', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($semen_processing) <= 0) {
            //create new
            $patient = R::load('patients', $patientid);

            $semen_processing = R::xdispense('semen_processing');
            $semen_processing->patient_id = $patientid;
            $semen_processing->semen_date = $this->today;
            $semen_processing->completed = 0;

            if ($patient->doctor1 > 0) {
                $semen_processing->doctor1 = $patient->doctor1;
            }

            if ($patient->h_doctor1 > 0) {
                $semen_processing->h_doctor1 = $patient->h_doctor1;
            }

            $semen_processing->user_id = $_SESSION['user_id'];
            $semen_processing_id = R::store($semen_processing);
        } else {
            $semen_processing_id = $semen_processing->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'semen_processing');
        $this->smarty->assign('show', 'processing_show');

        $this->loadProcessing($semen_processing_id);

        $freezing_media = R::findAll("freezingmedia");
        $this->smarty->assign('freezing_media', $freezing_media);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/iui_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function processing_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $semen_processing_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadProcessing($semen_processing_id);

        $freezing_media = R::findAll("freezingmedia");
        $this->smarty->assign('freezing_media', $freezing_media);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/iui_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function processing_print() {
        //check login
        autho::checkautho($this->hosturl);

        $semen_processing_id = filter_input(INPUT_POST, "id");
        $patientid = filter_input(INPUT_POST, "patientid");
        $patientData = R::load("patients", $patientid);
        $wifename = $patientData->wifename;
        $husbandname = $patientData->husdandname;
        $husbandage = $patientData->husbandage;

        $this->smarty->assign('wifename', $wifename);
        $this->smarty->assign('husbandname', $husbandname);
        $this->smarty->assign('husbandage', $husbandage);
        if ($semen_processing_id > 0) {
            $this->loadProcessing($semen_processing_id);
            $this->smarty->display('ivf_reports/iui_print.html');
        } else {
            echo -1;
        }
    }

    function loadProcessing($semen_processing_id) {

        $semen_processing = R::getRow('select *  ,  clin.name as clinician_name 
            ,  embryologist.name as embryologist_name 
            
                from semen_processing 
                left join   awusers   clin                       on   semen_processing.clinician   =  clin.user_id 
                left join   awusers   embryologist       on   semen_processing.embryologist   =  embryologist.user_id 
                
                where id = ' . $semen_processing_id);

        $semen_processing['semen_date'] = date('Y/m/d', strtotime($semen_processing['semen_date']));
        $this->smarty->assign('semen_processing', $semen_processing);

        $this->smarty->assign('patientId', $semen_processing['patient_id']);
        if ($semen_processing['catheter']) {
            $catheter = R::load('embryo_catheter_select', $semen_processing['catheter']);
            $this->smarty->assign('catheterName', $catheter->name);
        }
        if ($semen_processing['media']) {
            $freezingmedia = R::load('freezingmedia', $semen_processing['media']);
            $this->smarty->assign('freezingmedia', $freezingmedia->media);
        }
        #############################  load section 1  => refer + semen ##############################

        $this->getReferredDr($semen_processing['h_doctor1']);

        $records = R::findAll('embryo_catheter_select', ' deleted != 1 ');
        $this->smarty->assign('embryo_catheter_select', $records);
    }

    ###########################################################

    public function sperm_extract() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $sperm_extract = R::getAll('select sperm_extract.id  ,awusers.name as referred_dr_name  
                                                                , sperm_extract.date  
                            from  sperm_extract 
                            LEFT JOIN  awusers ON         sperm_extract.h_doctor1 =awusers.user_id
                            where sperm_extract.deleted != 1 and sperm_extract.completed =  1 
                            and patient_id = ' . $patientid);

        $this->smarty->assign('sperm_extract', $sperm_extract);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/sperm_extract.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function sperm_extract_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $sperm_extract = R::findOne('sperm_extract', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($sperm_extract) <= 0) {
            //create new
            $patient = R::load('patients', $patientid);

            $sperm_extract = R::xdispense('sperm_extract');
            $sperm_extract->patient_id = $patientid;
            $sperm_extract->date = $this->today;
            $sperm_extract->completed = 0;
            $sperm_extract->doctor1 = $patient->doctor1;
            $sperm_extract->h_doctor1 = $patient->h_doctor1;
            $sperm_extract->user_id = $_SESSION['user_id'];
            $sperm_extract_id = R::store($sperm_extract);
        } else {
            $sperm_extract_id = $sperm_extract->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'sperm_extract');
        $this->smarty->assign('show', 'sperm_extract');

        $this->loadSpermExtract($sperm_extract_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/sperm_extract_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadSpermExtract($sperm_extract_id) {

        $sperm_extract = R::getRow('select *  ,  sergeon.name as sergeon_name 
            ,  embryologist.name as embryologist_name 
            
                from sperm_extract 
                left join   awusers   sergeon                       on   sperm_extract.sergeon   =  sergeon.user_id 
                left join   awusers   embryologist       on   sperm_extract.embryologist   =  embryologist.user_id 
                
                where id = ' . $sperm_extract_id);

        $sperm_extract['date'] = date('Y/m/d', strtotime($sperm_extract['date']));
        $this->smarty->assign('sperm_extract', $sperm_extract);

        $this->smarty->assign('patientId', $sperm_extract['patient_id']);

        $tables = array("varic_select", "asp_select", "tb_select", "mtb_select");

        foreach ($tables as $table) {
            $records = R::findAll($table, ' deleted != 1 ');
            $this->smarty->assign($table, $records);
        }

        $this->getReferredDr($sperm_extract['h_doctor1']);
    }

    public function sperm_extract_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $sperm_extract_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadSpermExtract($sperm_extract_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/sperm_extract_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateselect() {
        //check login
        autho::checkautho($this->hosturl);

        $tableName = filter_input(INPUT_POST, "tablename");
        $value = filter_input(INPUT_POST, "value");
        $id = filter_input(INPUT_POST, "id");

        $mydata = R::load($tableName, $id);
        $mydata->name = $value;
        R::store($mydata);

        $myalldata = R::findAll($tableName, 'deleted = 0');
        print_r($myalldata);
    }

    ###########################################################

    public function ivf_report() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $ivf_report = R::getAll('select ivf_report.id  ,treatprotocol.name as protocolName  
                                                                , ivf_report.trial_no  
                            from  ivf_report 
                                LEFT JOIN  awusers            ON         ivf_report.doctor1 =awusers.user_id
                                LEFT JOIN  treatprotocol     ON         ivf_report.treat_protocol =treatprotocol.id
                            where ivf_report.deleted != 1 and ivf_report.completed =  1 
                            and patient_id = ' . $patientid);

        $this->smarty->assign('ivf_report', $ivf_report);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/ivf_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function ivf_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $ivf_report = R::findOne('ivf_report', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($ivf_report) <= 0) {
            //create new
            $patient = R::load('patients', $patientid);

            $ivf_report = R::xdispense('ivf_report');
            $ivf_report->patient_id = $patientid;
            $ivf_report->completed = 0;
            $ivf_report->doctor1 = $patient->doctor1;
            $ivf_report->h_doctor1 = $patient->h_doctor1;
            $ivf_report->user_id = $_SESSION['user_id'];
            $ivf_report->create_date = date('Y-m-d H:i:s');
            $ivf_report_id = R::store($ivf_report);
        } else {
            $ivf_report_id = $ivf_report->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'ivf_report');
        $this->smarty->assign('show', 'ivf_report');

        $this->loadIVF($ivf_report_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/ivf_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadIVF($ivf_report_id) {
        $ivf_report = R::getRow('select *   from ivf_report   where id = ' . $ivf_report_id);
        $this->smarty->assign('ivf_report', $ivf_report);

        $treatprotocol = R::findAll('treatprotocol', ' deleted != 1 ');
        $this->smarty->assign('treatprotocol', $treatprotocol);

        $this->loadIVFDrugs($ivf_report_id);
        $this->loadIVFRecords($ivf_report_id);
        $this->loadDrugsData();
        $this->getReferredDr($ivf_report['doctor1']);
        $this->getPatientAge($ivf_report['patient_id'], $ivf_report['completed'], $ivf_report['completed_date']);
        $dayName = $this->getDayNameFnAr($ivf_report['trig_date']);
        $this->smarty->assign('dayName', $dayName);

        $this->smarty->assign('patientId', $ivf_report['patient_id']);
    }

    function loadIVFDrugs($ivf_report_id) {
        $ivf_drugs = R::getAll(
                        'select ivf_drugs.id , ivf_drugs.drugid , ivf_drugs.drugdos  , drugs.drugname  as drugName
                                                  from ivf_drugs   
                                                       LEFT JOIN  drugs            ON         ivf_drugs.drugid =drugs.id
                                                    where ivf_drugs.deleted != 1 and ivf_drugs.ivf_report_id = ?  ',
                        [$ivf_report_id]
        );
        $this->smarty->assign('ivf_drugs', $ivf_drugs);
    }

    function loadIVFRecords($ivf_report_id) {
        $ivf_records = R::findAll('ivf_records', ' deleted != 1 and ivf_report_id = ? order by record_date asc  ', [$ivf_report_id]);

        foreach ($ivf_records as $ivf_record) {
            $ivf_records_drugs = R::getAll('select ivf_records_drugs.id ,   ivf_records_drugs.drugid 
                                                        , ivf_records_drugs.drugdos  , drugs.drugname  as drugName
                from ivf_records_drugs  
                  LEFT JOIN  drugs            ON         ivf_records_drugs.drugid =drugs.id
                where ivf_records_drugs.deleted != 1 and ivf_records_drugs.ivf_records_id = ?  ', [$ivf_record->id]);
            $ivf_record->record_drugs = $ivf_records_drugs;
        }
        $this->smarty->assign('ivf_records', $ivf_records);
    }

    function addNewRow() {
        $id = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, 'tableName');
        try {
            $obj = R::xdispense($tableName);
            switch ($tableName) {
                case "ivf_records":
                    $obj->ivf_report_id = $id;
                    break;
                case "ivf_drugs":
                    $obj->ivf_report_id = $id;
                    $this->loadDrugsData();
                    $this->smarty->assign('dosName', 'ddosIvf');
                    $this->smarty->assign('drgName', 'dnameIvf');
                    break;
                case "ivf_records_drugs":
                    $obj->ivf_records_id = $id;
                    $this->loadDrugsData();
                    $this->smarty->assign('dosName', 'ddosRec');
                    $this->smarty->assign('drgName', 'dnameRec');
                    $this->smarty->assign('origin', $id);
                    break;
            }

            $obj->user_id = $_SESSION['user_id'];
            $obj->create_date = date('Y-m-d H:i:s');
            $obj->id = R::store($obj);

            $this->smarty->assign('data', $obj);
            $this->smarty->assign('tableName', $tableName);

            $this->smarty->display('ivf_reports/ivf_rows.html');
        } catch (Exception $ex) {
            echo -1;
        }
    }

    function loadDrugsData() {
        $drugs = R::getAll('SELECT  id , drugname   FROM drugs where ivf_show = 1   order by drugname asc');
        $allDrugDoses = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');

        $this->smarty->assign('ivfDrugs', $drugs);
        $this->smarty->assign('allDrugDoses', $allDrugDoses);
    }

    public function ivf_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $ivf_report_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadIVF($ivf_report_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/ivf_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function ivf_print() {
        //check login
        autho::checkautho($this->hosturl);

        $ivf_report_id = filter_input(INPUT_POST, "id");
        if ($ivf_report_id > 0) {
            $this->loadIVFPrint($ivf_report_id);
            $this->smarty->display('ivf_reports/ivf_print.html');
        } else {
            echo -1;
        }
    }

    function loadIVFPrint($ivf_report_id) {
        $ivf_report = R::getRow('select ivf_report. *    , treatprotocol.name as protocolName  
                                from ivf_report   
                                LEFT JOIN  awusers            ON         ivf_report.doctor1 =awusers.user_id
                                LEFT JOIN  treatprotocol     ON         ivf_report.treat_protocol =treatprotocol.id
                where ivf_report.id = ' . $ivf_report_id);

        $ivf_report['trig_time'] = date('h:i A', strtotime($ivf_report['trig_time']));
        $this->smarty->assign('ivf_report', $ivf_report);

        $this->loadIVFDrugs($ivf_report_id);
        $this->loadIVFRecords($ivf_report_id);
        $this->getReferredDr($ivf_report['doctor1']);
        $this->getPatientAge($ivf_report['patient_id'], $ivf_report['completed'], $ivf_report['completed_date']);
    }

    public function addnewrecord() {
        //check login
        autho::checkautho($this->hosturl);

        //vars here
        $table = filter_input(INPUT_POST, 'selectId');
        $name = filter_input(INPUT_POST, 'new_name');
        $colName = filter_input(INPUT_POST, 'colname');

        try {

            $record = R::xdispense($table);
            $record->$colName = $name;
            $record->ivf_show = 1;
            $id = R::store($record);

            if ($colName == 'drugdos') {
                echo $name;
            } else {
                echo $id;
            }
        } catch (Exception $e) {
            echo $e;
        }
    }

    ###########################################################

    public function del() {

        //check login
        autho::checkautho($this->hosturl);
        //        //check authoize
        //        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $id = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, 'tableName');
        try {

            if (
                    $tableName == "ivf_report" || $tableName == "ivf_records" || $tableName == "ivf_drugs" ||
                    $tableName == "ivf_records_drugs"
            ) {
                R::exec('update  ' . $tableName . ' set deleted = 1 ,  delete_userid = ' . $_SESSION['user_id'] . '    ,  
                         delete_date = "' . date('Y-m-d H:i:s') . '" WHERE id = ' . $id);
            } else {
                R::exec('update  ' . $tableName . ' set deleted = 1  WHERE id = ' . $id);
            }
            echo 1;
        } catch (Exception $e) {
            echo $e;
        }
    }

    public function complete_one() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $id = filter_input(INPUT_GET, 'id');
        $tableName = filter_input(INPUT_GET, 'tname');
        $show = filter_input(INPUT_GET, 'show');
        $patientid = filter_input(INPUT_GET, "patientid");
        try {
            if ($tableName == "ivf_report") {
                R::exec('update  ' . $tableName . ' set completed = 1  
                          ,   completed_date = "' . date('Y-m-d H:i:s') . '"    WHERE id = ' . $id);
            } else {
                R::exec('update  ' . $tableName . ' set completed = 1  WHERE id = ' . $id);
            }

            if (!empty($patientid)) {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=' . $show . '&patientid=' . $patientid);
            } else {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=' . $show);
            }
        } catch (Exception $e) {
            print_r($e);
            //    header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
        }
    }

    function getReferredDr($userId) {

        if ($userId > 0) {
            $refer = R::getRow('select name from awusers where user_id = ?', [$userId]);
            $ref_dr = $refer['name'];
        } else {
            $ref_dr = 'لا يوجد';
        }

        $this->smarty->assign('ref_dr', $ref_dr);
    }

    public function update() {
        $id = filter_input(INPUT_POST, "id");
        $value = filter_input(INPUT_POST, "value");
        $tableName = filter_input(INPUT_POST, "tableName");
        $colName = filter_input(INPUT_POST, "colName");
        $patientId = filter_input(INPUT_POST, "patientId");
        $multi = filter_input(INPUT_POST, "multi");

        //here the update
        $mydata = R::load($tableName, $id);
        if ($multi == 1 || $colName == 'pre_history') {
            $selected = json_decode($value);
            sort($selected);
            $value = "";
            foreach ($selected as $myname) {
                $value = $value . $myname . ",";
            }
            $value = substr($value, 0, -1);
        }

        $mydata->$colName = $value;
        R::store($mydata);
    }

    function getPatientAge($patientId, $completed, $completed_date) {
        if ($completed > 0) {
            $date = date('Y-m-d', strtotime($completed_date));
        } else {
            $date = date('Y-m-d');
        }
        $date = new DateTime($date);

        $patient = R::load('patients', $patientId);
        $this->smarty->assign('patName', $patient->wifename);
        $dateWife = new DateTime($patient->dateofbirth);

        if ($patient->dateofbirth == '0000-00-00' || is_null($patient->dateofbirth)) {
            $this->smarty->assign('patAge', 0);
        } else {
            $interva2 = $date->diff($dateWife);
            $this->smarty->assign('patAge', $interva2->y);
        }
    }

    ###########################################################

    public function ivf_report_search() {
        $findate = filter_input(INPUT_POST, 'findate');
        $todate = filter_input(INPUT_POST, 'todate');
        $print = filter_input(INPUT_POST, 'print');
        $searchFn = (filter_input(INPUT_POST, 'searchFn')) . 'Search';
        $searchHtml = (filter_input(INPUT_POST, 'searchFn')) . '_search';
        $wId = filter_input(INPUT_POST, 'wId');
        $hId = filter_input(INPUT_POST, 'hId');
        $patientId = 0;
        if ($wId > 0 || $hId > 0) {
            if ($hId > 0) {
                $patientId = $hId;
            } else {
                $patientId = $wId;
            }
        }

        $this->$searchFn($findate, $todate, $patientId);
        if ($print == 1) {
            //      $this->smarty->display('adddevices/rfc_report_print.html');
        } else {
            $this->smarty->display('ivf_reports/' . $searchHtml . '.html');
        }
    }

    public function freezing_report() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $today = date("Y/m/d");
        $this->smarty->assign('today', date('Y/m/d', strtotime($today)));

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('ivf_reports/freezing.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function freezingSearch($fromDate, $toDate, $patientId) {
        $ext = '';
        if (!empty($patientId) && $patientId > 0) {
            $ext .= ' and embryoslab.patient_id = ' . $patientId;
        }

        $sql = 'select    embryoslab.id ,  clin.name as clinician_name , visits.visitdate  
            , patients.dateofbirth   , patients.wifename     ,  embryoslab.no_oocyte    
             ,  embryoslab.mii     ,  embryoslab.injection     ,  embryoslab.fertilized    
             , "" as etTxt   ,  embryotransfer.stage1   ,  embryotransfer.stage2   ,  embryotransfer.stage3
              ,  embryotransfer.stage4   ,  embryotransfer.date_transer_embryo ,  embryoslab.no_straws
              ,  embryoslab.no_embryos   , CASE    WHEN visits.result = 1  THEN " +ve "    
                                 WHEN visits.result = 2  THEN " -ve "     ELSE " "    END as preg 
                       from    embryoslab    
                           join     patients                                     on   embryoslab.patient_id   =  patients.id     
                         left join   awusers   clin                       on   embryoslab.clinician_id   =  clin.user_id      
                         join     visits                                     on   embryoslab.visit_id   =  visits.id      
                       left    join     embryotransfer                         on   embryotransfer.embryoslab_id   =  embryoslab.id     
                       
                  where visits.deleted  != 1     and  embryoslab.not_confirm  =  1    ' . $ext . '     
                  and visits.visitdate between  ? and ?  group by  embryoslab.id  ';

        $results = R::getAll($sql, [$fromDate, $toDate]);

        $i = 0;

        foreach ($results as $result) {
            $results[$i]['age'] = calcPatAge($result['dateofbirth'], $result['visitdate']);
            $et = 0;
            for ($x = 1; $x <= 4; $x++) {
                if ($result['stage' . $x] == 2) {
                    if ($et > 0) {
                        $results[$i]['etTxt'] .= ' , ';
                    }
                    $results[$i]['etTxt'] .= $x;
                    $et++;
                }
            }

            $i++;
        }
        $this->smarty->assign('results', $results);
        $this->smarty->assign('resCount', count($results));
    }

    public function icsi_cases_report() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $today = date("Y/m/d");
        $this->smarty->assign('today', date('Y/m/d', strtotime($today)));

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('ivf_reports/icsi_cases.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function icsi_casesSearch($fromDate, $toDate, $patientId) {
        $results = $this->totalCasesAll($fromDate, $toDate, '');
        $result['totalEC'] = count($results);

        foreach ($results as $res) {
            $age = calcPatAgeYear($res['dateofbirth'], $res['visitdate']);
            $status = 0;     ##   0 e.c , 1 preg    , 2 cancelled
            #########################################################
            if ($res['cancelled'] == 1) {
                $status = 2;
                $result['totalCancelled']++;
            } else {
                if ($res['et_day'] > 0) {
                    $result['totalET']++;
                    $result = $this->transferDays($result, $res['et_day'], $status);
                }
                if ($res['dayoffreezzing'] > 0) {
                    $result['totalFreezing']++;
                    $result['totalFrozenStraws'] = $result['totalFrozenStraws'] + +$res['no_straws'];
                    $result['totalFrozenEmbryos'] = $result['totalFrozenEmbryos'] + +$res['no_embryos'];
                }
            }
            ######################################################
            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['result'] == 1) {
                //                print_r('<pre>');
                //                print_r($res['id']);
                //                print_r('</pre>');
                $status = 1;
                $result['etPositive']++;
            }

            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['result'] != 1 && $res['result'] != 2) {
                $result['etNoAnswer']++;
            }

            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['stage1'] == 2) {
                $result['blastocyst1']++;
            }

            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['stage2'] == 2) {
                $result['blastocyst2']++;
            }

            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['stage3'] == 2) {
                $result['blastocyst3']++;
            }

            if ($res['et_day'] > 0 && $res['cancelled'] == 0 && $res['stage4'] == 2) {
                $result['blastocyst4']++;
            }
            ######################################################
            $result['totalInjectedOocytes'] = 0;
            $result['totalOocytes'] = $result['totalOocytes'] + $res['no_oocyte'];
            $result['totalMii'] = $result['totalMii'] + $res['mii'];
            $result['totalFertilized'] = $result['totalFertilized'] + $res['fertilized'];
            if ($result['totalOocytes'] > 0) {
                $result['totalInjectedOocytes'] = ($result['totalMii'] / $result['totalOocytes']) * 100;
                $result['totalInjectedOocytes'] = round($result['totalInjectedOocytes'], 1);
            }
            ######################################################
            $result = $this->ageSums($result, $age, $status);
            $result = $this->oocytesSums($result, $res['no_oocyte'], $status);
        }

        $result['etPositiveRate'] = 0;
        if (($result['totalET'] - $result['etNoAnswer']) > 0) {
            $result['etPositiveRate'] = ($result['etPositive'] / ($result['totalET'] - $result['etNoAnswer'])) * 100;
            $result['etPositiveRate'] = round($result['etPositiveRate'], 1);
        }


        $this->cancelReasons($fromDate, $toDate);
        $this->smarty->assign('result', $result);
    }

    function transferDays($result, $et_day, $status) {
        switch ($et_day) {
            case 2:
                $result['day2TransferCases']++;
                break;
            case 3:
                $result['day3TransferCases']++;
                break;
            case 4:
                $result['day4TransferCases']++;
                break;
            case 5:
                $result['day5TransferCases']++;
                break;
            case 6:
                $result['day6TransferCases']++;
                break;
        }

        return $result;
    }

    function oocytesSums($result, $no_oocyte, $status) {
        if ($no_oocyte >= 15) {
            $result['totalOverOocytes15']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregOverOocytes15']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelOverOocytes15']++;
                    break;
            }
        } elseif ($no_oocyte <= 5) {
            $result['totalUnderOocytes5']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregUnderOocytes5']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelUnderOocytes5']++;
                    break;
            }
        } else {
            $result['totalbetweenrOocytes5_15']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregbetweenrOocytes5_15']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelbetweenrOocytes5_15']++;
                    break;
            }
        }

        return $result;
    }

    function ageSums($result, $age, $status) {
        if ($age <= 34) {
            $result['totalUnderAge35']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregUnderAge35']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelUnderAge35']++;
                    break;
            }
        }

        if ($age >= 35) {
            $result['totalOverAge35']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregOverAge35']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelOverAge35']++;
                    break;
            }
        }

        if ($age <= 39) {
            $result['totalUnderAge39']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregUnderAge39']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelUnderAge39']++;
                    break;
            }
        }

        if ($age >= 40) {
            $result['totalOverAge40']++;
            switch ($status) {
                case 1:     ##  preg
                    $result['pregOverAge40']++;
                    break;

                case 2:    ##  cancelled
                    $result['cancelOverAge40']++;
                    break;
            }
        }

        return $result;
    }

    function totalCasesAll($fromDate, $toDate, $ex) {
        $sql = 'select  embryoslab.id  , embryotransfer.et_day  , embryoslab.cancelled , visits.result  , visits.visitdate  
             ,  embryotransfer.stage1   ,  embryotransfer.stage2   ,  embryotransfer.stage3 ,  embryotransfer.stage4
              ,  embryoslab.no_oocyte      ,  embryoslab.mii   ,  embryoslab.fertilized      , patients.dateofbirth 
              ,  embryoslab.dayoffreezzing ,  embryoslab.no_straws ,  embryoslab.no_embryos
               , patients.wifename     , patients.statusno   , embryoslab.patient_id
                     from    embryoslab     
                        join     visits                                     on   embryoslab.visit_id   =  visits.id      
                       join     patients                                     on   embryoslab.patient_id   =  patients.id     
                       left    join     embryotransfer                         on   embryotransfer.embryoslab_id   =  embryoslab.id     
                       
                  where visits.deleted  != 1     and  embryoslab.not_confirm  =  1   ' . $ex . '  
                  and embryoslab.no_oocyte > 0   and visits.visitdate between  ? and ? group by  embryoslab.id   ';
        //    r::debug(true, 2);
        $result = R::getAll($sql, [$fromDate, $toDate]);
        //   r::debug(false);
        return $result;
    }

    public function icsi_casesSearch2($fromDate, $toDate, $patientId) {
        $result['totalEC'] = $this->totalCases($fromDate, $toDate, '', '', 'count(embryoslab.id)');
        ######################################################
        $result['totalET'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0  ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );
        ######################################################
        $result['totalCancelled'] = $this->totalCases($fromDate, $toDate, ' and  embryoslab.cancelled  =  1  ', '', 'count(embryoslab.id)');
        ######################################################
        $result['etPositive'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and visits.result = 1   ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        $result['etNoAnswer'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and visits.result != 1   and visits.result != 2  ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        $result['etPositiveRate'] = ($result['etPositive'] / ($result['totalET'] - $result['etNoAnswer'])) * 100;
        $result['etPositiveRate'] = round($result['etPositiveRate'], 1);
        ######################################################
        $result['blastocyst1'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and embryotransfer.stage1 = 2   ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        $result['blastocyst2'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and embryotransfer.stage2 = 2   ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        $result['blastocyst3'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and embryotransfer.stage3 = 2   ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        $result['blastocyst4'] = $this->totalCases(
                $fromDate,
                $toDate,
                ' and embryotransfer.et_day > 0 and  embryoslab.cancelled  =  0 and embryotransfer.stage4 = 2   ',
                '  join     embryotransfer    on   embryotransfer.embryoslab_id   =  embryoslab.id    ',
                'count(embryoslab.id)'
        );

        ######################################################
        $result['totalOocytes'] = $this->totalCases($fromDate, $toDate, '', '', 'sum(embryoslab.no_oocyte)');
        $result['totalMii'] = $this->totalCases($fromDate, $toDate, '', '', 'sum(embryoslab.mii)');
        $result['totalInjectedOocytes'] = ($result['totalMii'] / $result['totalOocytes']) * 100;
        $result['totalInjectedOocytes'] = round($result['totalInjectedOocytes'], 1);
        $result['totalFertilized'] = $this->totalCases($fromDate, $toDate, '', '', 'sum(embryoslab.fertilized)');
        ######################################################
        $this->cancelReasons($fromDate, $toDate);
        $this->smarty->assign('result', $result);
    }

    function totalCases($fromDate, $toDate, $ext, $extJoin, $col) {
        $sql = 'select  ' . $col . '  as totalCases  from    embryoslab     
                         join     visits                                     on   embryoslab.visit_id   =  visits.id      
                        ' . $extJoin . '       
                  where visits.deleted  != 1     and  embryoslab.not_confirm  =  1   ' . $ext . '       
                  and embryoslab.no_oocyte > 0   and visits.visitdate between  ? and ?   ';

        $result = R::getRow($sql, [$fromDate, $toDate]);
        return $result['totalCases'];
    }

    function cancelReasons($fromDate, $toDate) {
        $cancel_reason = R::getAll('select id , name , 0 as totalCases from cancel_reason  where deleted != 1 ');
        $i = 0;
        foreach ($cancel_reason as $reason) {
            $ext = ' and  embryoslab.cancelled  =  1 and  embryoslab.cancel_reason  =   ' . $reason['id'];
            $cancel_reason[$i]['totalCases'] = $this->totalCases($fromDate, $toDate, $ext, '', 'count(embryoslab.id)');
            $i++;
        }
        $this->smarty->assign('cancel_reason', $cancel_reason);
    }

    public function casesDetails() {
        $findate = filter_input(INPUT_POST, 'findate');
        $todate = filter_input(INPUT_POST, 'todate');
        $searchFn = (filter_input(INPUT_POST, 'type')) . 'Search';
        $wId = filter_input(INPUT_POST, 'wId');
        $hId = filter_input(INPUT_POST, 'hId');
        $patientId = 0;
        if ($wId > 0 || $hId > 0) {
            if ($hId > 0) {
                $patientId = $hId;
            } else {
                $patientId = $wId;
            }
        }

        $this->$searchFn($findate, $todate, $patientId);
        $this->smarty->display('ivf_reports/cases_details.html');
    }

    public function totalEcCasesSearch($fromDate, $toDate, $patientId) {
        $cases = $this->totalCasesAll($fromDate, $toDate, $ex);
        $this->smarty->assign('cases', $cases);
    }

    public function totalEtCasesSearch($fromDate, $toDate, $patientId) {
        $ex = '  and embryotransfer.et_day > 0   and embryoslab.cancelled != 1   ';
        $cases = $this->totalCasesAll($fromDate, $toDate, $ex);
        $this->smarty->assign('cases', $cases);
    }

    public function totalCancelledCasesSearch($fromDate, $toDate, $patientId) {
        $ex = '   and embryoslab.cancelled = 1   ';
        $cases = $this->totalCasesAll($fromDate, $toDate, $ex);
        $this->smarty->assign('cases', $cases);
    }

    public function totalPregnantCasesSearch($fromDate, $toDate, $patientId) {
        $ex = '  and embryotransfer.et_day > 0 and embryoslab.cancelled = 0 and  visits.result  = 1      ';
        $cases = $this->totalCasesAll($fromDate, $toDate, $ex);
        $this->smarty->assign('cases', $cases);
    }

    ###########################################################

    public function operation_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $operation_form = R::getAll('select operation_form.id  , operation_form.op_date  
                            from  operation_form 
                            where operation_form.deleted != 1 and operation_form.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('operation_form', $operation_form);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/operation_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function operation_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $operation_form = R::findOne('operation_form', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($operation_form) <= 0) {
            $operation_form = R::xdispense('operation_form');
            $operation_form->patient_id = $patientid;
            $operation_form->op_date = $this->today;
            $operation_form->completed = 0;
            $operation_form->user_id = $_SESSION['user_id'];
            $operation_form_id = R::store($operation_form);
        } else {
            $operation_form_id = $operation_form->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'operation_form');
        $this->smarty->assign('show', 'operation_show');

        $this->loadOperation($operation_form_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/operation_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function operation_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $operation_form_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadOperation($operation_form_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/operation_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function operation_print() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $operation_form_id = filter_input(INPUT_POST, "id");
        $this->loadOperationPrint($operation_form_id);
        $this->smarty->assign('date', date("Y-m-d"));
        $this->smarty->display('ivf_reports/operation_print.html');
    }

    function patientLastVisit($patientId) {
        $visitId = 0;
        $visit = R::findOne('visits', ' patientid = ?  and deleted != 1 
                and detectionid != 999  and detectionid != 9999     and for_department = 13
                and visitdate <= ? order by visitdate desc ', [$patientId, date('Y-m-d')]);
        if (count($visit) > 0) {
            $visitId = $visit->id;
        }
        return $visitId;
    }

    function loadOperation($operation_form_id) {

        $operation_form = R::getRow('select operation_form.*   
                from operation_form 
                where id = ' . $operation_form_id);

        if ($operation_form['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($operation_form['patient_id']);
            R::exec(' update operation_form set visit_id = ? where id = ?  ', [$visit_id, $operation_form_id]);
        }

        if (!empty($operation_form['op_date']) && trim($operation_form['op_date']) != '' && $operation_form['op_date'] != null) {
            $operation_form['op_date'] = date('Y/m/d', strtotime($operation_form['op_date']));
        }
        $operation_form['anasthesa_start'] = date('h:i A', strtotime($operation_form['anasthesa_start']));
        $operation_form['anasthesa_end'] = date('h:i A', strtotime($operation_form['anasthesa_end']));
        $selectArray = explode(',', $operation_form['surgeon']);
        $operation_form['surgeon'] = $selectArray;
        $selectArray = explode(',', $operation_form['assistant']);
        $operation_form['assistant'] = $selectArray;
        $selectArray = explode(',', $operation_form['anasthesiologist']);
        $operation_form['anasthesiologist'] = $selectArray;
        $selectArray = explode(',', $operation_form['pre_diagnoses']);
        $operation_form['pre_diagnoses'] = $selectArray;
        $selectArray = explode(',', $operation_form['operations']);
        $operation_form['operations'] = $selectArray;

        $this->smarty->assign('operation_form', $operation_form);

        $this->smarty->assign('patientId', $operation_form['patient_id']);

        $doctors = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                where awrole.is_doctor =  1 and deleted != 1  ');
        $this->smarty->assign('doctors', $doctors);

        $anaesthetists = R::getAll("select * from awusers where role_id = 7");
        $this->smarty->assign('anaesthetists', $anaesthetists);

        $preDiags = R::getAll('select * from operationotherth');
        $this->smarty->assign('preDiags', $preDiags);

        $operations = R::getAll('select * from  phpastsurgicaloperation where del = 0');
        $this->smarty->assign('operations', $operations);

        $postDiags = R::getAll('select * from post_diagnoses where deleted = 0 ');
        $this->smarty->assign('postDiags', $postDiags);
    }

    function patientInfo($patientId, $visitId) {
        $patient = R::load('patients', $patientId);
        $programesetting = R::findOne('programesetting');
        $visit = R::load('visits', $visitId);

        $name = '';
        $sex = '';
        $for = 0;

        if ($programesetting->system_lang == 2) {
            $date = $patient->dateofbirth;
            $name = $patient->wifename;
            if ($patient->gender == 1) {
                $sex = 'Male';
            } else {
                $sex = 'Female';
            }
        } else {
            if (count($visit) > 0) {
                if ($visit->for_husband == 1) {
                    $for = 1;
                    $date = $patient->husbanddateofbirth;
                    $name = $patient->husdandname;
                    $sex = 'Male';
                } else if ($visit->for_husband == 2) {
                    $for = 2;
                    $child = R::load('patients_childs', $visit->child);
                    $date = $child->birth_date;
                    if ($child->gender == 1) {
                        $sex = 'Male';
                        if (is_null($child->child_name) || $child->child_name == '') {
                            $name = 'الطفل / ' . $patient->wifename;
                        } else {
                            $name = $child->child_name . '  /  ' . $patient->wifename;
                        }
                    } else {
                        $sex = 'Female';
                        if (is_null($child->child_name) || $child->child_name == '') {
                            $name = 'الطفلة / ' . $patient->wifename;
                        } else {
                            $name = $child->child_name . '  /  ' . $patient->wifename;
                        }
                    }
                } else {
                    $date = $patient->dateofbirth;
                    $name = $patient->wifename;
                    $sex = 'Female';
                }
            } else {
                $date = $patient->dateofbirth;
                $name = $patient->wifename;
                $sex = 'Female';
            }
        }


        if (count($visit) > 0) {
            $role = R::load('awrole', $visit->for_department);
            $this->smarty->assign('deptName', $role->name);
            if ($visit->res_room_no > 0) {
                $room = R::load('residence_rooms', $visit->res_room_no);
                $this->smarty->assign('roomNo', $room->name);
            }

            $this->smarty->assign('bedNo', $visit->bed_no);
            $this->smarty->assign('visitDate', $visit->visitdate);
        }

        if ($date == '0000-00-00' || is_null($date) || $date == '') {
            $age = 0;
        } else {
            $dateWife = new DateTime($date);
            $today1 = new DateTime(date('Y-m-d'));
            $interval = $today1->diff($dateWife);
            if ($interval->y > 0) {
                $age = $interval->y . ' Years';
            } elseif ($interval->m > 0) {
                $age = $interval->m . ' Months';
            } elseif ($interval->d >= 0) {
                $age = 1 + $interval->d . ' Days';
            }
        }

        $this->smarty->assign('statusNo', $patient->statusno);
        $this->smarty->assign('name', $name);
        $this->smarty->assign('sex', $sex);
        $this->smarty->assign('age', $age);
    }

    function loadOperationPrint($operation_form_id) {

        $operation_form = R::getRow('select operation_form.*    from operation_form  where id = ' . $operation_form_id);
        if ($operation_form['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($operation_form['patient_id']);
            if ($visit_id > 0) {
                R::exec(' update operation_form set visit_id = ? where id = ?  ', [$visit_id, $operation_form_id]);
                $operation_form['visit_id'] = $visit_id;
            }
        }

        $this->patientInfo($operation_form['patient_id'], $operation_form['visit_id']);
        $operation_form['anasthesa_start'] = date('h:i a', strtotime($operation_form['anasthesa_start']));
        $operation_form['anasthesa_end'] = date('h:i a', strtotime($operation_form['anasthesa_end']));
        if (!empty($operation_form['op_date']) && trim($operation_form['op_date']) != '' && $operation_form['op_date'] != null) {
            $operation_form['op_date'] = date('Y/m/d', strtotime($operation_form['op_date']));
        }


        $operation_form['surgeon'] = $this->multiValues($operation_form['surgeon'], 'awusers', 'user_id');
        $operation_form['assistant'] = $this->multiValues($operation_form['assistant'], 'awusers', 'user_id');
        $operation_form['anasthesiologist'] = $this->multiValues($operation_form['anasthesiologist'], 'awusers', 'user_id');

        $operation_form['pre_diagnoses'] = $this->multiValues($operation_form['pre_diagnoses'], 'operationotherth', 'id');
        $operation_form['pre_diagnoses'] = $this->noteValues(
                $operation_form['pre_diagnoses'],
                $operation_form['pre_diagnoses_note']
        );

        $operation_form['operations'] = $this->multiValues($operation_form['operations'], 'phpastsurgicaloperation', 'id');
        $operation_form['operations'] = $this->noteValues(
                $operation_form['operations'],
                $operation_form['operations_note']
        );

        $operation_form['post_diagnoses'] = $this->multiValues($operation_form['post_diagnoses'], 'post_diagnoses', 'id');
        $operation_form['post_diagnoses'] = $this->noteValues(
                $operation_form['post_diagnoses'],
                $operation_form['post_diagnoses_note']
        );

        $this->smarty->assign('operation_form', $operation_form);
    }

    function multiValues($idsText, $tableName, $colName) {
        $v = 1;
        $values = ' ';
        $selectArray = explode(',', $idsText);

        foreach ($selectArray as $data) {
            $obj = R::findOne($tableName, ' ' . $colName . ' = ?  ', [$data]);
            if ($obj->deleted < 1) {
                if ($v > 1) {
                    $values .= ' , ';
                }

                $values .= $obj->name;

                $v++;
            }
        }

        return $values;
    }

    function noteValues($values, $note) {
        if (!empty($note) && trim($note) != '' && $note != null) {
            $values .= ' ( ' . $note . ' )';
        }

        return $values;
    }

    ###########################################################

    public function exit_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $exit_summary = R::getAll('select exit_summary.id  , exit_summary.ad_date   , exit_summary.dis_date  
                            from  exit_summary 
                            where exit_summary.deleted != 1 and exit_summary.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('exit_summary', $exit_summary);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/exit_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function exit_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $exit_summary = R::findOne('exit_summary', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($exit_summary) <= 0) {
            $exit_summary = R::xdispense('exit_summary');
            $exit_summary->patient_id = $patientid;
            $exit_summary->ad_date = $this->today;
            $exit_summary->dis_date = $this->today;
            $exit_summary->completed = 0;
            $exit_summary->user_id = $_SESSION['user_id'];
            $exit_summary_id = R::store($exit_summary);
        } else {
            $exit_summary_id = $exit_summary->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'exit_summary');
        $this->smarty->assign('show', 'exit_show');

        $this->loadExit($exit_summary_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/exit_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function exit_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $exit_summary_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadExit($exit_summary_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/exit_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function exit_print() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $exit_summary_id = filter_input(INPUT_POST, "id");
        $this->loadExitPrint($exit_summary_id);
        $this->smarty->assign('date', date("Y-m-d"));
        $this->smarty->display('ivf_reports/exit_print.html');
    }

    function loadExitPrint($exit_summary_id) {
        $exit_summary = R::getRow('select exit_summary.*   , awusers.name as visitDoctor      
                from exit_summary 
                 left join     visits                                     on   exit_summary.visit_id   =  visits.id    
                 left join   awusers                                on   visits.for_doctor   =  awusers.user_id      
                where exit_summary.id = ' . $exit_summary_id);

        if ($exit_summary['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($exit_summary['patient_id']);
            R::exec(' update exit_summary set visit_id = ?  where id = ?  ', [$visit_id, $exit_summary_id]);
        }

        $this->patientInfo($exit_summary['patient_id'], $exit_summary['visit_id']);

        if (!empty($exit_summary['ad_date']) && trim($exit_summary['ad_date']) != '' && $exit_summary['ad_date'] != null) {
            $exit_summary['ad_date'] = date('Y/m/d', strtotime($exit_summary['ad_date']));
        }

        if (!empty($exit_summary['dis_date']) && trim($exit_summary['dis_date']) != '' && $exit_summary['dis_date'] != null) {
            $exit_summary['dis_date'] = date('Y/m/d', strtotime($exit_summary['dis_date']));
        }

        $exit_summary['discharge'] = $this->multiValues($exit_summary['discharge'], 'discharge', 'id');
        $exit_summary['trans_to'] = $this->multiValues($exit_summary['trans_to'], 'trans_to', 'id');
        $exit_summary['followup_app'] = $this->multiValues($exit_summary['followup_app'], 'followup_app', 'id');
        $exit_summary['dis_physician'] = $this->multiValues($exit_summary['dis_physician'], 'awusers', 'user_id');

        $this->smarty->assign('exit_summary', $exit_summary);
    }

    function loadExit($exit_summary_id) {
        $exit_summary = R::getRow('select exit_summary.*   , awusers.name as visitDoctor      
                from exit_summary 
                 left join     visits                                     on   exit_summary.visit_id   =  visits.id    
                 left join   awusers                                on   visits.for_doctor   =  awusers.user_id      
                where exit_summary.id = ' . $exit_summary_id);

        if ($exit_summary['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($exit_summary['patient_id']);
            R::exec(' update exit_summary set visit_id = ?  where id = ?  ', [$visit_id, $exit_summary_id]);
        }

        if (!empty($exit_summary['ad_date']) && trim($exit_summary['ad_date']) != '' && $exit_summary['ad_date'] != null) {
            $exit_summary['ad_date'] = date('Y/m/d', strtotime($exit_summary['ad_date']));
        }

        if (!empty($exit_summary['dis_date']) && trim($exit_summary['dis_date']) != '' && $exit_summary['dis_date'] != null) {
            $exit_summary['dis_date'] = date('Y/m/d', strtotime($exit_summary['dis_date']));
        }




        $this->smarty->assign('exit_summary', $exit_summary);
        $this->smarty->assign('patientId', $exit_summary['patient_id']);

        $discharges = R::getAll('select * from discharge where deleted = 0 ');
        $this->smarty->assign('discharges', $discharges);

        $trans_tos = R::getAll('select * from trans_to where deleted = 0 ');
        $this->smarty->assign('trans_tos', $trans_tos);

        $followup_apps = R::getAll('select * from followup_app where deleted = 0 ');
        $this->smarty->assign('followup_apps', $followup_apps);

        $doctors = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                where awrole.is_doctor =  1 and deleted != 1  ');
        $this->smarty->assign('doctors', $doctors);
    }

    ###########################################################

    public function pre_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $pre_anaesthetic = R::getAll('select pre_anaesthetic.id  , visits.visitdate
                            from  pre_anaesthetic 
                             left join     visits                                     on   pre_anaesthetic.visit_id   =  visits.id    
                            where pre_anaesthetic.deleted != 1 and pre_anaesthetic.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('pre_anaesthetic', $pre_anaesthetic);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/pre_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function pre_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $pre_anaesthetic = R::findOne('pre_anaesthetic', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($pre_anaesthetic) <= 0) {
            $pre_anaesthetic = R::xdispense('pre_anaesthetic');
            $pre_anaesthetic->patient_id = $patientid;
            $pre_anaesthetic->completed = 0;
            $pre_anaesthetic->user_id = $_SESSION['user_id'];
            $pre_anaesthetic_id = R::store($pre_anaesthetic);
        } else {
            $pre_anaesthetic_id = $pre_anaesthetic->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'pre_anaesthetic');
        $this->smarty->assign('show', 'pre_show');

        $this->loadPre($pre_anaesthetic_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/pre_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadPre($pre_anaesthetic_id) {
        $pre_anaesthetic = R::getRow('select pre_anaesthetic.*    , visits.visitdate 
                from pre_anaesthetic 
                 left join     visits                                     on   pre_anaesthetic.visit_id   =  visits.id    
                where pre_anaesthetic.id = ' . $pre_anaesthetic_id);

        if ($pre_anaesthetic['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($pre_anaesthetic['patient_id']);
            R::exec(' update pre_anaesthetic set visit_id = ?  where id = ?  ', [$visit_id, $pre_anaesthetic_id]);
        }

        if ($pre_anaesthetic['visit_id'] > 0) {
            $date = $pre_anaesthetic['visitdate'];
        } else {
            $date = date('Y-m-d');
        }

        $this->exmination($pre_anaesthetic['patient_id'], $date);
        $this->operation($pre_anaesthetic['patient_id'], $pre_anaesthetic['visit_id']);

        $selectArray = explode(',', $pre_anaesthetic['pre_history']);
        $pre_anaesthetic['pre_history'] = $selectArray;

        $this->smarty->assign('pre_anaesthetic', $pre_anaesthetic);
        $this->smarty->assign('patientId', $pre_anaesthetic['patient_id']);

        $pre_history = R::getAll('select * from pre_history where deleted = 0 ');
        $this->smarty->assign('pre_history', $pre_history);

        $drug_therapy = R::getAll('select * from drug_therapy where deleted = 0 ');
        $this->smarty->assign('drug_therapy', $drug_therapy);
        $this->smarty->assign('drug_therapyCount', count($drug_therapy));
    }

    function exmination($patient_id, $date) {
        $exmination = R::findOne('examination', 'del = ? and patientid = ?  and  examinationdate  <= ? 
            order  by examinationdate desc, id desc', [0, $patient_id, $date]);

        $ProgramesettingData = R::findone('programesetting');

        if ($ProgramesettingData->head != 1) {
            $examinationhead = R::load('examinationhead', $exmination->headandneck);
            $exmination->headandneck = $examinationhead->name;
        }

        if ($ProgramesettingData->chest != 1) {
            $examinationchest = R::load('examinationchest', $exmination->chestandheart);
            $exmination->chestandheart = $examinationchest->name;
        }

        if ($ProgramesettingData->abdomen != 1) {
            $examinationabdomen = R::load('examinationabdomen', $exmination->abdomen);
            $exmination->abdomen = $examinationabdomen->name;
        }

        if ($ProgramesettingData->pelvis != 1) {
            $examinationpelvis = R::load('examinationpelvis', $exmination->pelvis);
            $exmination->pelvis = $examinationpelvis->name;
        }

        if ($ProgramesettingData->extremitis != 1) {
            $examinationextremitis = R::load('examinationextremitis', $exmination->extremitis);
            $exmination->extremitis = $examinationextremitis->name;
        }


        $this->smarty->assign('exmination', $exmination);
    }

    function operation($patient_id, $visit_id) {
        $operation_form = R::findOne('operation_form', 'patient_id = ? and completed = 1
              and  visit_id = ? order by id desc  ', [$patient_id, $visit_id]);

        $operation_form['pre_diagnoses'] = $this->multiValues($operation_form['pre_diagnoses'], 'operationotherth', 'id');
        $operation_form['pre_diagnoses'] = $this->noteValues(
                $operation_form['pre_diagnoses'],
                $operation_form['pre_diagnoses_note']
        );

        $operation_form['operations'] = $this->multiValues($operation_form['operations'], 'phpastsurgicaloperation', 'id');
        $operation_form['operations'] = $this->noteValues(
                $operation_form['operations'],
                $operation_form['operations_note']
        );

        $this->smarty->assign('pre_diagnoses', $operation_form['pre_diagnoses']);
        $this->smarty->assign('operations', $operation_form['operations']);
        $this->smarty->assign('operation_category', $operation_form['category']);
    }

    function DrugTherapyAdd() {
        $id = filter_input(INPUT_POST, "id");
        $itr = filter_input(INPUT_POST, "itr");
        if ($id > 0) {
            $drug_therapy = R::xdispense('drug_therapy');
            $drug_therapy->pre_anaesthetic_id = $id;
            $drug_therapy->id = R::store($drug_therapy);
            $this->smarty->assign('drug', $drug_therapy);
            $this->smarty->assign('m', $itr);
            $this->smarty->display('ivf_reports/drug_therapy.html');
        }
    }

    public function pre_print() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $pre_anaesthetic_id = filter_input(INPUT_POST, "id");
        $this->loadPrePrint($pre_anaesthetic_id);
        $this->smarty->assign('date', date("Y-m-d"));
        $this->smarty->display('ivf_reports/pre_print.html');
    }

    function loadPrePrint($pre_anaesthetic_id) {
        $pre_anaesthetic = R::getRow('select pre_anaesthetic.*    , visits.visitdate 
                from pre_anaesthetic 
                 left join     visits                                     on   pre_anaesthetic.visit_id   =  visits.id    
                where pre_anaesthetic.id = ' . $pre_anaesthetic_id);

        if ($pre_anaesthetic['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($pre_anaesthetic['patient_id']);
            R::exec(' update pre_anaesthetic set visit_id = ?  where id = ?  ', [$visit_id, $pre_anaesthetic_id]);
        }

        $this->patientInfo($pre_anaesthetic['patient_id'], $pre_anaesthetic['visit_id']);

        if ($pre_anaesthetic['visit_id'] > 0) {
            $date = $pre_anaesthetic['visitdate'];
        } else {
            $date = date('Y-m-d');
        }

        $this->exmination($pre_anaesthetic['patient_id'], $date);
        $this->operation($pre_anaesthetic['patient_id'], $pre_anaesthetic['visit_id']);

        $pre_anaesthetic['pre_history'] = $this->multiValues($pre_anaesthetic['pre_history'], 'pre_history', 'id');

        $this->smarty->assign('pre_anaesthetic', $pre_anaesthetic);

        $drug_therapy = R::getAll('select * from drug_therapy where deleted = 0 ');
        $this->smarty->assign('drug_therapy', $drug_therapy);
        $this->smarty->assign('drug_therapyCount', count($drug_therapy));
    }

    public function pre_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $pre_anaesthetic_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadPre($pre_anaesthetic_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/pre_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    ###########################################################

    public function intra_show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }


        $intra_anaesthetic = R::getAll('select intra_anaesthetic.id   , visits.visitdate
                            from  intra_anaesthetic 
                              left join     visits                                     on   intra_anaesthetic.visit_id   =  visits.id    
                            where intra_anaesthetic.deleted != 1 and intra_anaesthetic.completed =  1 
                            and patient_id = ' . $patientid);
        $this->smarty->assign('intra_anaesthetic', $intra_anaesthetic);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }

        $this->smarty->display('ivf_reports/intra_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function intra_add() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

        $intra_anaesthetic = R::findOne('intra_anaesthetic', 'patient_id = ? and completed = 0', [$patientid]);
        if (count($intra_anaesthetic) <= 0) {
            $intra_anaesthetic = R::xdispense('intra_anaesthetic');
            $intra_anaesthetic->patient_id = $patientid;
            $intra_anaesthetic->completed = 0;
            $intra_anaesthetic->user_id = $_SESSION['user_id'];
            $intra_anaesthetic_id = R::store($intra_anaesthetic);
        } else {
            $intra_anaesthetic_id = $intra_anaesthetic->id;
        }

        $this->smarty->assign('is_add', 1);
        $this->smarty->assign('tableName', 'intra_anaesthetic');
        $this->smarty->assign('show', 'intra_show');

        $this->loadIntra($intra_anaesthetic_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/intra_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadIntra($intra_anaesthetic_id) {
        $intra_anaesthetic = R::getRow('select intra_anaesthetic.*    , visits.visitdate 
                from intra_anaesthetic 
                 left join     visits                                     on   intra_anaesthetic.visit_id   =  visits.id    
                where intra_anaesthetic.id = ' . $intra_anaesthetic_id);

        if ($intra_anaesthetic['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($intra_anaesthetic['patient_id']);
            R::exec(' update intra_anaesthetic set visit_id = ?  where id = ?  ', [$visit_id, $intra_anaesthetic_id]);
        }

        if ($intra_anaesthetic['visit_id'] > 0) {
            $date = $intra_anaesthetic['visitdate'];
        } else {
            $date = date('Y-m-d');
        }

        $this->operation($intra_anaesthetic['patient_id'], $intra_anaesthetic['visit_id']);
        $this->operation($intra_anaesthetic['patient_id'], $intra_anaesthetic['visit_id']);

        $this->smarty->assign('intra_anaesthetic', $intra_anaesthetic);
        $this->smarty->assign('patientId', $intra_anaesthetic['patient_id']);

        $tables = array(
            "posture", "introduction", "maintenance", "ventilation", "endotracheal_tube", "mention", "no_title", "m_relaxants", "antidotes", "complications", "infusions"
        );

        foreach ($tables as $table) {
            $records = R::getAll('select * from ' . $table . ' where deleted = 0 ');
            $this->smarty->assign($table, $records);
        }
    }

    public function intra_print() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $intra_anaesthetic_id = filter_input(INPUT_POST, "id");
        $this->loadIntraPrint($intra_anaesthetic_id);
        $this->smarty->assign('date', date("Y-m-d"));
        $this->smarty->display('ivf_reports/intra_print.html');
    }

    function loadIntraPrint($intra_anaesthetic_id) {
        $intra_anaesthetic = R::getRow('select intra_anaesthetic.*    , visits.visitdate 
                from intra_anaesthetic 
                 left join     visits                                     on   intra_anaesthetic.visit_id   =  visits.id    
                where intra_anaesthetic.id = ' . $intra_anaesthetic_id);

        if ($intra_anaesthetic['visit_id'] == 0) {
            $visit_id = $this->patientLastVisit($intra_anaesthetic['patient_id']);
            R::exec(' update intra_anaesthetic set visit_id = ?  where id = ?  ', [$visit_id, $intra_anaesthetic_id]);
        }

        $this->patientInfo($intra_anaesthetic['patient_id'], $intra_anaesthetic['visit_id']);

        if ($intra_anaesthetic['visit_id'] > 0) {
            $date = $intra_anaesthetic['visitdate'];
        } else {
            $date = date('Y-m-d');
        }

        $this->operation($intra_anaesthetic['patient_id'], $intra_anaesthetic['visit_id']);
        $tables = array(
            "posture", "introduction", "maintenance", "ventilation", "endotracheal_tube", "mention", "no_title", "m_relaxants", "antidotes", "complications", "infusions"
        );

        foreach ($tables as $table) {
            $intra_anaesthetic[$table] = $this->multiValues($intra_anaesthetic[$table], $table, 'id');
        }
        $intra_anaesthetic['pre_history'] = $this->multiValues($intra_anaesthetic['pre_history'], 'pre_history', 'id');

        $this->smarty->assign('intra_anaesthetic', $intra_anaesthetic);
    }

    public function intra_edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $intra_anaesthetic_id = filter_input(INPUT_GET, "id");
        $patientid = filter_input(INPUT_GET, "patientid");

        $this->loadIntra($intra_anaesthetic_id);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($patientid) {
            patientdata::patientdatashow($this->smarty, $this->hosturl);
        }
        $this->smarty->display('ivf_reports/intra_add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    ###########################################################

    public function ivf_cases() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //here will load the menu show
        //R::debug(true);

        $today = date("Y/m/d");
        $this->smarty->assign('today', date('Y/m/d', strtotime($today)));

        $py_all_doc = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                where awrole.is_doctor =  1 ');
        $this->smarty->assign('py_all_doc', $py_all_doc);

        $users = R::getAll('select * from awusers where deleted != 1 ');
        $this->smarty->assign('users', $users);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('ivf_reports/ivf_cases.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function ivf_cases_search() {
        $fdate = filter_input(INPUT_POST, 'fdate');
        $todate = filter_input(INPUT_POST, 'todate');
        $wId = filter_input(INPUT_POST, 'value');
        $hId = filter_input(INPUT_POST, 'hvalue');
        $userId = filter_input(INPUT_POST, 'userId');
        $drId = filter_input(INPUT_POST, 'referDrId');
        $print = filter_input(INPUT_POST, 'print');

        $patientId = 0;
        if ($wId > 0 || $hId > 0) {
            if ($hId > 0) {
                $patientId = $hId;
            } else {
                $patientId = $wId;
            }
        }

        $this->ivf_casesCommonSearch($fdate, $todate, $patientId, $userId, $drId);
        if ($print == 1) {
            //      $this->smarty->display('adddevices/rfc_report_print.html');
        } else {
            $this->smarty->display('ivf_reports/ivf_cases_search.html');
        }
    }

    public function ivf_casesCommonSearch($fromDate, $toDate, $patientId, $userId, $drId) {
        $ext = '';

        if (!empty($userId) && $userId > 0) {
            $ext .= ' and ivf_report.user_id =   ' . $userId;
        }

        if (!empty($patientId) && $patientId > 0) {
            $ext .= ' and ivf_report.patient_id = ' . $patientId;
        }

        if (!empty($drId) && $drId > 0) {
            $ext .= ' and ivf_report.doctor1 = ' . $drId;
        }

        $sql = 'select    ivf_report.id ,  awusers.name as user_name     , patients.wifename   , patients.husdandname     
             , patients.statusno    ,  ivf_report.trig_date  , ref.name as doctor  ,  ivf_report.patient_id
                       from    ivf_report    
                      join     patients                                     on   ivf_report.patient_id   =  patients.id     
                    left join   awusers                          on   ivf_report.user_id   =  awusers.user_id      
                      left join   awusers  ref                          on   ivf_report.doctor1   =  ref.user_id      
                       
                  where ivf_report.deleted  != 1     and  ivf_report.completed  =  1    ' . $ext . '     
                  and ivf_report.trig_date between  ? and ?    ';

        $result = R::getAll($sql, [$fromDate, $toDate]);
        $this->smarty->assign('result', $result);
    }

    ###########################################################

    public function dateDayName() {
        $date = filter_input(INPUT_POST, 'trigDate');
        $dayName = $this->getDayNameFnAr($date);
        echo $dayName;
    }

    private function getDayNameFnAr($date) {
        $timestamp = strtotime($date);

        $day = date('w', $timestamp);

        switch ($day) {
            case 0:
                $name = 'الأحد  ';
                break;
            case 1:
                $name = ' الإثنين';
                break;
            case 2:
                $name = ' الثلاثاء';
                break;
            case 3:
                $name = 'الأربعاء ';
                break;
            case 4:
                $name = 'الخميس  ';
                break;
            case 5:
                $name = 'الجمعة ';
                break;
            case 6:
                $name = 'السبت ';
                break;
        }

        return $name;
    }

    ###########################################################

    // at the end of class call
    public function __destruct() {
        //colse connection
        R::close();
    }
}
