<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    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 = 'setup';
        $this->shcontrollname = 'Setup';
        $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] = 'setup'; //controller name or tab name
        $active[1] = 'setup'; //controller name
// do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'index';
                break;
            case 'show':$active[2] = 'index';
                break;
            default :$active[2] = 'index';
                break;
        }
        $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() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

// $this->settingdatabse();
//Html files
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $data = 0;
        $this->smarty->assign('checked', $data);
        $this->smarty->display('databasesetting.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function settingdb() {

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

        $setupPassword = '123456';
        $_SESSION['pass'] = filter_input(INPUT_POST, 'pass');
//Html files

        if ($setupPassword == $_SESSION['pass']) {
            header::headershow($this->smarty, $this->hosturl);
            sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);

            $programesetting = R::load('programesetting', 1);
            $this->smarty->assign('programesetting', $programesetting);
            //if there is save load it
            if (isset($programesetting->erpdbsave) && $programesetting->erpdbsave > 0) {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $saveData = R::getRow('select savename from save where saveid = ' . $programesetting->erpdbsave);
                    R::selectDatabase('default');
                    $programesetting->erpdbsavename = $saveData["savename"];
                } else {
                    //throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    $programesetting->erpdbsave = 0;
                    $programesetting->erpdbsavename = '';
                }
            }
            $this->smarty->display('setupsetting.html');
            leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
            footer::footershow($this->smarty, $this->hosturl);
        } else {
            header::headershow($this->smarty, $this->hosturl);
            sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
            $data = 1;

            $this->smarty->assign('checked', $data);
            $this->smarty->display('databasesetting.html');
            leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
            footer::footershow($this->smarty, $this->hosturl);
        }
    }

    public function saveErpDB() {
        $db_name = DB_NAME;

        //$data = R::getcol("SHOW tables FROM " . $db_name . " WHERE Tables_in_" . $db_name . " NOT IN ('awcontroll','awcontrollprop','awmenu' ,'awrole','awrolecontrollprop','awrolemenu','awusers' , 'education','husbandjobs','husbandtypes','programesetting','wifejobs','wifestatus','wifetypes')");
        $erpDB = filter_input(INPUT_POST, 'erpDB');
//        if (!empty($erpDB)) {
        R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $erpDB . '', DB_USER, DB_PASS);
        R::selectDatabase('default');
        //
        $programesetting = R::load('programesetting', 1);
        $programesetting->erpdb = $erpDB;
        $_SESSION["erpDB"] = $erpDB;
        if (empty($erpDB)) {//saveErpDB
            $programesetting->erpdbsave = 0;
        }
        echo R::store($programesetting);
//        }
    }

    public function getErpSave() {
        $row_array = array();
        $return_arr = array();

        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            R::selectDatabase('erpDB');
            if (R::testConnection()) {
                $name = $_GET['term']; //It could be product name or category name
                $allSave = R::getAll('select saveid,savename from save where conditions = 0 and savename LIKE "%' . $name . '%"');
                R::selectDatabase('default');

                if (count($allSave) > 0) {
                    foreach ($allSave as $save) {
                        $row_array['id'] = $save["saveid"];
                        $row_array['text'] = $save["savename"];
                        array_push($return_arr, $row_array);
                    }
                }
            } else {
                $row_array['id'] = "";
                $row_array['text'] = "Loading failed ... check Erp Database Connection";
                array_push($return_arr, $row_array);
            }
        } else {
            $row_array['id'] = "";
            $row_array['text'] = "Loading failed ... Erp Database Name Is Empty";
            array_push($return_arr, $row_array);
        }

        echo json_encode($return_arr);
    }

    public function erpDBSave() {
        $erpDBSave = filter_input(INPUT_POST, 'erpDBSave');
        if (!empty($erpDBSave)) {
            $programesetting = R::load('programesetting', 1);
            if (isset($programesetting->erpdb) && !empty($programesetting->erpdb)) {
                $programesetting->erpdbsave = $erpDBSave;
                echo R::store($programesetting);
            }
        }
    }

    public function settingdatabase() {
        $tablesNotAllowedToDelete = '"awcontroll","awcontrollprop","awmenu","awrole","awrolecontrollprop","awrolemenu" 
               ,"awusers","awroleposition","awrolespecialize","programesetting" ,"wifestatus","drugs","investcats"
               ,"invests","phregularity","phamount","anasthesa","generalanasthesa","jncision","midlinejncision","excelinfo"';

        $tablesAllowedToDelete = ',"detections","wifetypes","wifejobs","husbandtypes","husbandjobs","education"'
                . ',"bloodtypes","diagnosis","diagnosisant","complaint","complaintant","operation","phfamilyrelative"'
                . ',"phobstericterplace","phpastmedicaldisease","phpastsurgicaloperation","phpastgynecologicaloperation"'
                . ',"phpastartcenter","phfamilydisease"';

        $db_name = DB_NAME;

        //$data = R::getcol("SHOW tables FROM " . $db_name . " WHERE Tables_in_" . $db_name . " NOT IN ('awcontroll','awcontrollprop','awmenu' ,'awrole','awrolecontrollprop','awrolemenu','awusers' , 'education','husbandjobs','husbandtypes','programesetting','wifejobs','wifestatus','wifetypes')");
        $emptyalltables = filter_input(INPUT_POST, 'emptyalltables');
        if ($emptyalltables == 0) {

            $data = R::getcol("SHOW tables FROM " . $db_name . " WHERE Tables_in_" . $db_name . " NOT IN ($tablesNotAllowedToDelete)");
            foreach ($data as $row) {
                echo R::exec("TRUNCATE TABLE $row");
            }
        }
        if ($emptyalltables == 1) {
            $data = R::getcol("SHOW tables FROM " . $db_name . " WHERE Tables_in_" . $db_name . " NOT IN ($tablesNotAllowedToDelete$tablesAllowedToDelete)");
            foreach ($data as $row) {
                echo R::exec("TRUNCATE TABLE $row");
            }
        }
    }

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