<?php

//session_start();
/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;

// 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 = 'index';
        $this->shcontrollname = 'Home';
        $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);


        require_once("../../_library/plugins/PHPMailer/PHPMailer.php");

# here show the active page in menu
// array called active[] with level of active element
        $active[0] = 'index'; //controller name or tab name
        $this->active = $active;


//here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

    //here the frist page and
    //the frist action in this class
    public function index() {
        // $this->rearrang_phone();
//        $this->retreive_rfc();
        $programesetting = $this->checkprogsetting();
        $focussearchindex = 0;
        $empty = filter_input(INPUT_GET, "empty");
        if ($empty == 1) {

            $focussearchindex = 1;
        }
        $this->smarty->assign('focussearchindex', $focussearchindex);
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        //autho::checkauthoize($this->controllname,$this->hosturl,$_SESSION['role_id']);

        $departs = R::findAll('awrole', 'visit_show = 1 ');
        //     if ($programesetting->system_type == 2) {

        $i = 1;
        foreach ($departs as $depart) {
            date_default_timezone_set('Africa/Cairo');
            $time = date('H', time());

            if ($time <= $programesetting->addshours) {
                $doctors = R::getAll('select distinct visits.for_doctor as docId , awusers.name   from  visits
                                join   awusers   on awusers.user_id =  visits.for_doctor      where  visits.visitdate in (? , ? )
                                and visits.deleted = ? and visits.for_department = ?  
                                 and visits.customer_add != 1  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $depart->id]);

                $visitCount = R::count('visits', 'visitdate in (? , ? )  and deleted = ? and visits.for_department = ?
                                and visits.customer_add != 1 ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $depart->id]);
            } else {
                $doctors = R::getAll('select distinct visits.for_doctor as docId , awusers.name   from  visits
                                join   awusers   on awusers.user_id =  visits.for_doctor      where  visits.visitdate = ?
                                and visits.deleted = ? and visits.for_department = ?  
                                 and visits.customer_add != 1', [date('Y-m-d'), 0, $depart->id]);

                $visitCount = R::count('visits', 'visitdate = ?  and deleted = ?   and visits.for_department = ?
                            and visits.customer_add != 1 ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $depart->id]);
            }

            $depart->doctors = $doctors;
            $depart->doctorsCount = count($doctors);
            $depart->visitCount = $visitCount;

            if ($i == 1) {
                $this->smarty->assign('firstDept', $depart->id);
                $this->smarty->assign('firstDoc', $doctors[0]['docId']);
            }

            $i++;
        }
        //   }
        $this->smarty->assign('departs', $departs);

        $awrole = R::load('awrole', $_SESSION['role_id']);
        $logUser = R::getRow('select * from awusers where user_id = ?', [$_SESSION['user_id']]);
        if ($awrole->redirect_to > 1 && $awrole->redirect_to != 6) {
            $index_redirect = R::load('index_redirect', $awrole->redirect_to);
            $link = $index_redirect->link;
        } else if ($awrole->redirect_to > 1 && $awrole->redirect_to == 6) {
            $link = -2;
        } else {
            $link = -1;
        }

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

        if ($logUser['show_all_visits'] == 1) {
            $this->smarty->assign('viewAll', -1);
        } else {
            $this->smarty->assign('viewAll', $awrole->index_visits_depts);
        }


        if (empty($awrole->index_visits_depts)) {
            $awrole->index_visits_depts = 0;
        } else {
            $departsFor = R::findAll('awrole', 'visit_show = 1  and  id in (  ' . $awrole->index_visits_depts . ' ) ');
            $i = 1;
            foreach ($departsFor as $depart) {
                date_default_timezone_set('Africa/Cairo');
                $time = date('H', time());

                if ($time <= $programesetting->addshours) {
                    $doctors = R::getAll('select distinct visits.for_doctor as docId , awusers.name   from  visits
                                join   awusers   on awusers.user_id =  visits.for_doctor      where  visits.visitdate in (? , ? )
                                and visits.deleted = ? and visits.for_department = ?  
                                 and visits.customer_add != 1  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $depart->id]);
                } else {
                    $doctors = R::getAll('select distinct visits.for_doctor as docId , awusers.name   from  visits
                                join   awusers   on awusers.user_id =  visits.for_doctor      where  visits.visitdate = ?
                                and visits.deleted = ? and visits.for_department = ?  
                                 and visits.customer_add != 1', [date('Y-m-d'), 0, $depart->id]);
                }

                $depart->doctors = $doctors;
                $depart->doctorsCount = count($doctors);

                if ($i == 1 && $logUser['show_all_visits'] != 1) {
                    $this->smarty->assign('firstDept', $depart->id);
                    $this->smarty->assign('firstDoc', $doctors[0]['docId']);
                }

                $i++;
            }

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

        if ($programesetting->system_type != 2) {

            ################## clinic   ##################
            date_default_timezone_set('Africa/Cairo');
            $time = date('H', time());
            $sql = ' and detectionid not in (-99 , 9999 , 999 )   ';
            $open = 0;
            $openF = 0;

            ## show custom visits
            if ($awrole->index_visits_depts != -1 && !empty($awrole->index_visits_depts) && $logUser['show_all_visits'] != 1) {
                $sql .= '  and ((  for_department   in (  ' . $awrole->index_visits_depts . ' ) ';
                $open = 1;
                $openF = 1;
            }

            ## show doctor  visits  only
            if ($awrole->user_visits_only == 1 && $logUser['show_all_visits'] != 1) {
                if ($open == 0) {
                    $sql .= '  and ( (   for_doctor   in (  ' . $_SESSION['user_id'] . ' ) ';
                    $open = 1;
                    $openF = 1;
                } else {
                    $sql .= '  and for_doctor   in (  ' . $_SESSION['user_id'] . ' ) ';
                }
            }

            if ($open == 1) {
                $sql .= ' ) ';
            }

            if ($awrole->custom_detections != null && !empty($awrole->custom_detections &&
                            $awrole->custom_detections != "" && $openF == 1)) {
                $sql .= '  ||  ( detectionid    in (  ' . $awrole->custom_detections . ' ) )   ';
            }

            if ($openF == 1) {
                $sql .= ' ) ';
            }


            //  R::debug(true, 2);
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ?  and customer_add != 1   ' . $sql . '
                                                  ORDER BY id ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
            } else {
                $allvisit = R::findAll('visits', 'visitdate = ?  and deleted = ?    and customer_add != 1
                             ' . $sql . '      ORDER BY id ASC  ', [date('Y-m-d'), 0]);
            }
            //   R::debug(false);

            foreach ($allvisit as $visit) {
                $patientName = R::findOne('patients', 'id = ? ', [$visit->patientid]);

                if ($visit->for_husband == 1) {
                    $visit->patientName = $patientName->husdandname;
                } elseif ($visit->for_husband == 2) {

                    $child = R::load('patients_childs', $visit->child);

                    if (is_null($child->child_name) || $child->child_name == '') {
                        if ($child->gender == 1) {
                            $visit->patientName = 'الطفل / ' . $patientName->wifename;
                        } else {
                            $visit->patientName = 'الطفلة / ' . $patientName->wifename;
                        }
                    } else {
                        $visit->patientName = $child->child_name . '  /  ' . $patientName->wifename;
                    }
                } else {
                    $visit->patientName = $patientName->wifename;
                }


                $visit->patientID = $patientName->id;
                $visit->statusno = $patientName->statusno;


                if ($visit->for_doctor > 0) {
                    $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
                    $visit->doctorName = $doctor['name'];
                } else {
                    $visit->doctorName = '';
                }

                if ($visit->detectionid != 0) {
                    switch ($visit->detectionid) {
                        case -99:
                            $visit->detectionType = 'دفع قسط';
                            break;

                        case 9999:
                            $originalVisit = R::load('visits', $visit->visitid);
                            $detection = R::load('detections', $originalVisit->detectionid);
                            $visit->detectionType = 'مرتجع العملاء';
                            $visit->detectionType .= ' ( ' . $detection->title . ' ) ';
                            break;

                        case 999:
                            $originalVisit = R::load('visits', $visit->visitid);
                            $detection = R::load('detections', $originalVisit->detectionid);
                            $visit->detectionType = 'دفع متبقى ';
                            $visit->detectionType .= ' ( ' . $detection->title . ' ) ';
                            break;

                        default:
                            $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
                            $visit->detectionType = $detection['title'];
                            break;
                    }
                } else {
                    $visit->detectionType = 'unknown';
                }

                if ($link == -2) {
                    $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit->patientid]);
                    if (!empty($lastVisitData)) {
                        $visit->link = $lastVisitData->control . '.php?ac=index&patientid=';
                    } else {
                        $visit->link = 'patienthistory.php?ac=index&patientid=';
                    }
                } else {
                    $visit->link = $link;
                }
                /* $antenatalData = R::findOne('antenalvisit', 'patientid = ? and conditions = 0 order by id desc limit 1', [$visit->patientid]);
                  $gynaData = R::findOne('gyna', 'patientid = ? and conditions = 0 order by id desc limit 1', [$visit->patientid]);
                  if (!empty($antenatalData) || !empty($gynaData)) {
                  if ($gynaData['gynadate'] < $antenatalData['antenaldate'])
                  $go = "antenatal";
                  else
                  $go = "gyna";
                  $visit->go = $go;
                  }
                  else
                  {
                  $visit->go = '';
                  } */
            }

            $this->smarty->assign('allvisit', $allvisit);
        } elseif ($programesetting->system_type == 2) {
            $this->loadShareVisits($programesetting);
        }

        //call other class with other content

        $loginPosition = R::getRow('select role_id from awusers where user_id = ?', [$_SESSION['user_id']]);
        $this->smarty->assign('loginPosition', $loginPosition['role_id']);
        if ($programesetting->visitsform == 1) {
            $allDetections = R::findAll('detections', 'del = 0');
            $this->smarty->assign('allDetections', $allDetections);
        }

        if (file_exists('../db_backups/opgy_' . date('Y-m-d') . '.sql')) {

            $this->smarty->assign('ifsend', 1);
        } else {
            $this->smarty->assign('ifsend', 0);
        }



        //get new features
        #options fast
        $fast_options = R::findAll('fastoptions');
        $this->smarty->assign('fast_options', $fast_options);

        $btn1 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 1  ', [$_SESSION['role_id']]);
        $btn2 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 2  ', [$_SESSION['role_id']]);

        $this->smarty->assign('showBtn1', $btn1->checkval);
        $this->smarty->assign('showBtn2', $btn2->checkval);


        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);

        if ($programesetting->system_type != 2) {
            $this->smarty->display('index.html');
        } else {
            $this->smarty->display('index_share.html');
        }

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

        $db_user = DB_USER;
        $db_password = DB_PASS;
        $dbname = DB_NAME;
        $host = DB_HOST;
        $newname = date("Y-m-d");

        if (file_exists('../db_backups/opgy_' . date('Y-m-d') . '.sql')) {
            
        } else {
            $inrtoi = "../db_backups/opgy_$newname.sql"; // check operating system
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'DAR') {
                //$path_mysqldump = '/Applications/AMPPS/mysql/bin/mysqldump';
                $path_mysqldump = '/Applications/MAMP/Library/bin/mysqldump';
            } else {
                $path_mysqldump = "$programesetting->backupdriver\mysqldump";
            }
            $command = "$path_mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";
            system($command);
        }
        if ($programesetting->backupdest) {
            if (file_exists("$programesetting->backupdest/opgy_$newname.sql")) {
                
            } else {
                $inrtoi = "$programesetting->backupdest/opgy_$newname.sql";
                $command = "$programesetting->backupdriver\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";
                system($command);
            }
        }
    }

    function rearrang_phone() {
        $patients = R::findAll('patients');
        foreach ($patients as $patient) {
            $phone = $patient->phone;
            $mobile = $patient->mobile;

            $patient->phone = $mobile;
            $patient->mobile = $phone;

            r::store($patient);
        }
    }

    function retreive_rfc() {
        $patients = R::findAll('patients', '   rfc is null and wrfc is null and done = 1 order by id desc');
        foreach ($patients as $patient) {
            $lastEdit = R::findOne('patients_updates', ' patientid_edit = ? and (rfc is not  null or  wrfc is not  null  )   order by id desc', [$patient->id]);
            if (count($lastEdit) > 0) {
                if ($lastEdit->wrfc > 0) {
                    $patient->wrfc = $lastEdit->wrfc;
                }

                if ($lastEdit->rfc > 0) {
                    $patient->rfc = $lastEdit->rfc;
                }
                r::store($patient);
            }
        }
    }

    function loadShareVisits($programesetting) {

        ################## clinic   ##################
        date_default_timezone_set('Africa/Cairo');
        $time = date('H', time());

        if ($time <= $programesetting->addshours) {
            ## iam now at extra time show yesterday visits  also
            $allvisit = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ?   ORDER BY id ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
        } else {
            $allvisit = R::findAll('visits', 'visitdate = ?  and deleted = ?   ORDER BY id  ASC  ', [date('Y-m-d'), 0]);
        }
        foreach ($allvisit as $visit) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit->patientid]);
            if ($visit->for_husband == 1) {
                $visit->patientName = $patientName->husdandname;
            } else {
                $visit->patientName = $patientName->wifename;
            }
            $visit->patientID = $patientName->id;
            $visit->statusno = $patientName->statusno;

            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
//            $visit->visitHour = $reserve->visit_hour;
            if (count($reserve) > 0) {
                $visit->visitHour = date('h:i A', strtotime($reserve->visit_hour));
            } else {
                $visit->visitHour = '';
            }




            if ($visit->for_department != "") {

                //get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

                $depart_name = R::load('awrole', $visit->for_department);
                if ($visit->for_doctor > 0) {
                    $visit->for_department_name = $depart_name->name . ' ( ' . $doctor['name'] . ' )';
                } else {
                    $visit->for_department_name = $depart_name->name;
                }
            }

            if ($visit->detectionid != 0) {
                $detection = R::findOne('detections', 'id = ? ', [$visit->detectionid]);
                $visit->detectionType = $detection->title;
            } else {
                $visit->detectionType = 'unknown';
            }

            /* $antenatalData = R::findOne('antenalvisit', 'patientid = ? and conditions = 0 order by id desc limit 1', [$visit->patientid]);
              $gynaData = R::findOne('gyna', 'patientid = ? and conditions = 0 order by id desc limit 1', [$visit->patientid]);
              if (!empty($antenatalData) || !empty($gynaData)) {
              if ($gynaData['gynadate'] < $antenatalData['antenaldate'])
              $go = "antenatal";
              else
              $go = "gyna";
              $visit->go = $go;
              }
              else
              {
              $visit->go = '';
              } */
            $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit->patientid]);
            if (!empty($lastVisitData))
                $visit->go = $lastVisitData->control;
        }


        if ($_SESSION['role_id'] == 4) {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and ((for_department = ? and for_doctor = ?) or for_department = 13)  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and ((for_department = ? and for_doctor = ?) or for_department = 13)   ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            }
        } elseif ($_SESSION['role_id'] == 8) {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and for_department = ? and for_doctor = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and for_department = ? and for_doctor = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            }
        } else {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and for_department = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and for_department = ?   ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id']]);
            }
        }

        foreach ($allvisit_for as $visit_for) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit_for->patientid]);
            if ($visit_for->for_husband == 1) {
                $visit_for->patientName = $patientName->husdandname;
            } else {
                $visit_for->patientName = $patientName->wifename;
            }
            $visit_for->patientID = $patientName->id;
            $visit_for->statusno = $patientName->statusno;
            if ($visit_for->detectionid != 0) {
                switch ($visit->detectionid) {
                    case -99:
                        $visit->detectionType = 'دفع قسط';
                        break;

                    case 9999:
                        $originalVisit = R::load('visits', $visit->visitid);
                        $detection = R::load('detections', $originalVisit->detectionid);
                        $visit->detectionType = 'مرتجع العملاء';
                        $visit->detectionType .= ' ( ' . $detection->title . ' ) ';
                        break;

                    case 999:
                        $originalVisit = R::load('visits', $visit->visitid);
                        $detection = R::load('detections', $originalVisit->detectionid);
                        $visit->detectionType = 'دفع متبقى ';
                        $visit->detectionType .= ' ( ' . $detection->title . ' ) ';
                        break;

                    default:
                        $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
                        $visit->detectionType = $detection['title'];
                        break;
                }
            } else {
                $visit_for->detectionType = 'unknown';
            }


            if ($visit_for->for_department != "") {

                //get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit_for->for_doctor]);

                $depart_name = R::load('awrole', $visit_for->for_department);
                if ($visit_for->for_doctor > 0) {
                    $visit_for->for_department_name = $depart_name->name . ' ( ' . $doctor['name'] . ' )';
                } else {
                    $visit_for->for_department_name = $depart_name->name;
                }
            }

            $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit_for->patientid]);
            if (!empty($lastVisitData))
                $visit_for->go = $lastVisitData->control;
        }


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

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

    public function getvisits() {
        $programesetting = $this->checkprogsetting();
        date_default_timezone_set('Africa/Cairo');
        $time = date('H', time());

        $this->smarty->assign('programesetting', $programesetting);
        //$time = $time+3;

        /* if($time > 12)
          $time = $time - 12; */

        if ($time <= $programesetting->addshours) {
            ## iam now at extra time show yesterday visits  also
            $allvisit = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ?   ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
        } else {
            $allvisit = R::findAll('visits', 'visitdate = ?  and deleted = ?   ORDER BY visitorder ASC  ', [date('Y-m-d'), 0]);
        }


        foreach ($allvisit as $visit) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit->patientid]);
            if ($visit->for_husband == 1) {
                $visit->patientName = $patientName->husdandname;
            } else {
                $visit->patientName = $patientName->wifename;
            }
            $visit->patientID = $patientName->id;
            $visit->statusno = $patientName->statusno;

            if ($visit->for_department != "") {

                //get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

                $depart_name = R::load('awrole', $visit->for_department);
                if ($visit->for_doctor > 0) {
                    $visit->for_department_name = $depart_name->name . ' ( ' . $doctor['name'] . ' )';
                } else {
                    $visit->for_department_name = $depart_name->name;
                }
            }

            if ($visit->detectionid != 0) {
                $detection = R::findOne('detections', 'id = ? ', [$visit->detectionid]);
                $visit->detectionType = $detection->title;
            } else {
                $visit->detectionType = 'unknown';
            }

            $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit->patientid]);
            if (!empty($lastVisitData))
                $visit->go = $lastVisitData->control;
        }


        if ($_SESSION['role_id'] == 4) {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and ((for_department = ? and for_doctor = ?) or for_department = 13)  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and ((for_department = ? and for_doctor = ?) or for_department = 13)   ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            }
        } elseif ($_SESSION['role_id'] == 8) {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and for_department = ? and for_doctor = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and for_department = ? and for_doctor = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id'], $_SESSION['user_id']]);
            }
        } else {
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit_for = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ? and for_department = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0, $_SESSION['role_id']]);
            } else {
                $allvisit_for = R::findAll('visits', 'visitdate = ?  and deleted = ?  and for_department = ?   ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, $_SESSION['role_id']]);
            }
        }
        foreach ($allvisit_for as $visit_for) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit_for->patientid]);
            if ($visit_for->for_husband == 1) {
                $visit_for->patientName = $patientName->husdandname;
            } else {
                $visit_for->patientName = $patientName->wifename;
            }
            $visit_for->patientID = $patientName->id;
            $visit_for->statusno = $patientName->statusno;
            if ($visit_for->detectionid != 0) {
                $detection = R::findOne('detections', 'id = ? ', [$visit_for->detectionid]);
                $visit_for->detectionType = $detection->title;
            } else {
                $visit_for->detectionType = 'unknown';
            }


            if ($visit_for->for_department != "") {

                //get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit_for->for_doctor]);

                $depart_name = R::load('awrole', $visit_for->for_department);
                if ($visit_for->for_department == 8 || $visit_for->for_department == 4 || $visit_for->for_department == 13) {
                    $visit_for->for_department_name = $depart_name->name . ' ( ' . $doctor['name'] . ' )';
                } else {
                    $visit_for->for_department_name = $depart_name->name;
                }
            }

            $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit_for->patientid]);
            if (!empty($lastVisitData))
                $visit_for->go = $lastVisitData->control;
        }

        $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->assign('allvisit_for', $allvisit_for);

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

        $this->smarty->display('visit_contain.html');
    }

    public function sortable() {
        $sortedData = filter_input(INPUT_POST, 'datasorted');
        $this->update($sortedData);
    }

    public function update($data) {
        parse_str($data, $str);
        $datasort = $str['item'];
        for ($i = 0; $i < count($datasort); $i++) {
            $allData = R::findOne('visits', 'id = ?', [$datasort[$i]]);
            $allData->visitorder = $i + 1;
            R::store($allData);
        }
        echo 'Successfully Updated!';
    }

    public function onesetup() {

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

        try {
            //delete all but with only default
            #1 clean roles only managment
            #2 clean menu only default
            #3 clean controls only default
            #4 users clean users
            #delete all menus
            $menus = R::findAll('awmenu', 'id > 15');
            #delete from awrolemenu
            foreach ($menus as $one) {
                //get propes
                $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
                R::trashAll($rolemenu);
            }
            R::trashAll($menus);
            #delete controles
            $controlls = R::findAll('awcontroll', 'id > 4 and id < 18');
            foreach ($controlls as $one) {
                //get propes
                $inprop = R::findAll('awcontrollprop', 'awcontroll_id = ?', [$one->id]);
                #delete from awrolecontroleprop
                foreach ($inprop as $one) {
                    //get propes
                    $roleprop = R::findAll('awrolecontrollprop', 'controllprop_id = ?', [$one->id]);
                    R::trashAll($roleprop);
                }
                R::trashAll($inprop);
            }
            R::trashAll($controlls);
            #delete othre roles
            $roles = R::findAll('awrole', 'id > 1');
            R::trashAll($roles);
            #delete other users
            //$users = R::findAll('awusers', 'user_id > 1');
            //R::exec('Delete from awusers where user_id > 1');
            //R::trashAll($users);
            ############################
            //new one
            $menusx = R::findAll('awmenu', ' id = 4 or id = 5 or id = 7 or id = 8 or id = 10 or id = 11 or id = 13 or id = 14 or id = 15 ');
            #delete from awrolemenu
            foreach ($menusx as $one) {
                //get propes
                $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
                R::trashAll($rolemenu);
            }
            R::trashAll($menusx);

            print_r('trash all , install is good');
        } catch (Exception $ex) {
            print_r('something go wrong  , try again');
        }
    }

    private function checkprogsetting() {    ## if prog setting exist otherwise create default one
        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('programesetting', $programesetting);

        if (count($programesetting) <= 0) {
            ## create default record
            $programesetting = R::dispense('programesetting');
            R::freeze('programesetting');

            try {
                R::store($programesetting);
            } catch (Exception $e) {
                header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
            }
        }
        return $programesetting;
    }

    public function sendmail() {
        //echo !extension_loaded('openssl')?"Not Available":"Available";
        //https://www.google.com/settings/security/lesssecureapps
        //turn it on

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

        $newname = date("Y-m-d");


        define('GUSER', $programesetting->email);
        define('GPWD', $programesetting->password);

        global $error;
        $mail = new PHPMailer();  // create a new object
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true;  // authentication enabled
        $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
        $mail->SMTPAutoTLS = false;
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;

        $mail->Username = GUSER;
        $mail->Password = GPWD;
        $mail->SetFrom($programesetting->email);
        $mail->Subject = "This is backup database for $newname";
        $mail->Body = 'You can download database backup and use it';
        $mail->addAttachment("../db_backups/opgy_$newname.sql");
        $mail->AddAddress($programesetting->email);
        if (!$mail->Send()) {
            //$error = 'Mail error: '.$mail->ErrorInfo;
            return false;
        } else {
            //$error = 'Message sent!';
            return true;
        }
    }

    public function operationresult() {
        $opera_id = filter_input(INPUT_POST, 'opera_id');
        $val_is = filter_input(INPUT_POST, 'val_is');

        $vist = R::load('visits', $opera_id);
        $vist->operation_result = $val_is;
        R::store($vist);
    }

    public function operationresultno() {
        $opera_id = filter_input(INPUT_POST, 'opera_id');
        $val_is = filter_input(INPUT_POST, 'val_is');

        $vist = R::load('visits', $opera_id);
        $vist->operation_result_no = $val_is;
        R::store($vist);
    }

    public function upmintest() {

        $drgs = R::findAll('storedrugsvalidation');
        foreach ($drgs as $dgs) {
            if ($dgs->currentbalance < 0) {
                $dgs->currentbalance = 0;
                R::store($dgs);
            }
        }
    }

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

        $search = (!filter_input(INPUT_POST, "search")) ? "" : filter_input(INPUT_POST, "search");

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

        $awrole = R::load('awrole', $_SESSION['role_id']);
        $logUser = R::getRow('select * from awusers where user_id = ?', [$_SESSION['user_id']]);
        if ($awrole->redirect_to > 1 && $awrole->redirect_to != 6) {
            $index_redirect = R::load('index_redirect', $awrole->redirect_to);
            $link = $index_redirect->link;
        } else if ($awrole->redirect_to > 1 && $awrole->redirect_to == 6) {
            $link = -2;
        } else {
            $link = -1;
        }

        $this->smarty->assign('link', $link);
        $ext = '';
        if (!empty($search) && $search != '') {
            $ext = " AND (patients.wifename  LIKE '%$search%'  OR patients.statusno  LIKE '%$search%'  OR patients.husdandname LIKE '%$search%') ";
        }

        $this->loadIndexVisits($programesetting, $awrole, $logUser, $link, $ext);
        $this->smarty->display('index_search.html');
    }

    function loadIndexVisits($programesetting, $awrole, $logUser, $link, $ext) {
        ################## clinic   ##################
        date_default_timezone_set('Africa/Cairo');
        $time = date('H', time());
        $sql = ' and visits.detectionid not in (-99 , 9999 , 999 )   ';
        $open = 0;
        $openF = 0;

        ## show custom visits
        if ($awrole->index_visits_depts != -1 && !empty($awrole->index_visits_depts) && $logUser['show_all_visits'] != 1) {
            $sql .= '  and ((  visits.for_department   in (  ' . $awrole->index_visits_depts . ' ) ';
            $open = 1;
            $openF = 1;
        }

        ## show doctor  visits  only
        if ($awrole->user_visits_only == 1 && $logUser['show_all_visits'] != 1) {
            if ($open == 0) {
                $sql .= '  and ( (   visits.for_doctor   in (  ' . $_SESSION['user_id'] . ' ) ';
                $open = 1;
                $openF = 1;
            } else {
                $sql .= '  and visits.for_doctor   in (  ' . $_SESSION['user_id'] . ' ) ';
            }
        }

        if ($open == 1) {
            $sql .= ' ) ';
        }

        if ($awrole->custom_detections != null && !empty($awrole->custom_detections &&
                        $awrole->custom_detections != "" && $openF == 1)) {
            $sql .= '  ||  ( visits.detectionid    in (  ' . $awrole->custom_detections . ' ) )   ';
        }

        if ($openF == 1) {
            $sql .= ' ) ';
        }


        //   R::debug(true, 2);
        if ($time <= $programesetting->addshours) {
            ## iam now at extra time show yesterday visits  also
            $allvisit = R::getAll('select visits.* 
                                                from visits 
                                                JOIN  patients ON visits.patientid =patients.id 
                                                where 
                                                visits. visitdate in (? , ? )  and visits.deleted = ?  and visits.customer_add != 1 
                                                ' . $sql . '   ' . $ext . '
                                                  ORDER BY id ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
        } else {
            $allvisit = R::getAll('select visits.* 
                                                from visits 
                                                JOIN  patients ON visits.patientid =patients.id 
                                                where 
                                                visits. visitdate = ?  and visits.deleted = ?  and visits.customer_add != 1 
                                                   ' . $sql . '   ' . $ext . '
                                                  ORDER BY id ASC  ', [date('Y-m-d'), 0]);
        }
        // R::debug(false);

        $x = 0;
        foreach ($allvisit as $visit) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit['patientid']]);
            //       $allvisit[$x]['link']                     $visit['visitid']
            if ($visit['for_husband'] == 1) {
                $allvisit[$x]['patientName'] = $patientName->husdandname;
            } elseif ($visit['for_husband'] == 2) {

                $child = R::load('patients_childs', $visit['child']);

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $allvisit[$x]['patientName'] = 'الطفل / ' . $patientName->wifename;
                    } else {
                        $allvisit[$x]['patientName'] = 'الطفلة / ' . $patientName->wifename;
                    }
                } else {
                    $allvisit[$x]['patientName'] = $child->child_name . '  /  ' . $patientName->wifename;
                }
            } else {
                $allvisit[$x]['patientName'] = $patientName->wifename;
            }


            $allvisit[$x]['patientID'] = $patientName->id;
            $allvisit[$x]['statusno'] = $patientName->statusno;


            if ($visit['for_doctor'] > 0) {
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit['for_doctor']]);
                $allvisit[$x]['doctorName'] = $doctor['name'];
            } else {
                $allvisit[$x]['doctorName'] = '';
            }

            if ($visit['detectionid'] != 0) {
                switch ($visit['detectionid']) {
                    case -99:
                        $allvisit[$x]['detectionType'] = 'دفع قسط';
                        break;

                    case 9999:
                        $originalVisit = R::load('visits', $visit['visitid']);
                        $detection = R::load('detections', $originalVisit->detectionid);
                        $allvisit[$x]['detectionType'] = 'مرتجع العملاء';
                        $allvisit[$x]['detectionType'] .= ' ( ' . $detection->title . ' ) ';
                        break;

                    case 999:
                        $originalVisit = R::load('visits', $visit['visitid']);
                        $detection = R::load('detections', $originalVisit->detectionid);
                        $allvisit[$x]['detectionType'] = 'دفع متبقى ';
                        $allvisit[$x]['detectionType'] .= ' ( ' . $detection->title . ' ) ';
                        break;

                    default:
                        $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit['detectionid'] . '"');
                        $allvisit[$x]['detectionType'] = $detection['title'];
                        break;
                }
            } else {
                $allvisit[$x]['detectionType'] = 'unknown';
            }

            if ($link == -2) {
                $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$visit['patientid']]);
                if (!empty($lastVisitData)) {
                    $allvisit[$x]['link'] = $lastVisitData->control . '.php?ac=index&patientid=';
                } else {
                    $allvisit[$x]['link'] = 'patienthistory.php?ac=index&patientid=';
                }
            } else {
                $allvisit[$x]['link'] = $link;
            }


            $x++;
        }

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

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

}
