<?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 = 'ovumpickupembryotrans';
        $this->shcontrollname = 'operations';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);


//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] = 'operations'; //controller name or tab name
        $active[1] = 'ovumpickup embryotrans'; //controller name
// do name  // switch($do)
        switch ($acty) {
            case '':
                $active[2] = 'ovumpickupembryotransadd';
                break;
            case 'show':
                $active[2] = 'ovumpickupembryotransshow';
                break;
            default :
                $active[2] = 'ovumpickupembryotransshow';
                break;
        }
        $this->active = $active;


        //so I can use underscore in table's name
        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("pres_common.php");

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

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

    public function index() {

//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();
        } else {

            $this->smarty->assign('patientId', $patientid);

//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);
            }
            //show operations//

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

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

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

            $showelemsovm = R::getAll("select* from ovumpickup WHERE patientid = $patientid order by id desc");
            $this->smarty->assign('showelemsovm', $showelemsovm);

            //mine
            $showelemsovm_mine = R::getAll('SELECT embryologyreport.id as embryologyreport_id,embryologyreport.clinician_id,
            embryologyreport.patient_id as patientId,awusers.name as clinician_name,
            patients.wifename as wifename, embryologyreport.date as created_date from embryologyreport
             LEFT JOIN  awusers ON embryologyreport.clinician_id =awusers.user_id
              LEFT JOIN  patients ON embryologyreport.patient_id =patients.id where embryologyreport.patient_id=' . $patientid . ' order by embryologyreport_id desc
         ');
            $this->smarty->assign('showelemsovm_mine', $showelemsovm_mine);


            $showElems_emb_mine = R::getAll('SELECT embryoslab.id as embryoslab_id,embryoslab.date,awusers.name as referred_dr_name from embryoslab
             LEFT JOIN  awusers ON embryoslab.referred_dr_id =awusers.user_id
              LEFT JOIN  patients ON embryoslab.patient_id =patients.id where embryoslab.not_confirm = 1 and embryoslab.radiotype = 1 AND embryoslab.patient_id=' . $patientid . ' order by embryoslab_id desc
         ');
            $new_showElems_emb_mine = array();
            foreach ($showElems_emb_mine as $one) {
                $transfer = R::findOne("embryotransfer", "embryoslab_id=?", [$one['embryoslab_id']]);
                $one['emp_th_type'] = $transfer->emp_th_type;
                array_push($new_showElems_emb_mine, $one);
            }
            $this->smarty->assign('showElems_emb_mine', $new_showElems_emb_mine);


            $showelemsemt = R::getAll("select* from embryotransferovum WHERE patientid = $patientid order by id asc");
            $this->smarty->assign('showelemsemt', $showelemsemt);


            ############## follow up #######
            $followUps = R::getAll('select followup_operation.id ,  operationotherth.name as  operationName 
                  ,    followup_operation.op_date
                from followup_operation   
                left join operationotherth   on operationotherth.id = followup_operation.operationid   
                where followup_operation.del != 1    and followup_operation.done = 1 and patientid = ' . $patientid);

            $this->smarty->assign('followUps', $followUps);
            ################
            $programesetting = R::findOne('programesetting');
            $this->smarty->assign('programesetting', $programesetting);
            /////////////
            $this->smarty->display('ovumpickup_embryotrans/show.html');
            leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
            footer::footershow($this->smarty, $this->hosturl);
        }
    }

//add ovum pick up //
    public function addOvum() {

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

        //vars here
        $consultant = filter_input(INPUT_POST, 'consultant');
        $date = filter_input(INPUT_POST, 'date');
        $anaesthetist = filter_input(INPUT_POST, 'anaesthetist');
        $nurse = filter_input(INPUT_POST, 'nurse');
        $operation = filter_input(INPUT_POST, 'operation');
        $postoperative_treatment = filter_input(INPUT_POST, 'postoperative_treatment');
        $complications = filter_input(INPUT_POST, 'complications');

        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            //here the add
            $ovumpickup = R::dispense('ovumpickup');

            $ovumpickup->patientid = $patientid;
            $ovumpickup->date = $date;
            $ovumpickup->consultant = $consultant;
            $ovumpickup->anaesthetist = $anaesthetist;
            $ovumpickup->nurse = $nurse;
            $ovumpickup->operation = $operation;
            $ovumpickup->postoperative = $postoperative_treatment;
            $ovumpickup->complications = $complications;


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

//add embryo transfer//
    public function addEmbryoTransfer() {

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

        //vars here
        $consultant = filter_input(INPUT_POST, 'consultant');
        $day = filter_input(INPUT_POST, 'day');
        $nurse = filter_input(INPUT_POST, 'nurse');
        $embryologist = filter_input(INPUT_POST, 'embryologist');
        $no_of_embryos = filter_input(INPUT_POST, 'no_of_embryos');
        $quality = filter_input(INPUT_POST, 'quality');
        $notes = filter_input(INPUT_POST, 'notes');

        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            //here the add
            $embryotransferovum = R::dispense('embryotransferovum');

            $embryotransferovum->patientid = $patientid;
            $embryotransferovum->date = date('Y-m-d h:i:s');
            ;
            $embryotransferovum->day = $day;
            $embryotransferovum->consultant = $consultant;
            $embryotransferovum->nurse = $nurse;
            $embryotransferovum->embryologist = $embryologist;
            $embryotransferovum->no_of_embryos = $no_of_embryos;
            $embryotransferovum->quality = $quality;
            $embryotransferovum->notes = $notes;

            try {
                $id = R::store($embryotransferovum);
                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) {
                header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
            }
        }
    }

//display ovum form//
    public function ovumPickUp() {

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

        $patientid = filter_input(INPUT_GET, "patientid");
//load all declerations here
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            $this->smarty->assign('patientId', $patientid);

//call other class with other content

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

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

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

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

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

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

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

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

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

            $operation_other_th = R::findAll('operationotherth');
            $this->smarty->assign('operation_other_th', $operation_other_th);


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

            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('ovumpickup_embryotrans/add_ovum_pickup.html');
            leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
            footer::footershow($this->smarty, $this->hosturl);
        }
    }

    function addnewoperation() {
        //vars here
        $name = filter_input(INPUT_POST, 'selectedoperation');
        $inline = filter_input(INPUT_POST, 'inline');
        $selectid = filter_input(INPUT_POST, 'id');

        ### insert into table
        $newtable = R::dispense('operationotherth');
        $newtable->name = $name;
        $insertid = R::store($newtable);

        if ($inline == 1) {
            $mydata = R::load('followup_operation', $selectid);
            $mydata->operationid = $insertid;
            R::store($mydata);
        }

        echo $insertid;
    }

// display embryo tranfer form//
    public function embryoTransfer() {

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

        $patientid = filter_input(INPUT_GET, "patientid");
//load all declerations here

        $this->smarty->assign('patientId', $patientid);
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
//call other class with other content


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

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

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

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


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

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

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

            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('ovumpickup_embryotrans/add_embryo_transfer.html');
            leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
            footer::footershow($this->smarty, $this->hosturl);
        }
    }

    public function editEmbryoTransferMine() {

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

        $embryoslab_id = filter_input(INPUT_GET, "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();
        }
        //referred doctors
        $ref_dr_id = R::load(patients, $patientid);
        if (!empty($ref_dr_id->refer_doctor)) {
            $ref_dr = R::getAll("select* from awusers where user_id=$ref_dr_id->refer_doctor");
            $this->smarty->assign('ref_dr', $ref_dr[0]);
        } else {
            $this->smarty->assign('ref_dr', "لايوجد");
        }


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

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

        $embryoslab = R::getAll("select* from embryoslab where id=$embryoslab_id");
//        print_r($embryoslab);
        $this->smarty->assign('updatedate', $embryoslab[0]);
//        $embryoslab_id = $embryoslab[0]["id"];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


        $scoring = R::findAll("embryoscoring", "embryoslab_id=$embryoslab_id");
        $this->smarty->assign('scoring', $scoring);

        $count_scoring = count($scoring);
        $this->smarty->assign('count_scoring', $count_scoring);


        $transfer = R::findOne("embryotransfer", "embryoslab_id=$embryoslab_id");
        $this->smarty->assign('transfer', $transfer);

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

        $count_embryofreezing = count($embryofreezing);
        $this->smarty->assign('count_embryofreezing', $count_embryofreezing);


        $day_array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31);
        $this->smarty->assign('day_array', $day_array);

        $et_day_array = array(1, 2, 3, 4, 5, 6);
        $this->smarty->assign('et_day_array', $et_day_array);
        //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('ovumpickup_embryotrans/editEmbryoTransferMine.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateEmbryoTransferMine() {
        $add_bttn = filter_input(INPUT_POST, 'add_bttn');
        $patientid = filter_input(INPUT_GET, "patientid");
        if ($add_bttn) {
            $embryoslab = R::dispense('embryoslab');
            $date_transer_embryo = filter_input(INPUT_POST, 'date_transer_embryo');
            $embryoslab->date = $date_transer_embryo;
            $embryoslab->patient_id = $patientid;
            $embryoslab->referred_dr_id = $_SESSION['user_id'];
            $embryoslab->radiotype = 1;
            $embryoslab = R::store($embryoslab);
        }

        //embryoslab table

        $notes = filter_input(INPUT_POST, "notes");
        $nurse = filter_input(INPUT_POST, "nurse");
        $tablename = 'embryotransfer';

        $row_id = filter_input(INPUT_POST, 'transfer_embryo_id');

        if ($add_bttn) {
            
        } else {
            $embryodata = R::findOne($tablename, 'embryoslab_id=' . $row_id . '');
            $id = $embryodata->id;

            $embryoslab = R::load('embryoslab', $embryodata->embryoslab_id);
            $date_transer_embryo = filter_input(INPUT_POST, 'date_transer_embryo');
            $embryoslab->date = $date_transer_embryo;
        }

        $embryo = R::load($tablename, $id);
        $embryo->nurse_id = $nurse;
        $embryo->notes = $notes;

        if ($add_bttn) {
            
        }

        $transfer_clinician_id = filter_input(INPUT_POST, 'transfer_clinician_id');
        $transfer_embryologist_id = filter_input(INPUT_POST, 'transfer_embryologist_id');
        $transfer_day_id = filter_input(INPUT_POST, 'transfer_day_id');
        $emp_th_type = filter_input(INPUT_POST, 'emp_th_type');
        $embryo->clinician_id = $transfer_clinician_id;
        $embryo->embryologist_id = $transfer_embryologist_id;
        $embryo->et_day = $transfer_day_id;
        $embryo->embryoslab_id = $embryoslab;
        $embryo->emp_th_type = $emp_th_type;



        try {
            $result = R::store($embryo);
            if (!empty($patientid)) {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index&patientid=' . $patientid);
            } else {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index');
            }
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

// show operations //
    public function show() {

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

        $patientid = filter_input(INPUT_GET, "patientid");
//load all declerations here

        $this->smarty->assign('patientId', $patientid);

//call other class with other content
        $showelemsovm = R::getAll("select * from ovumpickup WHERE patientid = $patientid order by id asc");
        $this->smarty->assign('showelemsovm', $showelemsovm);


        $showelemsemt = R::getAll("select * from embryotransferovum WHERE patientid = $patientid order by id asc");
        $this->smarty->assign('showelemsemt', $showelemsemt);

        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('ovumpickup_embryotrans/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function editOvmMine() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        //autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //get id for item
        $id = filter_input(INPUT_GET, 'id');
        $patientid = filter_input(INPUT_GET, "patientid");
        //load all here
        $editElement = R::load('embryologyreport', $id);
        $this->smarty->assign('editElement', $editElement);
//        print_r($editElement);
        $this->smarty->assign('patientId', $patientid);


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

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

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

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

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

        //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('ovumpickup_embryotrans/edit_mine.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateitMine() {

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


        $add_bttn = filter_input(INPUT_POST, 'add_bttn');


        //vars here
        $patientid = filter_input(INPUT_GET, "patientid");
        $nurse = filter_input(INPUT_POST, 'nurse');
        $anaesthetist = filter_input(INPUT_POST, 'anaesthetist');
        $ut_cx = filter_input(INPUT_POST, 'ut_cx');
        $avf_rvf = filter_input(INPUT_POST, 'avf_rvf');
        $easy_difficult = filter_input(INPUT_POST, 'easy_difficult');
        $postoperative = filter_input(INPUT_POST, 'postoperative');
        $complications = filter_input(INPUT_POST, 'complications');
        $notes = filter_input(INPUT_POST, 'notes');
        $id = filter_input(INPUT_POST, 'id');

        $this->smarty->assign('patientId', $patientid);


        //here the update
        $report = R::load('embryologyreport', $id);

        $report->patient_id = $patientid;
        $report->nurse_id = $nurse;
        $report->anaesthetist_id = $anaesthetist;
        $report->ut_cx = $ut_cx;
        $report->avf_rvf = $avf_rvf;
        $report->easy_difficult = $easy_difficult;
        $report->postoperative = $postoperative;
        $report->complications = $complications;
        $report->notes = $notes;


        $clinician = filter_input(INPUT_POST, 'clinician');
        $embryologist = filter_input(INPUT_POST, 'embryologist');
        $date = filter_input(INPUT_POST, 'date');
        $report->clinician_id = $clinician;
        $report->embryologist_id = $embryologist;
        $report->date = $date;

        try {
            R::store($report);
            if (!empty($patientid)) {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index&patientid=' . $patientid);
            } else {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index');
            }
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function editOvm() {

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

        //get id for item
        $id = filter_input(INPUT_GET, 'id');
        $patientid = filter_input(INPUT_GET, "patientid");

        //load all here
        $clinician = R::getAll("select* from awusers where role_id=4");
        $this->smarty->assign('clinician', $clinician);

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

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


        $editElementov = R::load('ovumpickup', $id);
        $this->smarty->assign('editElementov', $editElementov);
        $this->smarty->assign('patientId', $patientid);

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

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


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


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


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


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

        $operation_other_th = R::findAll('operationotherth');
        $this->smarty->assign('operation_other_th', $operation_other_th);

        //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('ovumpickup_embryotrans/edit_ovum.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function editEmbryoTransfer() {

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

        //get id for item
        $id = filter_input(INPUT_GET, 'id');
        $patientid = filter_input(INPUT_GET, "patientid");

        //load all here

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

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

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


        $editElement = R::load('embryotransferovum', $id);
        $this->smarty->assign('editElement', $editElement);
        $this->smarty->assign('patientId', $patientid);

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

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

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


        //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('ovumpickup_embryotrans/edit_embryo_transfer.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateOvm() {

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

        $consultant = filter_input(INPUT_POST, 'consultant');
        $date = filter_input(INPUT_POST, 'date');
        $anaesthetist = filter_input(INPUT_POST, 'anaesthetist');
        $nurse = filter_input(INPUT_POST, 'nurse');
        $operation = filter_input(INPUT_POST, 'operation');
        $postoperative_treatment = filter_input(INPUT_POST, 'postoperative_treatment');
        $complications = filter_input(INPUT_POST, 'complications');

        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            //here the add
            $ovumpickup = R::load('ovumpickup', $id);
            $ovumpickup->patientid = $patientid;
            $ovumpickup->date = $date;
            $ovumpickup->consultant = $consultant;
            $ovumpickup->anaesthetist = $anaesthetist;
            $ovumpickup->nurse = $nurse;
            $ovumpickup->operation = $operation;
            $ovumpickup->postoperative = $postoperative_treatment;
            $ovumpickup->complications = $complications;


            try {
                $id = R::store($ovumpickup);
                if (!empty($patientid)) {
                    header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index&patientid=' . $patientid);
                } else {
                    header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index');
                }
            } catch (Exception $e) {
                header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
            }
        }
    }

    public function updateEmbryotransfer() {

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

        //vars here
        $id = filter_input(INPUT_POST, 'id');

        $consultant = filter_input(INPUT_POST, 'consultant');
        $day = filter_input(INPUT_POST, 'day');
        $nurse = filter_input(INPUT_POST, 'nurse');
        $embryologist = filter_input(INPUT_POST, 'embryologist');
        $no_of_embryos = filter_input(INPUT_POST, 'no_of_embryos');
        $quality = filter_input(INPUT_POST, 'quality');
        $notes = filter_input(INPUT_POST, 'notes');

        $patientid = filter_input(INPUT_GET, "patientid");
        $this->smarty->assign('patientId', $patientid);
        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            //here the add
            $embryotransferovum = R::load('embryotransferovum', $id);

            $embryotransferovum->patientid = $patientid;
            $embryotransferovum->date = date('Y-m-d h:i:s');
            $embryotransferovum->day = $day;
            $embryotransferovum->consultant = $consultant;
            $embryotransferovum->nurse = $nurse;
            $embryotransferovum->embryologist = $embryologist;
            $embryotransferovum->no_of_embryos = $no_of_embryos;
            $embryotransferovum->quality = $quality;
            $embryotransferovum->notes = $notes;

            try {
                $id = R::store($embryotransferovum);
                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) {
                header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
            }
        }
    }

    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 {
            R::exec("DELETE from $tableName WHERE id = " . $id);
            echo 1;
        } catch (Exception $e) {
            
        }
    }

    public function tempdel() {
        //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 {
            $table_obj = R::load($tableName, $id);
            $table_obj->del = 1;
            R::store($table_obj);
            echo 1;
        } catch (Exception $e) {
            
        }
    }

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

        $easydifficult = filter_input(INPUT_POST, 'selectedeasydifficult');
        $addeasydifficult = R::dispense('easydifficult');
        $addeasydifficult->easydifficult = $easydifficult;
        $inserted = R::store($addeasydifficult);
        echo $inserted;
    }

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

        $ut = filter_input(INPUT_POST, 'selectedut');
        $addut = R::dispense('ut');
        $addut->ut = $ut;
        $inserted = R::store($addut);
        echo $inserted;
    }

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

        $avf = filter_input(INPUT_POST, 'selectedavf');
        $addavf = R::dispense('avf');
        $addavf->avf = $avf;
        $inserted = R::store($addavf);
        echo $inserted;
    }

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


        $tableName = filter_input(INPUT_POST, "tableName");

        $colName = filter_input(INPUT_POST, "colName");


        $alldata = R::findAll($tableName);

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

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

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


        $this->smarty->display('ovumpickup_embryotrans/editmodel.html');
    }

    public function addNewRow() {

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

        //vars here
        $table = filter_input(INPUT_POST, 'tableName');
        $columname = filter_input(INPUT_POST, 'colName');

        ### insert into table
        $newtable = R::dispense($table);
        $newtable->$columname = "";

        $insertid = R::store($newtable);

        echo $insertid;
    }

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


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

        $colName = filter_input(INPUT_POST, "colName");
        print_r($tableName);

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

    public function delRowsommedel() {

        $id = filter_input(INPUT_POST, "id");
        $tableName = filter_input(INPUT_POST, "tableName");
        $myData = R::load($tableName, $id);
        R::trash($myData);

        echo 1;
    }

    function ovumPickUpNew() {
        autho::checkautho($this->hosturl);


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

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

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

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

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

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


        //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('ovumpickup_embryotrans/add_edit_mine.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function embryoTransferNew() {

        //check login
        autho::checkautho($this->hosturl);

        //get id for item
        $patientid = filter_input(INPUT_GET, "patientid");

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

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

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


        //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('ovumpickup_embryotrans/add_editEmbryoTransferMine.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    #################################  follow up ##################################

    function followUp() {
        autho::checkautho($this->hosturl);


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

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

            $operation_other_th = R::findAll('operationotherth');
            $this->smarty->assign('operation_other_th', $operation_other_th);

            $follow_drugs = R::findAll('follow_drugs', 'conditions = 0 order by name');
            $this->smarty->assign('follow_drugs', $follow_drugs);

            $follow_rout = R::findAll('follow_rout', 'deleted = 0 order by name');
            $this->smarty->assign('follow_rout', $follow_rout);

            $follow_semen = R::findAll('follow_semen', 'deleted = 0 order by name');
            $this->smarty->assign('follow_semen', $follow_semen);

            $alldiagnosis = R::findall('diagnosis', 'conditions = 0 order by name');
            $this->smarty->assign('alldiagnosis', $alldiagnosis);

            $followup = R::findOne('followup_operation', 'done = 0 AND patientid = ?', [$patientid]);
            if (count($followup) < 1) {

                $followup = R::xdispense('followup_operation');

                $lastVisit = R::findOne('visits', 'deleted = 0 and for_department = 13 AND patientid = ? 
                         order by visitdate desc  ', [$patientid]);
                if (count($lastVisit) > 0) {
                    $followup->op_date = $lastVisit->visitdate;
                } else {
                    $followup->op_date = date("Y/m/d");
                }

                $followup->patientid = $patientid;
                $followup->operationid = 0;
                $followup->userid = $_SESSION['user_id'];
                $followup->del = 0;
                $followup->done = 0;

                $followup->day = date('l', strtotime(date("Y/m/d")));
                $followup->ontime = date("H:i", strtotime("10:30"));


                $followup->id = R::store($followup);
            }

            $followup->op_day = date('l', strtotime($followup->op_date));

            $selectArray = explode(',', $followup->diagnosis);
            $followup->diagnosis = $selectArray;


            $selectArray1 = explode(',', $followup->drugs);
            $followup->drugs = $selectArray1;

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

            $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);

            $days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
            $this->smarty->assign('days', $days);

            $bloodtypes = R::findAll('bloodtypes', 'order by title');
            $this->smarty->assign('bloodtypes', $bloodtypes);


            $follow_pre = R::findall('follow_pre', 'deleted = ? and followid = ? ORDER BY id DESC ', [0, $followup->id]);
            foreach ($follow_pre as $obj) {
                $obj->timing = date("m/d g:ia", strtotime($obj->timing));
            }

            $follow_post = R::findall('follow_post', 'deleted = ? and followid = ? ORDER BY id DESC ', [0, $followup->id]);
            foreach ($follow_post as $obj) {
                $obj->timing = date("m/d g:ia", strtotime($obj->timing));
            }

            $followup->op_date = date("Y/m/d", strtotime($followup->op_date));

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

            $this->smarty->assign('follow_pres', $follow_pre);
            $this->smarty->assign('preItr', count($follow_pre));

            $this->smarty->assign('follow_posts', $follow_post);
            $this->smarty->assign('postItr', count($follow_post));


            $follow_drain = R::findAll('follow_drain', 'deleted = 0 order by name');
            $this->smarty->assign('follow_drain', $follow_drain);

            $follow_vpack = R::findAll('follow_vpack', 'deleted = 0 order by name');
            $this->smarty->assign('follow_vpack', $follow_vpack);

            $follow_uop = R::findAll('follow_uop', 'deleted = 0 order by name');
            $this->smarty->assign('follow_uop', $follow_uop);

            $programesetting = R::findOne('programesetting');
            $this->smarty->assign('programesetting', $programesetting);
        }

        //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('ovumpickup_embryotrans/follow_up.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function addFollowUp() {

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

        $id = filter_input(INPUT_POST, 'id');
        $patientid = filter_input(INPUT_GET, "patientid");

        if (empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        } else {
            //here the add
            $followup = R::load('followup_operation', $id);
            $followup->done = 1;

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

    public function update() {

        //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");
        $colname = filter_input(INPUT_POST, "colName");
        $value = filter_input(INPUT_POST, "value");
        $dated = filter_input(INPUT_POST, "dated");


        if ($dated == 1) {
            $value = date("Y-m-d", strtotime($value));
        }

        echo $value;


        if ($colname == "diagnosis") {
            $diagnosis = json_decode($value);
            sort($diagnosis);
            $value = "";
            foreach ($diagnosis as $myname) {
                $value = $value . $myname . ",";
            }
            $value = substr($value, 0, -1);
        }

        if ($colname == "drugs") {
            $drugs = json_decode($value);
            sort($drugs);
            $value = "";
            foreach ($drugs as $myname) {
                $value = $value . $myname . ",";
            }
            $value = substr($value, 0, -1);
        }


        if ($colname == "timing") {
            $value = date("Y-m-d H:i", strtotime($value));
        }




        try {

            $obj = R::load($tablename, $id);

            $obj->$colname = $value;

            R::store($obj);

            echo $value;
        } catch (Exception $e) {
            print_r($e);
        }
    }

    public function adddiagnosis() {

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

        $name = filter_input(INPUT_POST, "diagnosisName");
        $id = filter_input(INPUT_POST, "id");
        $table = filter_input(INPUT_POST, "table");
        try {
            $diagnosis = R::xdispense($table);
            $diagnosis->name = $name;
            $diagnosis->conditions = 0;
            $did = R::store($diagnosis);


            $followup = R::load('followup_operation', $id);

            if ($table == 'diagnosis') {
                if (empty($followup->diagnosis)) {
                    $followup->diagnosis = $did;
                } else {
                    $followup->diagnosis = $followup->diagnosis . ',' . $did;
                }
            } else if ($table == 'follow_drugs') {
                if (empty($followup->drugs)) {
                    $followup->drugs = $did;
                } else {
                    $followup->drugs = $followup->drugs . ',' . $did;
                }
            }


            R::store($followup);


            echo $did;
        } catch (Exception $e) {
            echo $e;
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function alldiagnosis() {

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

        $colname = filter_input(INPUT_POST, "colName");

        if ($colname == 'drugs') {
            $table = "follow_drugs";
        }
        ##
        else if ($colname == 'complaint') {
            $table = "complaintant";
        }
        ##
        else {
            $table = $colname;
        }

        $delColname = 'conditions';
        $names = array('drug_sensitivity', 'blood_transfusion', 'complaint_analysis', 'symptoms', 'pre_history');

        if (in_array($table, $names)) {
            $delColname = 'deleted';
        }



        try {

            $alldiagnosis = R::findall($table, $delColname . ' = 0 order by name');
            $this->smarty->assign('alldata', $alldiagnosis);
            $this->smarty->assign('table', $table);
            $this->smarty->assign('delColname', $delColname);
            $this->smarty->display('ovumpickup_embryotrans/editmodel2.html');
            //header('Location:' . $this->hosturl . '/' . $this->controllname );
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    function editFollowUp() {
        autho::checkautho($this->hosturl);


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

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


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

        $this->smarty->assign('patientId', $patientid);

        $operation_other_th = R::findAll('operationotherth');
        $this->smarty->assign('operation_other_th', $operation_other_th);

        $follow_drugs = R::findAll('follow_drugs', 'conditions = 0 order by name');
        $this->smarty->assign('follow_drugs', $follow_drugs);

        $follow_rout = R::findAll('follow_rout', 'deleted = 0 order by name');
        $this->smarty->assign('follow_rout', $follow_rout);

        $follow_semen = R::findAll('follow_semen', 'deleted = 0 order by name');
        $this->smarty->assign('follow_semen', $follow_semen);

        $alldiagnosis = R::findall('diagnosis', 'conditions = 0 order by name');
        $this->smarty->assign('alldiagnosis', $alldiagnosis);

        $followup = R::load('followup_operation', $id);

        $followup->op_day = date('l', strtotime($followup->op_date));

        $selectArray = explode(',', $followup->diagnosis);
        $followup->diagnosis = $selectArray;

        $selectArray1 = explode(',', $followup->drugs);
        $followup->drugs = $selectArray1;

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

        $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);

        $days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
        $this->smarty->assign('days', $days);

        $bloodtypes = R::findAll('bloodtypes', 'order by title');
        $this->smarty->assign('bloodtypes', $bloodtypes);


        $follow_pre = R::findall('follow_pre', 'deleted = ? and followid = ? ORDER BY id DESC ', [0, $followup->id]);
        foreach ($follow_pre as $obj) {
            $obj->timing = date("m/d g:ia", strtotime($obj->timing));
        }

        $follow_post = R::findall('follow_post', 'deleted = ? and followid = ? ORDER BY id DESC ', [0, $followup->id]);
        foreach ($follow_post as $obj) {
            $obj->timing = date("m/d g:ia", strtotime($obj->timing));
        }

        $followup->op_date = date("Y/m/d", strtotime($followup->op_date));

        $this->smarty->assign('follow_pres', $follow_pre);
        $this->smarty->assign('preItr', count($follow_pre));

        $this->smarty->assign('follow_posts', $follow_post);
        $this->smarty->assign('postItr', count($follow_post));


        $follow_drain = R::findAll('follow_drain', 'deleted = 0 order by name');
        $this->smarty->assign('follow_drain', $follow_drain);

        $follow_vpack = R::findAll('follow_vpack', 'deleted = 0 order by name');
        $this->smarty->assign('follow_vpack', $follow_vpack);

        $follow_uop = R::findAll('follow_uop', 'deleted = 0 order by name');
        $this->smarty->assign('follow_uop', $follow_uop);


        $this->smarty->assign('followup', $followup);
        $this->smarty->assign('edit', 1);


        //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('ovumpickup_embryotrans/follow_up.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function printSheet() {
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "id");

        $followup = R::load('followup_operation', $followupId);

        $sql = '  select patients.id   , patients.wifename  ,  patients.husdandname  , "" as wAge   , "" as hAge  
                    ,  patients.husbanddateofbirth  ,  patients.dateofbirth ,  patients.phone,  patients.mobile 
                    ,  patients.wifenationalid ,  patients.husbandnationalid    ,  patients.address
                  , (CASE   WHEN patients.rfc = 1 THEN "Yes"   WHEN patients.rfc = 2 THEN "No" ELSE ""   END ) AS rfc   
                    , (CASE   WHEN patients.wrfc = 1 THEN "Yes"   WHEN patients.wrfc = 2 THEN "No" ELSE ""   END ) AS wrfc
                    ,  knownfrom.name   as  knownfrom   , "" as diagnosis       ,  patients.statusno 
                     ,  patients.refer_doctor  ,  patients.h_refer_doctor ,  patients.refer_doctor_tb,  patients.h_refer_doctor_tb 
                    
                    , (CASE   WHEN patients.doctor1 > 0 THEN doctor1.name      ELSE "لا يوجد "   END ) AS doctor1   
                    , (CASE   WHEN patients.h_doctor1 > 0 THEN h_doctor1.name      ELSE "لا يوجد "   END ) AS h_doctor1   
                    , (CASE   WHEN patients.doctor2 > 0 THEN doctor2.name      ELSE "لا يوجد "   END ) AS doctor2   
                    , (CASE   WHEN patients.h_doctor2 > 0 THEN h_doctor2.name      ELSE "لا يوجد "   END ) AS h_doctor2   
 
                   , wifejobs.title as wifejob  ,   husbandjobs.title as husbandjob
                   , religion.name as religion  ,   hreligion.name as hreligion
                    , nationality.name as nationality  ,   hnationality.name as hnationality

                     from    patients
                     left join knownfrom             on knownfrom.id = patients.knownfrom 
                     left join wifejobs                 on wifejobs.id = patients.wifejob  
                     left join husbandjobs         on husbandjobs.id = patients.husbandjob  
                     left join religion                 on religion.id = patients.religion  
                     left join hreligion                on hreligion.id = patients.h_religion  
                     left join nationality                 on nationality.id = patients.nationality  
                     left join hnationality            on hnationality.id = patients.h_nationality   
                      left join awusers   doctor1       on doctor1.user_id = patients.doctor1  
                     left join awusers     h_doctor1     on h_doctor1.user_id = patients.h_doctor1  
                     left join awusers   doctor2       on doctor2.user_id = patients.doctor2  
                     left join awusers     h_doctor2      on h_doctor2.user_id = patients.h_doctor2  
            
                    where   patients.id =  ' . $followup->patientid;

        $patient = R::getRow($sql);

        $today1 = new DateTime(date('Y-m-d'));

        $dateHusband = new DateTime($patient['husbanddateofbirth']);
        $dateWife = new DateTime($patient['dateofbirth']);

        if ($patient['dateofbirth'] == '0000-00-00' || is_null($patient['dateofbirth'])) {
            $patient['wAge'] = 0;
        } else {
            ## calculate wife age
            $interva2 = $today1->diff($dateWife);
            $patient['wAge'] = $interva2->y;
        }


        if ($patient['husbanddateofbirth'] == '0000-00-00' || is_null($patient['husbanddateofbirth'])) {
            $patient['hAge'] = 0;
        } else {
            ## calculate husband age
            $interval = $today1->diff($dateHusband);
            $patient['hAge'] = $interval->y;
        }


        if ($patient['refer_doctor'] > 0) {
            if ($patient['refer_doctor_tb'] == 1) {
                $refer = R::getRow('select name from awusers where user_id = ?', [$patient['refer_doctor']]);
                $patient['refer_doctor'] = $refer['name'];
            } else {
                $refer = R::load('refer', $patient['refer_doctor']);
                $patient['refer_doctor'] = $refer->name;
            }
        } else {
            $patient['refer_doctor'] = "لا يوجد ";
        }


        if ($patient['h_refer_doctor'] > 0) {
            if ($patient['h_refer_doctor_tb'] == 1) {
                $refer = R::getRow('select name from awusers where user_id = ?', [$patient['h_refer_doctor']]);
                $patient['h_refer_doctor'] = $refer['name'];
            } else {
                $refer = R::load('refer', $patient['h_refer_doctor']);
                $patient['h_refer_doctor'] = $refer->name;
            }
        } else {
            $patient['h_refer_doctor'] = "لا يوجد ";
        }

        $v = 1;
        $diagnosis = ' ';
        $selectArray = explode(',', $followup->diagnosis);

        foreach ($selectArray as $data) {
            $diag = R::load('diagnosis', $data);
            if ($diag->conditions < 1) {
                if ($v > 1) {
                    $diagnosis .= ' , ';
                }

                $diagnosis .= $diag->name;

                $v++;
            }
        }

        $patient['diagnosis'] = $diagnosis;


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


        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('programesetting', $programesetting);

        $this->smarty->display('ovumpickup_embryotrans/printsheet.html');
    }

    public function delPre() {

        //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 {

            $obj = R::load($tableName, $id);
            $obj->deleted = 1;
            R::store($obj);

            echo 1;
        } catch (Exception $e) {
            
        }
    }

    function addPreRow() {

        //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");
        $itr = filter_input(INPUT_POST, "newItr");
        if ($id < 1) {
            echo '-1';
        } else {
            $obj = R::xdispense($tableName);
            $obj->followid = $id;
            $obj->deleted = 0;
            $obj->timing = date('Y-m-d H:i');
            ##
            $obj->bp = '12080';
            $obj->pulse = '85';
            $obj->temp = '37';
            $obj->so2 = '95';
            ##
            $obj->id = R::store($obj);


            $obj->timing = date("m/d g:ia", strtotime($obj->timing));

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

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

            $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);

            $bloodtypes = R::findAll('bloodtypes', 'order by title');
            $this->smarty->assign('bloodtypes', $bloodtypes);

            $follow_drain = R::findAll('follow_drain', 'deleted = 0 order by name');
            $this->smarty->assign('follow_drain', $follow_drain);

            $follow_vpack = R::findAll('follow_vpack', 'deleted = 0 order by name');
            $this->smarty->assign('follow_vpack', $follow_vpack);

            $follow_uop = R::findAll('follow_uop', 'deleted = 0 order by name');
            $this->smarty->assign('follow_uop', $follow_uop);

            $this->smarty->assign('tableName', $tableName);
            $this->smarty->assign('itr', $itr);
            $this->smarty->display('ovumpickup_embryotrans/newrow.html');
        }
    }

    function addnewoRecord() {
        //vars here
        $name = filter_input(INPUT_POST, 'selectedoperation');
        $inline = filter_input(INPUT_POST, 'inline');
        $selectid = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, "tableName");
        $colName = filter_input(INPUT_POST, "colName");

        ### insert into table
        $newtable = R::xdispense($tableName);
        $newtable->name = $name;
        $insertid = R::store($newtable);

        if ($inline == 1) {
            $mydata = R::load('followup_operation', $selectid);
            $mydata->$colName = $insertid;
            R::store($mydata);
            print_r($mydata);
        } elseif ($inline == 2) {
            $mydata = R::load('follow_post', $selectid);
            $mydata->$colName = $insertid;
            R::store($mydata);
        }

        echo $insertid;
    }

    function followTTT() {
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "id");
        $this->smarty->assign('followupId', $followupId);

        $follow_instruction = R::findAll('follow_instruction', 'followid = ? and deleted != 1', [$followupId]);
        $this->smarty->assign('follow_instruction', $follow_instruction);


        $doctorsAll = 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('doctorsAll', $doctorsAll);

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

        $this->smarty->display('ovumpickup_embryotrans/addttt.html');
    }

    function getInsByDoctor() {
        autho::checkautho($this->hosturl);

        $doctorId = filter_input(INPUT_POST, "id");


        $insts = R::getAll('SELECT * FROM doc_instruction WHERE doctorid = ? and deleted != 1', [$doctorId]);

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

        $this->smarty->display('ovumpickup_embryotrans/newselect.html');
    }

    public function getprint() {

        //check login
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "followupId");
        $forHusband = filter_input(INPUT_POST, "preFor");
        $send = filter_input(INPUT_POST, "send");
        $instructionArray = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));
        $followup = R::load('followup_operation', $followupId);


        $instructionArrayNew = array();

        $patientId = $followup->patientid;
        $printDate = date('Y-m-d');

        foreach ($instructionArray as $inst) {
            $instruction = R::load('doc_instruction', $inst);
            $presId = $this->addFollowInst($instruction, $forHusband, $followupId);
            if ($send == 1 && $presId > 0) {
                $res = $this->sendPre($presId);
                echo $res;
            }
            array_push($instructionArrayNew, $instruction);
        }

        if ($send != 1) {
            $patient = R::load('patients', $patientId);

            if ($forHusband == 1) {
                $this->smarty->assign('name', $patient->husdandname);
            } else {
                $this->smarty->assign('name', $patient->wifename);
            }

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

            //  $this->createbarcode($patient->statusno);

            $doc = R::findOne('awusers', 'user_id = ?', [$patient->doctor1]);
            $h_doc = R::findOne('awusers', 'user_id = ?', [$patient->h_doctor1]);

            $this->smarty->assign('doctor_name', $doc->name);
            $this->smarty->assign('h_doctor_name', $h_doc->name);

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

            $this->smarty->assign('patientId', $patientId);
            $this->smarty->assign('printDate', $printDate);

            $ProgramesettingData = R::findone('programesetting');
            $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

            $this->smarty->assign('instructions', $instructionArrayNew);
            $this->smarty->assign('show', 0);

            $this->smarty->display('ovumpickup_embryotrans/print.html');
        }
    }

    function addFollowInst($instruction, $forHusband, $followupId) {

        ### insert into table
        $newtable = R::xdispense('follow_instruction');
        $newtable->followid = $followupId;
        $newtable->for_husband = $forHusband;
        $newtable->doc_instructionid = $instruction->id;
        $newtable->name = $instruction->name;
        $newtable->content = $instruction->content;
        $newtable->sysdate = date('Y-m-d');
        $newtable->deleted = 0;
        $id = R::store($newtable);
        return $id;
    }

    function addTTTInst() {
        autho::checkautho($this->hosturl);

        //vars here
        $name = filter_input(INPUT_POST, 'fileName');
        $content = filter_input(INPUT_POST, 'content');
        $docAddId = filter_input(INPUT_POST, 'docAddId');

        $newtable = R::xdispense('doc_instruction');
        $newtable->doctorid = $docAddId;
        $newtable->name = $name;
        $newtable->content = $content;
        $newtable->deleted = 0;
        $insertid = R::store($newtable);
        echo $insertid;
    }

    function editTTTInst() {
        autho::checkautho($this->hosturl);

        $id = filter_input(INPUT_POST, "id");
        $save = filter_input(INPUT_POST, "save");

        if (empty($id) || $id < 1) {
            header('Location:' . $this->hosturl . '/controllers/index.php');
            exit();
        }

        $doc_instruction = R::load('doc_instruction', $id);
        $this->smarty->assign('doc_instruction', $doc_instruction);

        $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);

        $this->smarty->assign('save', $save);
        $this->smarty->display('ovumpickup_embryotrans/edittttinst.html');
    }

    function updateTTTInst() {
        autho::checkautho($this->hosturl);

        //vars here
        $insId = filter_input(INPUT_POST, 'insId');
        $name = filter_input(INPUT_POST, 'fileNameEdit');
        $content = filter_input(INPUT_POST, 'contentEdit');
        $docAddId = filter_input(INPUT_POST, 'docAddIdEdit');

        $newtable = R::load('doc_instruction', $insId);
        $newtable->doctorid = $docAddId;
        $newtable->name = $name;
        $newtable->content = $content;
        $insertid = R::store($newtable);
        echo $insertid;
    }

    function getDayName() {
        autho::checkautho($this->hosturl);

        $date = filter_input(INPUT_POST, "value");

        echo date('l', strtotime($date));
    }

    function showFllowTTT() {
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "id");
        $this->smarty->assign('followupId', $followupId);

        $follow_instruction = R::findAll('follow_instruction', 'followid = ? and deleted != 1', [$followupId]);
        $this->smarty->assign('follow_instruction', $follow_instruction);

        $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);

        $this->smarty->display('ovumpickup_embryotrans/show_ttt.html');
    }

    function followInsDetails() {
        autho::checkautho($this->hosturl);

        $id = filter_input(INPUT_POST, "id");

        if (empty($id) || $id < 1) {
            header('Location:' . $this->hosturl . '/controllers/index.php');
            exit();
        }

        $follow_instruction = R::load('follow_instruction', $id);

        $result = array(
            "fileName" => $follow_instruction->name,
            "content" => $follow_instruction->content
        );

        echo json_encode($result);
    }

    public function getprintFollow() {

        //check login
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "followupId");
        $instructionArray = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));




        $followup = R::load('followup_operation', $followupId);


        $patientId = $followup->patientid;
        $printDate = date('Y-m-d');


        $patient = R::load('patients', $patientId);

        $instructionArrayNew = array();


        foreach ($instructionArray as $inst) {
            $instruction = R::load('follow_instruction', $inst);

            if ($instruction->for_husband == 1) {
                $instruction->pName = $patient->husdandname;
            } else {
                $instruction->pName = $patient->wifename;
            }

            array_push($instructionArrayNew, $instruction);
        }


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

        //  $this->createbarcode($patient->statusno);

        $doc = R::findOne('awusers', 'user_id = ?', [$patient->doctor1]);
        $h_doc = R::findOne('awusers', 'user_id = ?', [$patient->h_doctor1]);

        $this->smarty->assign('doctor_name', $doc->name);
        $this->smarty->assign('h_doctor_name', $h_doc->name);



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

        $this->smarty->assign('patientId', $patientId);
        $this->smarty->assign('printDate', $printDate);

        $ProgramesettingData = R::findone('programesetting');
        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

        $this->smarty->assign('instructions', $instructionArrayNew);
        $this->smarty->assign('show', 3);

        $this->smarty->display('ovumpickup_embryotrans/print.html');
    }

    function printFollow() {
        autho::checkautho($this->hosturl);

        $followupId = filter_input(INPUT_POST, "id");
        $forHusband = filter_input(INPUT_POST, "preFor");

        $sql = '  select  patients.wifename  ,  patients.husdandname   , follow.pre_note
                   , follow.op_date ,   operationotherth.name as operationName  , follow.post_instruction
                    ,  surgeon.name as surgeonName   ,  assistant.name as assistantName  ,  anaesthetist.name as anaesthetistName 

                     from    followup_operation  follow
                      left join operationotherth                on operationotherth.id = follow.operationid  
                       join patients                                  on patients.id = follow.patientid  
                       
                        left join awusers   surgeon                on surgeon.user_id = follow.surgeon  
                        left join awusers   assistant                 on assistant.user_id = follow.assistant  
                       left join awusers   anaesthetist                 on anaesthetist.user_id = follow.anaesthetist  
            
                   where   follow.id =  ' . $followupId;

        $followup = R::getRow($sql);

        $followup['op_day'] = date('l', strtotime($followup['op_date']));

        $this->smarty->assign('followup', $followup);
        $this->smarty->assign('forHusband', $forHusband);

        $sql = '  select  bloodtypes.title as aborh  ,  doctor.name as doctorName   ,  nurse.name as nurseName 
                   , pre.hb  , pre.plt ,   pre.rbs    ,  pre.bp   ,  pre.pulse  ,  pre.temp ,  pre.so2 ,  pre.timing

                     from    follow_pre  pre
                      left join awusers   doctor                on doctor.user_id = pre.doctorid  
                      left join awusers   nurse                 on nurse.user_id = pre.nurseid  
                     left join bloodtypes                          on bloodtypes.id = pre.aborh  
            
                   where pre.deleted = 0 and    pre.followid =  ' . $followupId . '  order by pre.timing asc';

        $follow_pre = R::getAll($sql);

        $i = 0;
        foreach ($follow_pre as $obj) {
            $follow_pre[$i]['timing'] = date('m/d g:ia', strtotime($follow_pre[$i]['timing']));
            $i++;
        }

        $this->smarty->assign('follow_pres', $follow_pre);

        $sql = '  select   doctor.name as doctorName   ,  nurse.name as nurseName  
                  ,   follow_drain.name as drain   ,  follow_vpack.name as vpack 
                   ,  follow_uop.name as uop       ,   post.rbs ,   post.bp   ,  post.pulse 
                   ,  post.temp ,  post.so2 ,  post.timing

                     from    follow_post  post
                      left join awusers   doctor                on doctor.user_id = post.doctorid  
                      left join awusers   nurse                 on nurse.user_id = post.nurseid  
                     left join follow_drain                          on follow_drain.id = post.drain  
                      left join follow_vpack                        on follow_vpack.id = post.vpack  
                       left join follow_uop                          on follow_uop.id = post.uop  
            
                   where post.deleted = 0 and    post.followid =  ' . $followupId . '  order by post.timing asc';

        $follow_post = R::getAll($sql);

        $i = 0;
        foreach ($follow_post as $obj) {
            $follow_post[$i]['timing'] = date('m/d g:ia', strtotime($follow_post[$i]['timing']));
            $i++;
        }

        $this->smarty->assign('follow_posts', $follow_post);

//        $today1 = new DateTime(date('Y-m-d'));
//
//        $dateHusband = new DateTime($patient['husbanddateofbirth']);
//        $dateWife = new DateTime($patient['dateofbirth']);
//
//        if ($patient['dateofbirth'] == '0000-00-00' || is_null($patient['dateofbirth'])) {
//            $patient['wAge'] = 0;
//        } else {
//            ## calculate wife age
//            $interva2 = $today1->diff($dateWife);
//            $patient['wAge'] = $interva2->y;
//        }
//
//
//        if ($patient['husbanddateofbirth'] == '0000-00-00' || is_null($patient['husbanddateofbirth'])) {
//            $patient['hAge'] = 0;
//        } else {
//            ## calculate husband age
//            $interval = $today1->diff($dateHusband);
//            $patient['hAge'] = $interval->y;
//        }
//
//
//        if ($patient['refer_doctor'] > 0) {
//            if ($patient['refer_doctor_tb'] == 1) {
//                $refer = R::getRow('select name from awusers where user_id = ?', [$patient['refer_doctor']]);
//                $patient['refer_doctor'] = $refer['name'];
//            } else {
//                $refer = R::load('refer', $patient['refer_doctor']);
//                $patient['refer_doctor'] = $refer->name;
//            }
//        } else {
//            $patient['refer_doctor'] = "لا يوجد ";
//        }
//
//
//        if ($patient['h_refer_doctor'] > 0) {
//            if ($patient['h_refer_doctor_tb'] == 1) {
//                $refer = R::getRow('select name from awusers where user_id = ?', [$patient['h_refer_doctor']]);
//                $patient['h_refer_doctor'] = $refer['name'];
//            } else {
//                $refer = R::load('refer', $patient['h_refer_doctor']);
//                $patient['h_refer_doctor'] = $refer->name;
//            }
//        } else {
//            $patient['h_refer_doctor'] = "لا يوجد ";
//        }
//
//        $v = 1;
//        $diagnosis = ' ';
//        $selectArray = explode(',', $followup->diagnosis);
//
//        foreach ($selectArray as $data) {
//            $diag = R::load('diagnosis', $data);
//            if ($diag->conditions < 1) {
//                if ($v > 1) {
//                    $diagnosis .= ' , ';
//                }
//
//                $diagnosis .= $diag->name;
//
//                $v++;
//            }
//        }
//
//        $patient['diagnosis'] = $diagnosis;
//
//
//        $this->smarty->assign('patient', $patient);
//
//
        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('programesetting', $programesetting);

        $this->smarty->display('ovumpickup_embryotrans/printfollow.html');
    }

    function printInstWithoutSave() {
        autho::checkautho($this->hosturl);

        //vars here
        $insId = filter_input(INPUT_POST, 'insId');
        $name = filter_input(INPUT_POST, 'fileNameEdit');
        $content = filter_input(INPUT_POST, 'contentEdit');
        $docAddId = filter_input(INPUT_POST, 'docAddIdEdit');
        $send = filter_input(INPUT_POST, "insSend");

        $instruction = R::load('doc_instruction', $insId);
        $instruction->doctorid = $docAddId;
        $instruction->name = $name;
        $instruction->content = $content;

        $followupId = filter_input(INPUT_POST, "insFollowId");
        $forHusband = filter_input(INPUT_POST, "preForNo");
        $followup = R::load('followup_operation', $followupId);

        $patientId = $followup->patientid;
        $printDate = date('Y-m-d');


        $instructionArrayNew = array();

        $presId = $this->addFollowInst($instruction, $forHusband, $followupId);
        if ($send == 1 && $presId > 0) {
            $res = $this->sendPre($presId);
            echo $res;
        }
        array_push($instructionArrayNew, $instruction);

        if ($send != 1) {
            $patient = R::load('patients', $patientId);

            if ($forHusband == 1) {
                $this->smarty->assign('name', $patient->husdandname);
            } else {
                $this->smarty->assign('name', $patient->wifename);
            }

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

            //  $this->createbarcode($patient->statusno);

            $doc = R::findOne('awusers', 'user_id = ?', [$patient->doctor1]);
            $h_doc = R::findOne('awusers', 'user_id = ?', [$patient->h_doctor1]);

            $this->smarty->assign('doctor_name', $doc->name);
            $this->smarty->assign('h_doctor_name', $h_doc->name);



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

            $this->smarty->assign('patientId', $patientId);
            $this->smarty->assign('printDate', $printDate);

            $ProgramesettingData = R::findone('programesetting');
            $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

            $this->smarty->assign('instructions', $instructionArrayNew);
            $this->smarty->assign('show', 0);

            $this->smarty->display('ovumpickup_embryotrans/print.html');
        }
    }

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

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

        $id = filter_input(INPUT_POST, "id");
        $res = $this->sendPre($id);
        echo $res;
    }

    function sendPre($id) {
        autho::checkautho($this->hosturl);                   ##  check login
        $pres = R::load('follow_instruction', $id);
        $followup = R::load('followup_operation', $pres->followid);
        $instruction = R::load('doc_instruction', $pres->doc_instructionid);
        $printDate = date("Y/m/d");

        $res = presSend(1, $followup->patientid, $instruction->doctorid, $printDate, $pres, $pres->for_husband);

//        $dataArray = $this->pdfContent($pres, $followup->patientid, $printDate, $instruction->doctorid);
//        $fileName = md5(uniqid(mt_rand(), true)) . '.pdf';
//        $res = $this->generatePresPdf($dataArray, $fileName);
        echo $res;
    }

    function pdfContent($pres, $patientId, $printDate, $doctorId) {
        $htmlHead = ' <html> <head> <style>  ';
        $htmlHead .= ' </style></head>  <body> ';
        $htmlBody = $this->presInfo($pres);
        $dataArray = $this->patientInfo($patientId, $pres->for_husband, $printDate, $doctorId, $htmlBody);
        $dataArray['htmlBody'] .= $this->presInfo($pres, 1);
        $htmlFoot = '</body></html>';

        $html = $htmlHead . ' ' . $dataArray['htmlBody'] . ' ' . $htmlFoot;

        $dataArray['html'] = $html;
        return $dataArray;
    }

    function patientInfo($patientId, $preFor, $printDate, $doctorId, $htmlBody) {
        $patient = R::load('patients', $patientId);

        if ($preFor == 1) {
            $name = $patient->husdandname;
        } elseif ($preFor == 0) {
            $name = $patient->wifename;
        }

        $htmlBody .= ' <br><br>';
        $htmlBody .= '<table style="width: 100%;">
    <tr style="line-height: 20px; ">
              <td style="width: 20%;font-weight: bold;text-align: right;"> ' . $printDate . ' </td>
                  <td style="width: 15%;font-weight: bold;text-align: right;"> التاريخ        </td>
                   <td  style="width: 50%;font-weight: bold;text-align: right;">  ' . $name . '   </td>
                  <td style="width: 15%;font-weight: bold;text-align: right;"> اسم الحالة       </td>
    </tr> </table> ';

        $doctorName = ' لا يوجد  ';
        if ($doctorId > 0) {
            $doctor = R::getRow('SELECT name FROM awusers WHERE user_id = ? ', [$doctorId]);
            $doctorName = $doctor['name'];
        }

        $dataArray = array();
        $dataArray['patient_id'] = $patientId;
        $dataArray['name'] = $name;
        $dataArray['prescription_date'] = date("Y-m-d", strtotime($printDate));
        $dataArray['doctor_name'] = $doctorName;
        $dataArray['statusno'] = $patient->statusno;
        $dataArray['htmlBody'] = $htmlBody;

        return $dataArray;
    }

    function presInfo($pres, $part = 0) {
        $htmlBody = ' ';
        if ($part == 1) {
            $htmlBody .= ' <br><br>';
            $htmlBody .= ' <hr  style="border: 1px solid black;width: 100%;">';
            $htmlBody .= '<table style="width: 100%;">
                    <tr style="line-height: 20px; "><td style="text-align: right;">  ' . $pres->content . '  </td></tr> </table> ';
        } else {
            $htmlBody .= ' <br><br>';
            $htmlBody .= ' <h1 class="h1" style="text-align: center;">    ' . $pres->name . '</h1>';
            $htmlBody .= ' <hr  style="border: 1px solid black;width: 100%;">';
            $htmlBody .= ' <br><br>';
        }



        return $htmlBody;
    }

    function generatePresPdf($dataArray, $fileName) {
        ob_start();

        $programesetting = R::findOne('programesetting');

        require_once("../../_library/plugins/tcpdf/tcpdf.php");
// create new PDF document
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(5, 15, 5);
        $pdf->SetHeaderMargin(0);
        $pdf->SetFooterMargin(0);

        $pdf->SetPrintHeader(false);
        $pdf->SetPrintFooter(false);


// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
            require_once(dirname(__FILE__) . '/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

// ---------------------------------------------------------
        define('K_PATH_FONTS', dirname(__FILE__) . '/../../_library/plugins/tcpdf/');
// set font
        $pdf->SetFont('dejavusans', '', 10);
// add a page
        $pdf->AddPage();

// output the HTML content
        $pdf->writeHTML($dataArray['html'], true, false, true, false, '');

// reset pointer to the last page
        $pdf->lastPage();

        if (!file_exists('../../upload/pres_pdf/' . $dataArray['statusno'])) {
            //    print_r(555);
            mkdir('../../upload/pres_pdf/' . $dataArray['statusno'], 0777, true);
        }

//    $fileName = '5555.pdf';
//Close and output PDF document
        $pdf->Output(__DIR__ . '/../../upload/pres_pdf/' . $dataArray['statusno'] . '/' . $fileName, 'F');

        $res = $this->sendPdf($fileName, $dataArray);

        return $res;
//============================================================+
// END OF FILE
//============================================================+
    }

    function sendPdf($fileName, $dataArray) {

        $url = 'http://lab.royal-fc.net/api/prescriptions';
        $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Im1lZGljYWxfdGVzdHMiLCJwYXNzd29yZCI6Im1lZGljYWxfdGVzdHNAcGFzc3dvcmQifQ.6_o87c9NR48MsyMoer2OQzJ8PCDBVgLFJpeNo449RDA';

        $data = array(
            'patient_id' => $dataArray['patient_id']
            , 'name' => $dataArray['name']
            , 'prescription_date' => $dataArray['prescription_date']
            , 'doctor_name' => $dataArray['doctor_name']
            , 'patient_code' => $dataArray['statusno']
            , 'prescription_pdf' => new CURLFile('../../upload/pres_pdf/' . $dataArray['statusno'] . '/' . $fileName, 'application/pdf')
        );

        // Initializes a new cURL session
        $curl = curl_init($url);
        //  print_r($curl);
        // 1. Set the CURLOPT_RETURNTRANSFER option to true
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 2. Set the CURLOPT_POST option to true for POST request
        curl_setopt($curl, CURLOPT_POST, true);
// 3. Set the request data 
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// 4. Set  headers for API Auth 

        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            //'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
            'AuthorizationKey: Bearer ' . $apiKey
        ));



        // Execute cURL request with all previous settings
        $response = curl_exec($curl);


        // Close cURL session
        curl_close($curl);

        //      echo $response . PHP_EOL;

        $res = json_decode($response);
//    print_r($res->success);
//    print_r($res->error);


        return $res->success;
    }

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

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

}
