<?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 $suggestStatusNo;

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

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

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

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

    public function index() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //call other class with other content

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


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

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

        ## constants come from aw_config
        $dbhost = DB_HOST;
        $dbusern = DB_USER;
        $dbpassword = DB_PASS;
        $dbname = DB_NAME;

        $done = $this->backup_tables('*', '../db_backups/', $dbname, $dbhost, $dbusern, $dbpassword);
    }

    public function backup_tables($tables, $backupdir, $dbname, $db_host, $db_user, $db_password) {
        $host = $db_host;
        $newname = date("Y-m-d");
        $programesetting = R::findone('programesetting');
        //the path of backup files
        $inrtoi = "../db_backups/obgy_$newname.sql";
        ## for App server
        //$command = "$programesetting->backupdriver:\AppServ\MySQL\bin\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";
        ## for Wamp server
        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";
        $rslt = system($command);
        ################################################################################################################################################
        ## download it in program setting path

        if ($programesetting->backupdest) {
            //the path of backup files
            $inrtoi = "$programesetting->backupdest/obgy_$newname.sql";
            ## for App server
            //$command = "$programesetting->backupdriver:\AppServ\MySQL\bin\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";
            ## for Wamp server
            $command = "$programesetting->backupdriver\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";
            $rslt = system($command);
        }


        ######################################################################################################################################################
        ## allow user to download it in another location + default on determined above
        header('Content-Description: File Transfer');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=' . basename("../db_backups/obgy_$newname.sql"));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize("../db_backups/obgy_$newname.sql"));
        ob_clean();
        flush();
        readfile("../db_backups/obgy_$newname.sql");

        exit;

        return 1;
    }

    public function solution() {
        ### if drugid is null but has  drug name insert it in drug table and save inserted id in drugid (gyna & antenatal )
        ####################
        ## antenatal drugs
        ####################
        $allEmptyDrugs = R::getAll("select * from mainantenentaldrugs where drugid is null and drugname is not null and drugname != ''");
        foreach ($allEmptyDrugs as $emoDrug) {
            ## check if drug exist
            $drug = R::getRow("select id from drugs where drugname = ?", [$emoDrug['drugname']]);
            if (count($drug) == 0) {    ## this drug doesnot exist in drug table
                $newDrug = R::dispense('drugs');
                $newDrug->drugname = $emoDrug['drugname'];
                $newDrug->drugtype = $emoDrug['drugtype'];
                $newDrug->drugdos = $emoDrug['drugdos'];
                $newDrug->initialbalance = 0;
                $newDrug->currentbalance = 0;
                $id = R::store($newDrug);

                R::exec("update mainantenentaldrugs set drugid = ? where id = ?", [$id, $emoDrug['id']]);
            } else {    ## this drug  exist in drug table
                R::exec("update mainantenentaldrugs set drugid = ? where id = ?", [$drug['id'], $emoDrug['id']]);
            }
        }

        ####################
        ## gyna drugs
        ####################


        $allEmptyDrugsG = R::getAll("select * from gynadrugs where drugid is null and drugname is not null and drugname != ''");
        foreach ($allEmptyDrugsG as $emoDrug) {
            ## check if drug exist
            $drug = R::getRow("select id from drugs where drugname = ?", [$emoDrug['drugname']]);
            if (count($drug) == 0) {    ## this drug doesnot exist in drug table
                $newDrug = R::dispense('drugs');
                $newDrug->drugname = $emoDrug['drugname'];
                $newDrug->drugtype = $emoDrug['drugtype'];
                $newDrug->drugdos = $emoDrug['drugdos'];
                $newDrug->initialbalance = 0;
                $newDrug->currentbalance = 0;
                $id = R::store($newDrug);
                ;
                R::exec("update gynadrugs set drugid = ? where id = ?", [$id, $emoDrug['id']]);
            } else {    ## this drug  exist in drug table
                R::exec("update gynadrugs set drugid = ? where id = ?", [$drug['id'], $emoDrug['id']]);
            }
        }


        ####################
        ## patientss status No
        ####################

        $startTime = microtime(true);


        #######################################################
        $this->getstatusno();

        #########################################################
        echo "Time Elapsed: " . ((microtime(true) - $startTime) / 60) . "m";
        print_r("<br/> Done <br/>");
    }

    private function getstatusno() {
        $usedStatusNoArray = array();
        $NotUsedStatusNoArray = array();

        ## count of  all Patients in database
        $allPatients = R::getRow("select count(id) from patients ");

        $from = 1;
        $to = $allPatients['count(id)'];

        ## available range of status no     = all - used
        $allStatusNoArray = range($from, $to);

        $usedStatusNo = R::getAll("select id , statusno from patients where statusno BETWEEN  ?  AND  ? ORDER BY statusno ASC ", [$from, $to]);

        foreach ($usedStatusNo as $sss) {
            array_push($usedStatusNoArray, $sss['statusno']);
        }

        $NotUsedStatusNoArray = array_diff($allStatusNoArray, $usedStatusNoArray);

        ## all Patients With Empty Status number
        $allEmpStatusPat = R::getAll("select id , statusno from patients where statusno = 0 or statusno is null ");

        $index = key($NotUsedStatusNoArray);       // First Element's Key
        foreach ($allEmpStatusPat as $patient) {
            R::exec("update patients set statusno = ? where id = ?", [$NotUsedStatusNoArray[$index], $patient['id']]);
            $index++;
        }
    }

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

    public function resolve_error() {
        $oldDbHost = 'localhost';
        $oldDbName = 'adeelcom_backup';
        $oldDbUser = 'adeelcom_obgy2';
        $oldDbPassword = 'SSgGhFIB1AVo';
        ## define another database
        R::addDatabase("adeelcom_backup", 'mysql:host=' . $oldDbHost . ';dbname=' . $oldDbName . '', '' . $oldDbUser . '', '' . $oldDbPassword . '');

        ## switch to the new database
        R::selectDatabase("adeelcom_backup");
        $visits = R::findAll('newvisit', ' id > 0 ');

        R::selectDatabase('default');
        foreach ($visits as $visit) {
            if ($visit->id > 0 && $visit->id > 3981 && $visit->id <= 3998) {
                $obj = R::load('newvisit', $visit->id);
                $obj->ttt = $visit->ttt;
                r::store($obj);
                echo $visit->id . ' - ';
            }
        }
    }

    ######################################################
    #
// at the end of class call

    public function __destruct() {
        //echo "Time Elapsed: ".(microtime(true) - $this->time)."s";
//close connection
        R::close();
    }

}
