<?php

/*
 * 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() {
        $programesetting = $this->checkprogsetting();
        ##session_start(); needed to set new session variable $_SESSION["erpDB"]
        session_start();
        $_SESSION["erpDB"] = $programesetting->erpdb;
        $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']);

        if ($programesetting->visitsform == 1) {       ################## hospital
            $allvisit = R::find('visits', 'visitdate = ? AND view  = ? and deleted = ?  ORDER BY visitorder ASC  ', [date('Y-m-d'), 0, 0]);

            foreach ($allvisit as $visit) {
                $patientName = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid"); // R::findOne('patients', 'id = ? ', [$visit->patientid]);
                $visit->patientName = $patientName['wifename'];
                $visit->patientID = $patientName['id'];

                if ($visit->detectionid == -99) {
                    $visit->detectionType = 'دفع قسط';
                } else {
                    $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
                    $visit->detectionType = $detection['title'];
                }

                /* $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";


                  }
                  else
                  {
                  $go = '';
                  } */
                $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc', [$visit->patientid]);
                if (!empty($lastVisitData))
                    $visit->go = $lastVisitData->control;
            }

            $allvisitentered = R::find('visits', 'visitdate = ? AND view  = ? and deleted = ? ORDER BY enterordered ASC  ', [date('Y-m-d'), 1, 0]);

            foreach ($allvisitentered as $visit) {
                $patientName = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");
                $visit->patientName = $patientName['wifename'];
                $visit->patientID = $patientName['id'];
                if ($visit->detectionid == -99) {
                    $visit->detectionType = 'دفع قسط';
                } else {
                    $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
                    $visit->detectionType = $detection['title'];
                }
            }
            $this->smarty->assign('allvisitentered', $allvisitentered);
        } else {                                        ################## clinic
            date_default_timezone_set('Africa/Cairo');
            $time = date('H', time());
            //$time = $time+3;

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

            $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
            $branchSql = ' ';
            if ($programesetting->branches == 1 && $user->branch_id != -1) {
                $branchSql = '  and visits.branch_id =  ' . $user->branch_id;
            }

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


            foreach ($allvisit as $visit) {
                $patientName = R::findOne('patients', 'id = ? ', [$visit->patientid]);
                $visit->patientName = $patientName->wifename;
                $visit->patientID = $patientName->id;
                $visit->statusno = $patientName->statusno;
                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 ($visit->approx_time != '' && $visit->approx_time != null && !empty($visit->approx_time)) {
                    $visit->approx_time = date("g:i A", strtotime($visit->approx_time));
                }

                /* $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 = ? order by id desc', [$visit->patientid]);
                if (!empty($lastVisitData))
                    $visit->go = $lastVisitData->control;
            }
        }


        //call other class with other content

        $visit_periods = R::findAll('visit_periods', 'deleted = 0');
        $this->smarty->assign('visit_periods', $visit_periods);

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

        $hasBranch = 0;
        if ($_SESSION['user_id'] > 0 && $programesetting->branches == 1) {
            $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
            if ($user->branch_id > 0) {
                $hasBranch = $user->branch_id;
            }
        }
        $this->smarty->assign('hasBranch', $hasBranch);

        $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->assign('visitPeriod', $programesetting->visit_period);
        $this->smarty->assign('visitBranches', $programesetting->branches);

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


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

        //   $this->visitsForSms();

        $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";
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'DAR') {
                $path_mysqldump = '/Applications/AMPPS/apps/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);
            }
        }

        /*
          ##### EXAMPLE #####
          EXPORT_DATABASE("localhost","user","pass","db_name" );

          ##### Notes #####
         * (optional) 5th parameter: to backup specific tables only,like: array("mytable1","mytable2",...)   
         * (optional) 6th parameter: backup filename (otherwise, it creates random name)
         * IMPORTANT NOTE ! Many people replaces strings in SQL file, which is not recommended. READ THIS:  http://puvox.software/tools/wordpress-migrator
         * If you need, you can check "import.php" too
         */

        //   $this->EXPORT_DATABASE($host, $db_user, $db_password, $dbname, false, "opgy_" . $newname . "_tt.sql");
    }

    function visitsForSms() {
        $minDate = date("Y-m-d", strtotime("-7 days"));
        $tomorrow = date("Y-m-d", strtotime("+1 day"));

        $sql = '      select    visits.id as  visitd  , patients.phone  , patients.wifename  , visits.visitdate        
                            from   visits   
                            join patients      on patients.id   = visits.patientid
                            where 
                            visits.visitdate = ? and visits.deleted = 0 and patients.deleted = 0     and visits.sms_send = 0
                            and  DATE(visits.createdate)   <= ?   and patients.phone != ""  and patients.phone IS NOT NULL
                ';
        $visits = R::getAll($sql, [$tomorrow, $minDate]);

        foreach ($visits as $visit) {
            $recipient = ltrim($visit['phone'], "2");
            $recipient = ltrim($recipient, "+2");
            $recipient = ltrim($recipient, "02");
            $recipient = ltrim($recipient, "002");
            $recipient = ltrim($recipient, "0");
            $phoneNoWithCode = "20" . ($recipient);
            $message = "";
            $message .= ' أ  /  ' . $visit['wifename'] . '   ';
            $message .= '  عيادة د/محمود جمعة تذكركم بموعد زيارة لكم بتاريخ    ' . $visit['visitdate'];
            $message .= '  برجاء الاتصال بنا  للتأكيد     ';
            $message .= '   01062610024 ';
            // $this->sendSms($phoneNoWithCode, $message);
            // R::exec('update visits set sms_send = 1 where id = ' . $visit['visitd']);
        }
    }

    function sendSms($phoneNo, $message) {
        $data = array(
            "recipient" => $phoneNo
            , "sender_id" => "DrMhmodGoma"
            , "type" => "plain"
            , "message" => $message
        );

        $buildQuery = http_build_query($data);
        $requestUrl = "https://bulk.whysms.com/api/v3/sms/send/?" . $buildQuery;

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt_array($curl, array(
            CURLOPT_URL => $requestUrl,
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array('Content-Type:application/json'
                , 'Accept: application/json'
                , 'Authorization: Bearer 40|tbtaEm4E8gdINZE8sG455GWzGmhJYIkRDDFW54pT'
                , 'Content-Length:0')
        ));

        $response = curl_exec($curl);

        // Close cURL session
        curl_close($curl);
        $res = json_decode($response);
        if ($res->success) {
            //   print('success');
            //    return $res->success;
        } else {
            //   print('error');
            //  return $res->error->message;
        }
    }

    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;
        }
    }

    function EXPORT_DATABASE($host, $user, $pass, $name, $tables = false, $backup_name = false) {

        set_time_limit(3000);
        $mysqli = new mysqli($host, $user, $pass, $name);
        $mysqli->select_db($name);
        $mysqli->query("SET NAMES 'utf8'");
        $queryTables = $mysqli->query('SHOW TABLES');
        while ($row = $queryTables->fetch_row()) {
            $target_tables[] = $row[0];
        } if ($tables !== false) {
            $target_tables = array_intersect($target_tables, $tables);
        }
        $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `" . $name . "`\r\n--\r\n\r\n\r\n";
        foreach ($target_tables as $table) {
            if (empty($table)) {
                continue;
            }
            $result = $mysqli->query('SELECT * FROM `' . $table . '`');
            $fields_amount = $result->field_count;
            $rows_num = $mysqli->affected_rows;
            $res = $mysqli->query('SHOW CREATE TABLE ' . $table);
            $TableMLine = $res->fetch_row();
            $content .= "\n\n" . $TableMLine[1] . ";\n\n";
            $TableMLine[1] = str_ireplace('CREATE TABLE `', 'CREATE TABLE IF NOT EXISTS `', $TableMLine[1]);
            for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) {
                while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
                    if ($st_counter % 100 == 0 || $st_counter == 0) {
                        $content .= "\nINSERT INTO " . $table . " VALUES";
                    }
                    $content .= "\n(";
                    for ($j = 0; $j < $fields_amount; $j++) {
                        $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                        if (isset($row[$j])) {
                            $content .= '"' . $row[$j] . '"';
                        } else {
                            $content .= '""';
                        } if ($j < ($fields_amount - 1)) {
                            $content .= ',';
                        }
                    } $content .= ")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num) {
                        $content .= ";";
                    } else {
                        $content .= ",";
                    } $st_counter = $st_counter + 1;
                }
            } $content .= "\n\n\n";
        }
        $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
        $backup_name = $backup_name ? $backup_name : $name . '___(' . date('H-i-s') . '_' . date('d-m-Y') . ').sql';

        $fp = fopen("../db_backups/" . $backup_name, "wb");
        fwrite($fp, $content);
        fclose($fp);

        //  echo $content;
        exit;
    }

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

}
