<?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);
            //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()) {
                    R::exec('SET NAMES latin1');
                    $saveData = R::getRow('select savename from save where saveid = ' . $programesetting->erpdbsave);
                    $visaAccountData = R::getRow('select accountname,bankname
                        from bankaccount
                        join bank on bank.bankid = bankaccount.bankid
                        where accountid = ' . $programesetting->erpdbvisaaccount);
                    R::selectDatabase('default');
                    $programesetting->erpdbsavename = $saveData["savename"];
                    $programesetting->erpdbvisaaccountname = $visaAccountData["accountname"] . " / " . $visaAccountData["bankname"];
                } 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 = '';
                    $programesetting->erpdbvisaaccountname = '';
                }
            }
            $this->smarty->assign('programesetting', $programesetting);

            $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
                //var_dump(R::getDatabaseAdapter()->getDatabase()->getMysqlEncoding());
                R::exec('SET NAMES latin1');
                $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 geterpVisaAccounts() {
        $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
                R::exec('SET NAMES latin1');
                $allVisaAccounts = R::getAll('select accountid,accountname,bankname
                        from bankaccount
                        join bank on bank.bankid = bankaccount.bankid
                        where bankaccount.conditions = 0 and visa = 1 and (bankname LIKE "%' . $name . '%"  or accountname LIKE "%' . $name . '%")');
                R::selectDatabase('default');

                if (count($allVisaAccounts) > 0) {
                    foreach ($allVisaAccounts as $vAccount) {
                        $row_array['id'] = $vAccount["accountid"];
                        $row_array['text'] = $vAccount["accountname"] . " / " . $vAccount["bankname"];
                        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 saveERPDBVisaAccount() {
        $erpDBVisaAccount = filter_input(INPUT_POST, 'erpDBVisaAccount');
        if (!empty($erpDBVisaAccount)) {
            $programesetting = R::load('programesetting', 1);
            if (isset($programesetting->erpdb) && !empty($programesetting->erpdb)) {
                $programesetting->erpdbvisaaccount = $erpDBVisaAccount;
                echo R::store($programesetting);
            }
        }
    }

    public function settingdatabase() {
        $tables = $this->tablesToClean();

        $db_name = DB_NAME;
        //    ini_set("display_errors", "on");

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

        $programesetting = R::findOne('programesetting');
        $programesetting->last_serial = 0;
        $programesetting->last_refund_serial = 0;
        r::store($programesetting);

        //    r::debug(true, 2);
        $pw = '$2y$10$G.ZYzcWYKP8xNJ82cMXMbeC.W.7gV72cMO7KdMre/NdBqASsID8DO';

        $sql = "INSERT INTO `awusers` (`user_id`, `user_name`, `user_password_hash`, `user_email`
                                                                , `user_active`, `user_activation_hash`, `user_password_reset_hash`
                                                                , `user_password_reset_timestamp`, `user_rememberme_token`
                                                                , `user_failed_logins`, `user_last_failed_login`, `user_registration_datetime`
                                                                , `user_registration_ip`, `role_id`, `name`, `specialid`, `positionid`, `attend`
                                                                , `hour_price`, `normal_per`, `pulse_per`, `session_per`) VALUES
                   (1, 'manager', '$pw' 
                , 'ahmed.freedeveloper@gmail.com', 1, '1ebf1664a5d6077504fcb60caccefc2d88b964e4'
                , '36e688b8ef85a659b3ec39646df92a809f2d6a28', 1422433469, NULL, 0, NULL
                , '2015-01-25 12:41:59', '127.0.0.1', 1, 'Manager', 0, 0, NULL, 0, 10, 10, 10)";
        r::exec($sql);
    }

    function tablesToClean() {
        $tablesAllowedToDelete .= '
            "andcontraception","antenalvisit","andvisitsus" ,"andvisitssemen","andvisitsrays"  ,"receiptdrugs" ,"mrict"
            ,"andvisitsinvestigation","andvisitsgenetictesting","andvisitsficils" ,"andvisitsdrugs","andvisits" ,"records" 
           ,"andmedicalproblems","andhistory","andexamination" ,"anderection","andejaculation"  ,"gtdetail","follow_pre"
           ,"excelinfopatients","examination","endvisitreports" ,"embryotransferovum","embryotransfer" ,"recorddrugs"
           ,"embryothawing","embryoslab","embryoselection" ,"embryoscoring","embryologyreport" ,"operationids"
           ,"embryofreezingreport","embryofreezing","embryo" ,"drugmovements","doc_instruction" ,"recepittmp" ,"thawing"
           ,"doctors_reserves","device_tracking","devices" ,"councilstaff","clinic_rooms","followup_operation" ,"semen"
           ,"clinic_reserves","bsessionmembers","bsession" ,"brequests","bmemberopenion" ,"mainantenentalus"
           ,"bcomments","hsg","hormon" ,"gynausficils","gynaus" ,"raysresults_img","raysresults"   ,"operations_main" 
           ,"gynarays","gynainvestigation","gynadrugs" ,"gyna","gtimage" ,"follow_post" ,"follow_instruction" ,"sonar"
           ,"followupvisit","followupinvest","followupexam" ,"followupdrugs","followupdiagnosis"   ,"operation_data"
           ,"followupcarddrugs","followupcard","followup" ,"operativedetails","operation_residence"  ,"residence_reserves"
           ,"mainantenentalrays","mainantenentalinvest","mainantenentaldrugs" ,"mainantenental","lastvisit"
           ,"aparoscopy","invofferdetails","invoffer" ,"invests_supplies","investigationresults_urine" ,"spermfreezingreport"
           ,"investigationresults_times","investigationresults_stool","investigationresults_pt"  ,"ultrasounddetail" 
           ,"investigationresults_culture_rs","investigationresults_culture_ms" ,"investigationresults_custom"
           ,"investigationresults_culture_ls" ,"investigationresults_culture_hs","investigationresults_culture" , "awusers"
           ,"investigationresults_cross_donners","investigationresults_cross","investigationresults_blood","ultrasound"
           ,"investigationresults_aborh","investigationresults" ,"instruction" ,"infertilitynotes" ,"storedrugs"  ,"visits_updates"
           ,"infertilitylmp","infertilityinvest","infertilitygyna" ,"infertilitydrugs","infertilitydiagnosis" ,"ultrasoundgyna"
           ,"infertility","importtdetails","importdrugs" ,"importbill","hysteroscopy"  ,"investigationresults_esr"
          ,"phsexual","phpersonal","phpastsurgical" ,"phpastmedical","phpasticsi"   ,"tankcells","storedrugsvalidation"
            ,"phpasthx","phpastgynecological","phpastart" ,"phobstetric","phmenstrual"   ,"ultrasoundobst"  ,"bill_paying"
           ,"phfamily","phcontraception","patients_updates" ,"patients_tmp","patients_complaints" ,"visits" ,"ustv"
           ,"patients_childs","patients","patientfiles" ,"patientdecleration","pathology" ,"ultrasoundobstdetail" , "bill_paying"
           ,"ovumpickup","otherinvestigationsvalues","otherinvestigationsrows" ,"operativedetailsdrugs"  ,"visit_hours"
             , "votes", "vote_answers" , "vote_devices" , "archive_tracking" , "login_tacking" 
             , "residence_rooms" , "semen_cryopreservation"  , "semen_analysis"  , "patients_notify"  
             , "manual_operation"   , "ivf_records" , "ivf_drugs" , "ivf_records_drugs"  , "ivf_report" , "sms_control_setting"    ';

        return $tablesAllowedToDelete;
    }

//    public function settingdatabase() {
//        $tablesNotAllowedToDelete = '"awcontroll","awcontrollprop","awmenu","awrole","awrolecontrollprop","awrolemenu","awusers","awroleposition","awrolespecialize","programesetting"';
//        $tablesNotAllowedToDelete .= ',"wifestatus","drugs","investcats","invests","phregularity","phamount","phdysmenorrhoea","phcontracttype","phobstericterminate","phpastarttype"';
//        $tablesNotAllowedToDelete .= ',"anasthesa","generalanasthesa","jncision","midlinejncision","excelinfo"';
//
//        $tablesAllowedToDelete = ',"detections","wifetypes","wifejobs","husbandtypes","husbandjobs","education","bloodtypes","diagnosis","diagnosisant","complaint","complaintant","operation","phfamilyrelative"';
//        $tablesAllowedToDelete .= ',"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();
    }

}
