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


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

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

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

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


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

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

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

    public function test() {
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('test.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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


        $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);
        $current_date = date("Y/m/d");
        $this->smarty->assign('current_date', $current_date);
        //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('embryoslab/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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

        $this->smarty->assign('patientId', $patientid);
        //load all parents here
        $showElems = R::getAll('SELECT embryoslab.id as embryoslab_id ,  visits.visitdate 
                                                 ,awusers.name as referred_dr_name 
                                                  from embryoslab
                                                 LEFT JOIN  awusers ON embryoslab.clinician_id = awusers.user_id
                                                 LEFT JOIN  patients ON embryoslab.patient_id =patients.id  
                                                   left join   visits                                     on   embryoslab.visit_id   =   visits.id            
                                                 where 
                                                 embryoslab.not_confirm = 1 and embryoslab.patient_id=' . $patientid . ' 
                                                     order by embryoslab_id desc ');
        $this->smarty->assign('showElems', $showElems);

        $logUser = R::getRow('select * from awusers where user_id = ?', [$_SESSION['user_id']]);
        $this->smarty->assign('tanks_settings', $logUser['tanks_settings']);

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

    public function addnotconfirm() {
        //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($this->patientid)) {
            header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
            exit();
        }

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

            $em_lab_new = R::dispense('embryoslab');
            $em_lab_new->patient_id = $patientid;
            $em_lab_new->not_confirm = 0;
            $em_lab_new->doctor1 = $patient->doctor1;
            $em_lab_new->h_doctor1 = $patient->h_doctor1;
            $em_lab_new->clinician_id = $patient->doctor1;
            $em_lab_new->referred_dr_id = $patient->refer_doctor;
            $em_lab_new->refer_doctor_tb = $patient->refer_doctor_tb;

            $em_lab_new->h_referred_dr_id = $patient->h_refer_doctor;
            $em_lab_new->h_refer_doctor_tb = $patient->h_refer_doctor_tb;
            $em_lab_new->create_date = date('Y-m-d H:i:s');
            $embryoslab_id = R::store($em_lab_new);
        } else {
            $embryoslab_id = $em_lab->id;
        }


        checkEmbVisit($embryoslab_id);
        $this->smarty->assign('is_add', 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('embryoslab/edit/head.html');
        $this->loadOne($embryoslab_id);
        $this->smarty->display('embryoslab/edit/foot.html');

        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function edit() {

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


        //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('embryoslab/edit/head.html');
        checkEmbVisit($embryoslab_id);
        $this->loadOne($embryoslab_id);
        $this->smarty->display('embryoslab/edit/foot.html');

        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadOne($embryoslab_id) {

        $embryoslab = R::getRow('select embryoslab.*  ,  clin.name as clinician_name  ,  visits.visitdate 
            
                from embryoslab 
                  left join   visits                                     on   embryoslab.visit_id   =   visits.id                
                left join   awusers   clin                       on   embryoslab.clinician_id   =  clin.user_id                 
                where embryoslab.id = ' . $embryoslab_id);

        $embryoslab['embryologist_name'] = getEmbDrName($embryoslab['embryologist_id'],
                $embryoslab['embryologist_id_tb']);
        $embryoslab['icsi_name'] = getEmbDrName($embryoslab['icsi_by'], $embryoslab['icsi_by_tb']);

        $embryoslab['freeze_embryologist_name'] = getEmbDrName($embryoslab['freeze_embryologist_id'],
                $embryoslab['freeze_embryologist_id_tb']);


        $compSelectArray = explode(',', $embryoslab['media']);
        $embryoslab['media'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['oil']);
        $embryoslab['oil'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['incubator']);
        $embryoslab['incubator'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['injection_embrologist']);
        $embryoslab['injection_embrologist'] = $compSelectArray;


        if ($embryoslab['date'] == '0000-00-00' || is_null($embryoslab['date']) || $embryoslab['date'] == '') {
            $embryoslab['date'] = '';
        } else {
            $embryoslab['date'] = date('Y/m/d', strtotime($embryoslab['date']));
        }

        $this->smarty->assign('updatedate', $embryoslab);
        $this->smarty->assign('embryoslab_id', $embryoslab_id);
        $this->smarty->assign('patientId', $embryoslab['patient_id']);

        $this->semen($embryoslab['referred_dr_id'], $embryoslab['refer_doctor_tb'], $embryoslab['visit_id']);
        $this->oocyte();
        $this->smarty->display('embryoslab/edit/cancel.html');
        $this->sexSelection($embryoslab_id);
        $this->smarty->display('embryoslab/edit/tab_head.html');
        $this->scoring($embryoslab_id, $embryoslab['media'], $embryoslab['oil'], $embryoslab['incubator'], $embryoslab['injection_embrologist']);
        $this->transfer($embryoslab_id);
        $this->freezing($embryoslab_id, $embryoslab['patient_id']);
        $this->smarty->display('embryoslab/edit/tab_foot.html');
        $this->lot($embryoslab_id);
    }

    function semen($referred_dr_id, $refer_doctor_tb, $visit_id) {
        $ref_dr = getReferredDrName($referred_dr_id, $refer_doctor_tb);
        $this->smarty->assign('ref_dr', $ref_dr);

        $visit_rfc = getVisitRfc($visit_id);
        $this->smarty->assign('visit_rfc', $visit_rfc);

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

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

        $this->smarty->display('embryoslab/edit/semen.html');
    }

    function oocyte() {

        $tables = array("cancel_reason", "oocytequality", "oocytezona", "oocytecytoplasm", "oocytepvs"
            , "oocyteother", "growthmedia", "growthoil", "growthincubator", "growthco2"
            , "embryo_lot_select", "embryo_catheter_select", "embryo_device", "injection"
            , "embryo_tank", "embryo_kit_type", "embryo_result", "embryo_emb", "injection_location");

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

        $sql = ' (  SELECT user_id as id  ,   name   FROM awusers    WHERE role_id =   11  )  ';
        $sql .= '  union all ';
        $sql .= ' (select  CONCAT("*", id ) as  id  , name from embryologist  where deleted = 0  order by name  )';
        $injection_embrologist = R::getAll($sql);
        $this->smarty->assign('injection_embrologist', $injection_embrologist);

        $this->smarty->display('embryoslab/edit/oocyte.html');
    }

    function sexSelection($embryoslab_id) {
        $selections = R::getAll('select* from embryoselection where deleted = 0 
                and embryoslab_id = ?  ', [$embryoslab_id]);

        $this->smarty->assign('selections', $selections);
        $this->smarty->assign('selectionsCount', count($selections));

        $this->smarty->display('embryoslab/edit/selection.html');
    }

    function scoring($embryoslab_id, $emb_media, $emb_oil, $emb_incubator, $emb_embrologist) {
        $scoring = R::findAll("embryoscoring", "embryoslab_id= ?  and deleted != 1 ", [$embryoslab_id]);

        foreach ($scoring as $score) {
            for ($i = 1; $i <= 6; $i++) {
                $mediaName = 'media' . $i;
                $oilName = 'oil' . $i;
                $incubatorName = 'incubator' . $i;
                $embrologistName = 'embrologist' . $i;


                if (count($emb_media) == 1 && $emb_media[0] > 0 &&
                        ($score->$mediaName == '' || is_null($score->$mediaName))) {
                    R::exec("update  embryoscoring  set  $mediaName  =  $emb_media[0]   WHERE id = $score->id");
                    $score->$mediaName = $emb_media[0];
                }

                if (count($emb_oil) == 1 && $emb_oil[0] > 0 &&
                        ($score->$oilName == '' || is_null($score->$oilName))) {
                    R::exec("update  embryoscoring  set  $oilName  =  $emb_oil[0]   WHERE id = $score->id");
                    $score->$oilName = $emb_oil[0];
                }

                if (count($emb_incubator) == 1 && $emb_incubator[0] > 0 &&
                        ($score->$incubatorName == '' || is_null($score->$incubatorName))) {
                    R::exec("update  embryoscoring  set  $incubatorName  =  $emb_incubator[0]   WHERE id = $score->id");
                    $score->$incubatorName = $emb_incubator[0];
                }

                $selectArray = explode(',', $score->$mediaName);
                $score->$mediaName = $selectArray;

                $selectArray = explode(',', $score->$oilName);
                $score->$oilName = $selectArray;

                $selectArray = explode(',', $score->$incubatorName);
                $score->$incubatorName = $selectArray;

                $selectArray = explode(',', $score->$embrologistName);
                $score->$embrologistName = $selectArray;
            }
        }
        $this->smarty->assign('scoring', $scoring);

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

        $this->scoringSelects($emb_media, $emb_oil, $emb_incubator, $emb_embrologist);

        $this->smarty->display('embryoslab/edit/scoring_head.html');
        $this->smarty->display('embryoslab/edit/scoring_day2.html');
        $this->smarty->display('embryoslab/edit/scoring_day3.html');
        $this->smarty->display('embryoslab/edit/scoring_day4.html');
        $this->smarty->display('embryoslab/edit/scoring_day5.html');
        $this->smarty->display('embryoslab/edit/scoring_day6.html');
        $this->smarty->display('embryoslab/edit/scoring_foot.html');
    }

    function scoringSelects($emb_media, $emb_oil, $emb_incubator, $emb_embrologist) {
        $stages = R::findAll("stage");
        $this->smarty->assign('stages', $stages);

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

        $emb1 = ' 0 ';
        $emb2 = ' 0 ';
        foreach ($emb_embrologist as $value) {
            $value = trim($value);
            $x = $value[0];

            if ($x == '*') {
                $value = ltrim($value, '*');
                if ($value > 0) {
                    $emb1 .= ' , ' . $value;
                }
            } else {
                if ($value > 0) {
                    $emb2 .= ' , ' . $value;
                }
            }
        }

        $emb_media = implode(',', $emb_media);
        $emb_oil = implode(',', $emb_oil);
        $emb_incubator = implode(',', $emb_incubator);
        //   $emb_embrologist = implode(',', $emb_embrologist);

        if ($emb_media != '' && !(is_null($emb_media))) {
            $media = R::findAll("growthmedia", " deleted != 1 and id in  ( $emb_media ) ");
            $this->smarty->assign('scoring_media', $media);
        }

        if ($emb_oil != '' && !(is_null($emb_oil))) {
            $oil = R::findAll("growthoil", " deleted != 1 and id  in  ( $emb_oil  ) ");
            $this->smarty->assign('scoring_oil', $oil);
        }

        if ($emb_incubator != '' && !(is_null($emb_incubator))) {
            $incubator = R::findAll("growthincubator", " deleted != 1 and id  in ( $emb_incubator  ) ");
            $this->smarty->assign('scoring_incubator', $incubator);
        }


        $sql = "(  SELECT user_id as id  ,   name   FROM awusers    WHERE role_id =   11 
                and user_id  in ( $emb2    )  )  ";
        $sql .= " union all  ";
        $sql .= "(select  CONCAT(' * ', id ) as  id  , name from embryologist  where deleted = 0  
                 and id  in ( $emb1   ) )   ";
        $embrologist = R::getAll($sql);

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

    function transfer($embryoslab_id) {
        $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);

        $transfer = R::findOne("embryotransfer", "embryoslab_id=$embryoslab_id");

        if ($transfer) {
            $cl = R::getRow("select name from awusers where user_id=" . $transfer->clinician_id);

            $transfer->clinician_name = $cl['name'];
            $transfer->embryologist_name = getEmbDrName($transfer->embryologist_id
                    , $transfer->embryologist_id_tb);
        }


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


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

        $this->smarty->display('embryoslab/edit/transfer.html');
    }

    function freezing($embryoslab_id, $patientid) {
        $cells = $this->loadCellsDisplay($embryoslab_id);
        $this->smarty->assign('cells', $cells);


//             # tanks
//        $tanks = R::findAll('tanks');
//        $this->smarty->assign('tanks', $tanks);
//
//        // get tank cell for patient
//        $tank_cells = R::getAll('select DISTINCT tank_id,up_level_name,cell_name,patient_id,tanks.name ,tanks.tank_type
//                from tankcells inner join tanks on tankcells.tank_id = tanks.id where patient_id =  ? and tank_type = 1', [$patientid]);
//        $this->smarty->assign('tank_cells', $tank_cells);
//        $tank_cells_2 = R::getAll('select DISTINCT tank_id,up_level_name,cell_name,patient_id,tanks.name ,tanks.tank_type,cell_part_name 
//                from tankcells inner join tanks on tankcells.tank_id = tanks.id where patient_id =  ? and tank_type = 2', [$patientid]);
//        $this->smarty->assign('tank_cells_2', $tank_cells_2);

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

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

        $embryothawing = R::getAll(" select * from embryothawing where 
                embryofreezing_id = $embryoslab_id ");
        $this->smarty->assign('embryothawing', $embryothawing);

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

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


        $this->smarty->display('embryoslab/edit/freezing.html');
    }

    function lot() {
        $this->smarty->display('embryoslab/edit/lot.html');
    }

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

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

        $name = filter_input(INPUT_GET, "term");
        $role_id = filter_input(INPUT_GET, "role_id");

        $clinician = R::getAll('SELECT user_id as id  ,   name 
            FROM awusers    WHERE role_id =   ' . $role_id . ' and   name  LIKE "%' . $name . '%"    limit 0,50  ');
//        echo $name . ' - ';
        echo json_encode($clinician);
    }

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

        $name = filter_input(INPUT_GET, "term");
        $role_id = filter_input(INPUT_GET, "role_id");
        $ext = filter_input(INPUT_GET, "ext");
        $extSql = '';

        $sql = ' (  SELECT user_id as id  ,   name 
            FROM awusers    WHERE role_id =   ' . $role_id . ' and   name  LIKE "%' . $name . '%"    limit 0,30 )  ';

        if ($role_id == 11) {
            $sql .= '  union all ';
            $sql .= ' (select  CONCAT("*", id ) as  id  , name from embryologist  where deleted = 0 
                       and   name  LIKE "%' . $name . '%"    order by name  limit 0,30 )';
            switch ($ext) {
                case 1:      ##  transfer
                    break;

                case 2:      ##  transfer
                    break;

                case 3:      ##  freeze
                    break;
            }
        }



        $clinician = R::getAll($sql);
//        echo $name . ' - ';
        echo json_encode($clinician);
    }

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

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

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

        $em_lab_new = R::findOne('embryoslab', 'patient_id = ? and not_confirm = 0', [$patientid]);

        $count_em_lab = R::count('embryoslab', 'patient_id = ? and not_confirm = 0', [$patientid]);
        if ($count_em_lab > 0) {
            //create new to save
            $em_lab_new->not_confirm = 1;
            R::store($em_lab_new);
        }

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

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

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

        $addstage = R::dispense('stage');
        $addstage->stage = $stage;
        $inserted = R::store($addstage);
        echo $inserted;
    }

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

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

        $addgrade = R::dispense('grade');
        $addgrade->grade = $grade;
        $inserted = R::store($addgrade);
        echo $inserted;
    }

    public function addToTable() {

        $name = filter_input(INPUT_POST, 'name');
        $tablename = filter_input(INPUT_POST, 'tablename');
        $newdata = R::xdispense($tablename);
        $newdata->name = $name;
        $inserted = R::store($newdata);
        echo $inserted;
    }

    public function getprint() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $embryoslab_id = filter_input(INPUT_POST, 'id');
        $patientId = filter_input(INPUT_POST, 'patientid');
        $patientData = R::load("patients", $patientId);

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

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


        $embryoslab = R::load("embryoslab", $embryoslab_id);


        $embryoslab->date = date('Y/m/d', strtotime($embryoslab->date));

        $ref_by_dr_id = $embryoslab->referred_dr_id;
        $clinician_id = $embryoslab->clinician_id;
        $embryologist_id = $embryoslab->embryologist_id;

        $ref_by_dr_name = R::getRow('select name from awusers where user_id = ' . $ref_by_dr_id);
        $this->smarty->assign('ref_by_dr_name', $ref_by_dr_name["name"]);
        $clinician_name = R::getRow('select name from awusers where user_id = ' . $clinician_id);
        $this->smarty->assign('clinician_name', $clinician_name["name"]);
        $embryologist_name = R::getRow('select name from awusers where user_id = ' . $embryologist_id);
        $this->smarty->assign('embryologist_name', $embryologist_name["name"]);
//        print_r($embryoslab);
        $this->smarty->assign('updatedate', $embryoslab);
//        $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  and deleted != 1");
        $this->smarty->assign('scoring', $scoring);

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

        $embryofreezing = R::findAll("embryofreezing", "embryoslab_id=$embryoslab_id and deleted != 1 ");
        $this->smarty->assign('embryofreezing', $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);

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

    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");
        $data_selectid = filter_input(INPUT_POST, "data_selectid");

        $alldata = R::findAll($tableName, ' deleted != 1 ');

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

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

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

        $this->smarty->display('embryoslab/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::xdispense($table);
        $newtable->$columname = "";

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

        echo $insertid;
    }

//edit the new row of modal
    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");


        $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);
        $myData->deleted = 1;
        r::store($myData);
        echo 1;
    }

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

        //embryoslab table
        $colName = filter_input(INPUT_POST, "colName");
        $tablename = filter_input(INPUT_POST, "tablename");
        $value = filter_input(INPUT_POST, "value");
        $row_id = filter_input(INPUT_POST, 'row_id');
        $multiple = filter_input(INPUT_POST, 'multiple');

        if (!empty($row_id)) {
//            //here the update embryoslab table
            $embryo = R::load($tablename, $row_id);
        } else {
            $embryo = R::xdispense($tablename);
        }

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

        if ($tablename == 'embryoslab' && $colName == 'icsi_by' && $value[0] == "*") {
            $value = ltrim($value, '*');
            $embryo->icsi_by_tb = 1;
        }
        ##
        elseif ($tablename == 'embryoslab' && $colName == 'embryologist_id' && $value[0] == "*") {
            $value = ltrim($value, '*');
            $embryo->embryologist_id_tb = 1;
        }
        ##
        elseif ($tablename == 'embryoslab' && $colName == 'freeze_embryologist_id' && $value[0] == "*") {
            $value = ltrim($value, '*');
            $embryo->freeze_embryologist_id_tb = 1;
        }
        ##
        elseif ($tablename == 'embryotransfer' && $colName == 'embryologist_id' && $value[0] == "*") {
            $value = ltrim($value, '*');
            $embryo->embryologist_id_tb = 1;
        }

        if ($tablename == 'embryoslab' && $colName == 'cancelled' && $value == 1) {
            $embryo->cancelled_user = $_SESSION['user_id'];
        }

        if ($tablename == 'embryoslab' && $colName == 'cancelled' && $value != 1) {
            $embryo->cancelled_reverse_user = $_SESSION['user_id'];
        }


        $embryo->$colName = $value;

        $result = R::store($embryo);
        if ($result) {
            echo $result;
        }
    }

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

        //embryoslab table

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

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


        if (!empty($table_row_id)) {
//            //here the update embryoslab table
            $embryo = R::load($tablename, $table_row_id);
        } else {
            $embryo = R::xdispense($tablename);
        }

        $embryo->$colName = $value;

        $result = R::store($embryo);
        if ($result) {
            echo $result;
        }
    }

    public function insertNewRow() {
        //embryoscoring table

        $row_id = filter_input(INPUT_POST, 'row_id');
        $myItra = filter_input(INPUT_POST, 'myItra');
        $tablename = filter_input(INPUT_POST, "tablename");
//
//
        $embryo = R::xdispense($tablename);
        $embryo->embryoslab_id = $row_id;

        $result = R::store($embryo);
        if ($result) {
            switch ($tablename) {
                case 'embryoselection':
                    $embryo_result = R::findAll("embryo_result", ' deleted != 1 ');
                    $this->smarty->assign('embryo_result', $embryo_result);

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

                    $this->smarty->assign('myItra', $myItra);
                    $this->smarty->assign('row_id', $result);

                    $this->smarty->display('embryoslab/edit/selection_row.html');
                    break;

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

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

                    $this->smarty->assign('myItra', $myItra);
                    $this->smarty->assign('row_id', $result);

                    $this->smarty->display('embryoslab/scoringRow.html');
                    break;
            }
        }
    }

    public function insertNewFreezing() {
        //embryoscoring table

        $row_id = filter_input(INPUT_POST, 'row_id');
        $itr = filter_input(INPUT_POST, 'Itr');
        $tablename = filter_input(INPUT_POST, "tablename");
//
//
        $embryo = R::xdispense($tablename);
        $embryo->embryoslab_id = $row_id;

        $result = R::store($embryo);
        if ($result) {
            $stages = R::findAll("stage");
            $this->smarty->assign('stages', $stages);

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

            $this->smarty->assign('row_id', $result);

            $this->smarty->display('embryoslab/freezingRow.html');
        }
    }

    public function updateRow() {
        //update data row
        $patientid = filter_input(INPUT_POST, "patientid");
        $colName = filter_input(INPUT_POST, "colName");
        $tablename = filter_input(INPUT_POST, "tablename");
        $value = filter_input(INPUT_POST, "value");
        $row_id = filter_input(INPUT_POST, 'row_id');
        $multiple = filter_input(INPUT_POST, 'multiple');


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

//            //here the update embryoslab table
        $embryo = R::load($tablename, $row_id);
        $embryo->$colName = $value;
        $result = R::store($embryo);
        if ($result) {
            echo $result;
        }
    }

    public function delRowFromTable() {

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

        echo 1;
    }

    public function updateTransferTable() {

        //embryoslab table
        $patientid = filter_input(INPUT_POST, "patientid");
        $colName = filter_input(INPUT_POST, "colName");
        $tablename = filter_input(INPUT_POST, "tablename");
        $value = filter_input(INPUT_POST, "value");

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



        $embryodata = R::findOne($tablename, 'embryoslab_id=' . $row_id . '');
        print_r($embryodata->id);

        if (!empty($embryodata)) {
            $embryo = R::load($tablename, $embryodata->id);
        } else {
            $embryo = R::xdispense($tablename);
            $embryo->embryoslab_id = $row_id;
        }

        if ($tablename == 'embryotransfer' && $colName == 'embryologist_id' && $value[0] == "*") {
            $value = ltrim($value, '*');
            $embryo->embryologist_id_tb = 1;
        }
        $embryo->$colName = $value;

        $result = R::store($embryo);
        if ($result) {
            echo $result;
        }
    }

    //////new row/////////
    public function drawRow() {       ## new row without database insert
        $type = filter_input(INPUT_POST, "type");   ## ussimple or uscomplete or usantenatal
        $itr = filter_input(INPUT_POST, "itr");
        $lab_id = filter_input(INPUT_POST, "lab_id");
        $patientId = filter_input(INPUT_POST, "patientId");


        $tablename = filter_input(INPUT_POST, "tableName");
        if ($type == "thawing") {
            #################################################################### Heba : ## Drugs Data   ##############################################################################

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

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


            $cathetrs = R::getAll("select* from cathetr");
            $this->smarty->assign('cathetrs', $cathetrs);
            $this->smarty->assign('itr', $itr);
            $this->smarty->assign('type', $type);

            $embryothawing = R::xdispense('embryothawing');
            $embryothawing->embryofreezing_id = $lab_id;
            $row_id = R::store($embryothawing);

            $this->smarty->assign('row_id', $row_id);
        } else {
            $stages = R::getAll("select* from stage");
            $this->smarty->assign('stages', $stages);

            $grades = R::getAll("select* from grade");
            $this->smarty->assign('grades', $grades);
            $this->smarty->assign('itr', $itr);
            $this->smarty->assign('type', $type);
        }
        if ($tablename == "embryothawing") {
            $this->smarty->display('embryofreezing/newrowUS.html');
        } else {
            $this->smarty->display('embryofreezing/newrowUS_1.html');
        }
    }

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

        $value = filter_input(INPUT_POST, 'value');
        $table = filter_input(INPUT_POST, 'table');

        $add = R::xdispense($table);
        if ($table == 'colors') {
            $add->color_name = $value;
        } else {
            $add->name = $value;
            $add->deleted = 0;
        }
        $inserted = R::store($add);
        echo $inserted;
    }

    public function fertilizedData() {
        //check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $itr = (filter_input(INPUT_POST, 'itr') > 0) ? filter_input(INPUT_POST, 'itr') : 0;
        $embryoslab_id = filter_input(INPUT_POST, 'embryoslab_id');
        $scoring = R::findAll("embryoscoring", "embryoslab_id=$embryoslab_id and deleted != 1 ");
        $count_scoring = count($scoring);


        if ($itr != $count_scoring) {
            //    R::trashAll($scoring);
            R::exec("update  embryoscoring  set  deleted  = 1   WHERE embryoslab_id  = $embryoslab_id");
            $this->embryoScoringRows($itr, $embryoslab_id);
        }


        $scoring = R::findAll("embryoscoring", "embryoslab_id=$embryoslab_id  and deleted != 1");

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

        $embryoslab = R::getRow('select media , oil  ,  incubator , injection_embrologist    from embryoslab             
                where id = ' . $embryoslab_id);

        $compSelectArray = explode(',', $embryoslab['media']);
        $embryoslab['media'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['oil']);
        $embryoslab['oil'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['incubator']);
        $embryoslab['incubator'] = $compSelectArray;

        $compSelectArray = explode(',', $embryoslab['injection_embrologist']);
        $embryoslab['injection_embrologist'] = $compSelectArray;
        //  r::debug(true, 2);
        $this->scoringSelects($embryoslab['media'], $embryoslab['oil'], $embryoslab['incubator'], $embryoslab['injection_embrologist']);
        //   r::debug(false);
        $this->smarty->display('embryoslab/edit/scoring_tab.html');
    }

    function embryoScoringRows($itr, $embryoslab_id) {
        if ($itr > 0) {
            for ($index = 0; $index < $itr; $index++) {
                $existItr = $index + 1;
                $existItrObj = R::findone("embryoscoring", "embryoslab_id= $embryoslab_id and itr  = $existItr ");
                if (count($existItrObj) > 0) {
                    R::exec("update  embryoscoring  set  deleted  = 0   WHERE id  = $existItrObj->id");
                } else {
                    $firstZeroItrObj = R::findone("embryoscoring", "embryoslab_id= $embryoslab_id and itr  = 0 order by  id asc ");
                    if (count($firstZeroItrObj) > 0) {
                        R::exec("update  embryoscoring  set  deleted  = 0 , itr = $existItr   WHERE id  = $firstZeroItrObj->id");
                    } else {
                        $newObj = R::xdispense('embryoscoring');
                        $newObj->embryoslab_id = $embryoslab_id;
                        $newObj->itr = $existItr;
                        $newObj->deleted = 0;
                        R::store($newObj);
                    }
                }
            }
        }
    }

    public function getDate() {
        $day = filter_input(INPUT_POST, 'day');
        $embryoslab_id = filter_input(INPUT_POST, 'embryoslab_id');
        $embryoslab = R::load('embryoslab', $embryoslab_id);
        $visit = R::load('visits', $embryoslab->visit_id);

        if ($day > 0 && $visit->id > 0) {
            $end = date("Y/m/d", strtotime("+ $day days", strtotime($visit->visitdate)));
            echo $end;
        }
    }

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

        $itr = (filter_input(INPUT_POST, 'itr') > 0) ? filter_input(INPUT_POST, 'itr') : 0;
        $embryoslab_id = filter_input(INPUT_POST, 'embryoslab_id');
        $embryofreezing = R::findAll("embryofreezing", "embryoslab_id=$embryoslab_id and deleted != 1 ");
        $count_freezing = count($embryofreezing);

        if ($itr != $count_freezing) {
            //    R::trashAll($embryofreezing);
            R::exec("update  embryofreezing  set  deleted  = 1   WHERE embryoslab_id  = $embryoslab_id");
            $this->embryoFreezingRows($itr, $embryoslab_id);
        }

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

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

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

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

        $this->smarty->display('embryoslab/edit/straw_table.html');
    }

    function embryoFreezingRows($itr, $embryoslab_id) {
        if ($itr > 0) {
            for ($index = 0; $index < $itr; $index++) {
                $existItr = $index + 1;
                $existItrObj = R::findone("embryofreezing", "embryoslab_id= $embryoslab_id and itr  = $existItr ");
                if (count($existItrObj) > 0) {
                    R::exec("update  embryofreezing  set  deleted  = 0   WHERE id  = $existItrObj->id");
                } else {
                    $firstZeroItrObj = R::findone("embryofreezing", "embryoslab_id= $embryoslab_id and itr  = 0 order by  id asc ");
                    if (count($firstZeroItrObj) > 0) {
                        R::exec("update  embryofreezing  set  deleted  = 0 , itr = $existItr   WHERE id  = $firstZeroItrObj->id");
                    } else {
                        $newObj = R::xdispense('embryofreezing');
                        $newObj->embryoslab_id = $embryoslab_id;
                        $newObj->itr = $existItr;
                        $newObj->deleted = 0;
                        R::store($newObj);
                    }
                }
            }
        }
    }

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

    public function tankLocationDisplay() {
//check login
        autho::checkautho($this->hosturl);
        $embryosLabId = filter_input(INPUT_POST, "embryosLabId");
        $cells = $this->loadCellsDisplay($embryosLabId);
        $this->smarty->assign('cells', $cells);
        $this->smarty->display('embryoslab/edit/cells.html');
    }

    function loadCellsDisplay($embryosLabId) {

        $cells = R::getAll('select tank_cell , location , btn_no , row_no , col_no  , cell_no 
                                        from embryoslab_tank_cells where deleted = 0 
                                         and embryoslab_id = ?  ', [$embryosLabId]);
        $i = 0;
        foreach ($cells as $cell) {
            $tanks_general = R::findOne('tanks_general', '  location = ?  and btn_no = ?  ', [$cell['location'], $cell['btn_no']]);
            $cells[$i]['rows_letter'] = $tanks_general->rows_letter;
            $i++;
        }
        return $cells;
    }

    public function tankLocation() {
//check login
        autho::checkautho($this->hosturl);
        $specTabId = filter_input(INPUT_POST, "specTabId");
        $specCanId = filter_input(INPUT_POST, "specCanId");
        $preview = filter_input(INPUT_POST, "preview");

        $this->smarty->assign('specTabId', $specTabId);
        $this->smarty->assign('specCanId', $specCanId);
        $this->smarty->assign('preview', $preview);

        $this->tankLocationSetting();
        $this->smarty->display('embryoslab/edit/tank_location.html');
    }

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

//        $colors = array("#8db3e2", "#c4bc96", "#e5b8b7", "#d6e3bc", "#ccc0d9", "#b6dde8", "#fbd4b4", "#ffff66", "#ffccff");
//        $this->smarty->assign('colors', $colors);
        $this->tankLocationSetting();

        $tanks_generalsA = R::findAll("tanks_general", '  location = "A"  order by  id asc  ');
        foreach ($tanks_generalsA as $tanks_general) {
            for ($i = 1; $i <= 9; $i++) {
                $col = 'row' . $i . '_color';
                $colLetter = 'color' . $i . '_letter';
                $colName = 'color' . $i . '_name';
                $color = R::load("colors", $tanks_general->$col);
                $tanks_general->$colName = $color->color_name;
                $tanks_general->$colLetter = $color->color_letter;
            }
        }

        $tanks_generalsB = R::findAll("tanks_general", '  location = "B"  order by  id asc  ');
        foreach ($tanks_generalsB as $tanks_general) {
            for ($i = 1; $i <= 9; $i++) {
                $col = 'row' . $i . '_color';
                $colLetter = 'color' . $i . '_letter';
                $colName = 'color' . $i . '_name';
                $color = R::load("colors", $tanks_general->$col);
                $tanks_general->$colName = $color->color_name;
                $tanks_general->$colLetter = $color->color_letter;
            }
        }


        $this->smarty->assign('tanks_generalsA', $tanks_generalsA);
        $this->smarty->assign('tanks_generalsB', $tanks_generalsB);

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

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

    function tankLocationSetting() {
        for ($i = 1; $i <= 21; $i++) {
            $tanks_generalA = R::findOne('tanks_general', '  location = "A"  and btn_no = ' . $i);
            if (count($tanks_generalA) <= 0) {
                $tanks_generalA = R::xdispense('tanks_general');
                $tanks_generalA->location = "A";
                $tanks_generalA->btn_no = $i;
                R::store($tanks_generalA);
            }


            $tanks_generalB = R::findOne('tanks_general', '  location = "B"  and btn_no = ' . $i);
            if (count($tanks_generalB) <= 0) {
                $tanks_generalB = R::xdispense('tanks_general');
                $tanks_generalB->location = "B";
                $tanks_generalB->btn_no = $i;
                R::store($tanks_generalB);
            }
        }
    }

    function tankCanSetting($location, $btn_no) {
        $tanks_general = R::findOne('tanks_general', '  location = ?  and btn_no = ?  ', [$location, $btn_no]);
        for ($i = 1; $i <= 9; $i++) {
            $col = 'row' . $i . '_color';
            $colLetter = 'color' . $i . '_letter';
            $colName = 'color' . $i . '_name';
            $color = R::load("colors", $tanks_general->$col);
            $tanks_general->$colName = $color->color_name;
            $tanks_general->$colLetter = $color->color_letter;
        }
        $this->smarty->assign('tanks_general', $tanks_general);
        //   print_r($tanks_general);
    }

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

        $embryosLabId = filter_input(INPUT_POST, "embryosLabId");
        $preview = filter_input(INPUT_POST, "preview");
        $location = filter_input(INPUT_POST, "location");
        $no = filter_input(INPUT_POST, "no");

        $this->tankCanSetting($location, $no);
        if ($preview != 1) {
            $this->tankCanDetails($embryosLabId, $location, $no);
        } else {
            $this->smarty->assign('patCells', array());
            $this->smarty->assign('otherCells', array());
        }

        $this->smarty->assign('no', $no);
        $this->smarty->assign('location', $location);
        $this->smarty->assign('preview', $preview);
        $this->smarty->display('embryoslab/edit/tank_cans.html');
    }

    function tankCanDetails($embryosLabId) {
        $cells = R::getAll('select tank_cell  from embryoslab_tank_cells where deleted = 0 
                and embryoslab_id = ?  ', [$embryosLabId]);

        $other_cells = R::getAll('select tank_cell  from embryoslab_tank_cells where deleted = 0 
                and embryoslab_id != ?  ', [$embryosLabId]);

        #########################################
        $patCells = array();
        $otherCells = array();

        foreach ($cells as $value) {
            $tank_cell = trim($value['tank_cell']);
            array_push($patCells, $tank_cell);
        }
        $this->smarty->assign('patCells', $patCells);

        foreach ($other_cells as $value) {
            $tank_cell = trim($value['tank_cell']);
            array_push($otherCells, $tank_cell);
        }
        $this->smarty->assign('otherCells', $otherCells);

        #########################################
    }

    public function saveTankLocation() {
//check login
        autho::checkautho($this->hosturl);
        $embryosLabId = filter_input(INPUT_POST, "embryosLabId");
        $selectedCells = json_decode(stripslashes(filter_input(INPUT_POST, 'selectedCells')));
        $errorMsg = ' ';
        $error = 0;
        $ids = '';
        $location = filter_input(INPUT_POST, "location");
        $btn_no = filter_input(INPUT_POST, "no");

        if (count($selectedCells) > 0) {

            foreach ($selectedCells as $cell) {
                $notEmpty = R::findOne('embryoslab_tank_cells', 'deleted = 0   and location = ?  and btn_no = ?
                and row_no = ?  and col_no = ?  and cell_no = ? and  embryoslab_id != ?  '
                                , [$cell[0], $cell[1], $cell[2], $cell[3], $cell[4], $embryosLabId]);
                if (count($notEmpty) > 0) {
                    $errorMsg = $cell[0] . ' _' . $cell[1] . ' _' . $cell[2] . ' _' . $cell[3] . ' _' . $cell[4] . '  reserved to another Patient';
                    $error = 1;
                } else {
                    $resForMe = R::findOne('embryoslab_tank_cells', 'deleted = 0   and location = ?  and btn_no = ?
                and row_no = ?  and col_no = ?  and cell_no = ? and  embryoslab_id = ?  '
                                    , [$cell[0], $cell[1], $cell[2], $cell[3], $cell[4], $embryosLabId]);
                    if ($ids != '') {
                        $ids .= ' , ';
                    }
                    if (count($resForMe) > 0) {
                        $ids .= $resForMe->id;
                    } else {
                        $ids .= $this->storeTankCell($cell[0], $cell[1], $cell[2], $cell[3], $cell[4], $embryosLabId);
                    }
                }
            }

            R::exec('update  embryoslab_tank_cells set  deleted = 1  , userid_edit = ' . $_SESSION['user_id'] . ' 
               , date_edit = "' . date('Y-m-d H:i:s') . '"     where id  not in (' . $ids . ')  and embryoslab_id = ' . $embryosLabId . '   
                    and location = "' . $location . '"  and btn_no = "' . $btn_no . '" ');
        } else {
            R::exec('update  embryoslab_tank_cells set  deleted = 1  , userid_edit = ' . $_SESSION['user_id'] . ' 
               , date_edit = "' . date('Y-m-d H:i:s') . '"     where embryoslab_id = ' . $embryosLabId . ' 
                    and location = "' . $location . '"  and btn_no = "' . $btn_no . '" ');
        }

        if ($error != 1) {
            $errorMsg = ' saved Successfully ';
        }
        echo $errorMsg;
    }

    function storeTankCell($location, $btn_no, $row_no, $col_no, $cell_no, $embryoslab_id) {
        $add = R::xdispense('embryoslab_tank_cells');
        $add->embryoslab_id = $embryoslab_id;
        $add->location = $location;
        $add->btn_no = $btn_no;
        $add->row_no = $row_no;
        $add->col_no = $col_no;
        $add->cell_no = $cell_no;
        $add->date_add = date('Y-m-d H:i:s');
        $add->user_id = $_SESSION['user_id'];
        $add->tank_cell = $location . '_' . $btn_no . '_' . $row_no . '_' . $col_no . '_' . $cell_no;
        $add->deleted = 0;
        $id = R::store($add);
        return $id;
    }

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

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

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

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

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

    public function correctDates() {

        $detectTxt = '';
        $detections = R::findAll('detections', 'del = 0 and for_embryo = 1 ');
        $i = 0;
        foreach ($detections as $detection) {
            if ($i > 0) {
                $detectTxt .= ', ';
            }
            $detectTxt .= $detection->id;
            $i++;
        }



        $labs = R::findAll('embryoslab');
        foreach ($labs as $lab) {
            if ($detectTxt != '') {
                $visit = R::findOne('visits', 'patientid = ? and detectionid in ( ' . $detectTxt . ' )
                                 and visitdate <= ? and deleted != 1 order by visitdate desc '
                                , [$lab->patient_id, date('Y-m-d')]);
                if (count($visit) > 0) {
                    $lab->visit_id = $visit->id;
                    R::store($lab);
                }
            }

            print_r($lab->id);
            print_r('<br>');
        }
    }

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

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

}
