<?php

//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');
//Lastbillidspricesupdated
require_once('../models/dao/LastbillidspricesupdatedDAO.class.php');
require_once('../models/dto/Lastbillidspricesupdated.class.php');
require_once('../models/mysql/LastbillidspricesupdatedMySqlDAO.class.php');
require_once('../models/mysql/ext/LastbillidspricesupdatedMySqlExtDAO.class.php');
//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');
//Maccontrol
require_once('../models/dao/MaccontrolDAO.class.php');
require_once('../models/dto/Maccontrol.class.php');
require_once('../models/mysql/MaccontrolMySqlDAO.class.php');
require_once('../models/mysql/ext/MaccontrolMySqlExtDAO.class.php');


require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

/* ======================

  Controller Name :- gt4setting

  ======================== */
//Programsetting
$programSetting = new Programsetting();
$programSettingDAO = new ProgramsettingsMySqlDAO();
$programSettingEX = new ProgramsettingsMySqlExtDAO();
//Lastbillidspricesupdated
$lastBillIdsPricesUpdated = new Lastbillidspricesupdated();
$lastBillIdsPricesUpdatedDAO = new LastbillidspricesupdatedMySqlDAO();
$lastBillIdsPricesUpdatedEX = new LastbillidspricesupdatedMySqlExtDAO();
//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();
//Maccontrol
$macControl = new Maccontrol();
$macControlDAO = new MaccontrolMySqlDAO();
$macControlEX = new MaccontrolMySqlExtDAO();


$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();



//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();


//Sellbilldetail
$sellbilldetail = new Sellbilldetail();
$sellbilldetailDAO = new SellbilldetailMySqlDAO();
$sellbilldetailEX = new SellbilldetailMySqlExtDAO();
//Returnsellbilldetail
$returnSellBillDetail = new Returnsellbilldetail();
$returnSellBillDetailDAO = new ReturnsellbilldetailMySqlDAO();
$returnSellBillDetailEX = new ReturnsellbilldetailMySqlExtDAO();
//Sellandruternbilldetail
$sellAndRuternBillDetail = new Sellandruternbilldetail();
$sellAndRuternBillDetailDAO = new SellandruternbilldetailMySqlDAO();
$sellAndRuternBillDetailEX = new SellandruternbilldetailMySqlExtDAO();





$programSettingData = $programSettingDAO->load(1);
$smarty->assign("programSettingData", $programSettingData);
//include_once("../public/auth.php");
//here the global templates
if (empty($do) || $do == "show" || $do == "sucess" || $do == "error") {
    $smarty->display("header.html");
}





//check and use the condetion that suite this action
if (empty($do) || $do == "show") {
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("gt4settingview/pass.html");
    //$smarty->display("gt4settingview/add.html");
} elseif ($do == "en") {
    // Read in entire file
    $password = filter_input(INPUT_POST, "password");
    $save = file_get_contents("../models/sql/Save.txt");
    $save = trim($save);
    if ($password == $save) {

        /* ------------------------------------- */
        $lastBillIdsPricesUpdated = $lastBillIdsPricesUpdatedDAO->load(1);
        if (!isset($lastBillIdsPricesUpdated->id) || empty($lastBillIdsPricesUpdated->id)) {
            $lastBillIdsPricesUpdated->buybill = 0;
            $lastBillIdsPricesUpdated->buyandret = 0;
            $lastBillIdsPricesUpdated->retbuy = 0;
            $lastBillIdsPricesUpdated->sell = 0;
            $lastBillIdsPricesUpdated->sellandret = 0;
            $lastBillIdsPricesUpdated->retsell = 0;
            $lastBillIdsPricesUpdated->buyquantity = 0;
            $lastBillIdsPricesUpdated->buyandretquantity = 0;
            $lastBillIdsPricesUpdatedDAO->insert($lastBillIdsPricesUpdated);
        }
        if ($lastBillIdsPricesUpdated->buybill > 0) {
            $bill = $buyBillDetailDAO->load($lastBillIdsPricesUpdated->buybill);
            $lastBillIdsPricesUpdated->buybill = $bill->buybillid;
        }
        if ($lastBillIdsPricesUpdated->buyandret > 0) {
            $bill = $buyAndReturnBillDetailDAO->load($lastBillIdsPricesUpdated->buyandret);
            $lastBillIdsPricesUpdated->buyandret = $bill->buybillid;
        }
        if ($lastBillIdsPricesUpdated->sell > 0) {
            $bill = $sellbilldetailDAO->load($lastBillIdsPricesUpdated->sell);
            $lastBillIdsPricesUpdated->sell = $bill->sellbillid;
        }
        if ($lastBillIdsPricesUpdated->sellandret > 0) {
            $bill = $sellAndRuternBillDetailDAO->load($lastBillIdsPricesUpdated->sellandret);
            $lastBillIdsPricesUpdated->sellandret = $bill->sellbillid;
        }
        if ($lastBillIdsPricesUpdated->retsell > 0) {
            $bill = $returnSellBillDetailDAO->load($lastBillIdsPricesUpdated->retsell);
            $lastBillIdsPricesUpdated->retsell = $bill->returnsellbillid;
        }

        if ($lastBillIdsPricesUpdated->buyquantity > 0) {
            $bill = $buyBillDetailDAO->load($lastBillIdsPricesUpdated->buyquantity);
            $lastBillIdsPricesUpdated->buyquantity = $bill->buybillid;
        }
        if ($lastBillIdsPricesUpdated->buyandretquantity > 0) {
            $bill = $buyAndReturnBillDetailDAO->load($lastBillIdsPricesUpdated->buyandretquantity);
            $lastBillIdsPricesUpdated->buyandretquantity = $bill->buybillid;
        }
        $smarty->assign('last', $lastBillIdsPricesUpdated);
        /* ------------------------------------- */
        $allowedMacs = $macControlEX->queryAllowedMac();
        $smarty->assign('allowedMacs', json_encode($allowedMacs));
        $users = $userDAO->queryByConditions(0);
        $smarty->assign('users', $users);



        $smarty->display("gt4settingview/show.html");
        //header("location:usergroupControllerAdmin.php?do=edit");
    } else {
        echo -1;
    }
} elseif ($do == "sql") {
    $type = $_POST['type'];
    try {
        $sqlQuery = array();
        switch ($type) {
            /* -- products------------------------------------------------- */
            case "applyCatDiscountThatIsDirectDisountOnLastBuyWithDiscount"://apply discount of category on products "only when category has direct discount"
                $sqlQuery[] = 'UPDATE product a
                            JOIN productcat b ON a.productCatId = b.productCatId
                            SET a.lastbuyprice_withDiscount = a.productBuyPrice - b.buydiscount
                            where b.discounttype=0';
                break;
            case "applyCatDiscountThatIsPercentageDisountOnLastBuyWithDiscount"://apply discount of category on products "only when category has percentage discount"
                $sqlQuery[] = 'UPDATE product a
                            JOIN productcat b ON a.productCatId = b.productCatId
                            SET a.lastbuyprice_withDiscount = a.productBuyPrice - ((b.buydiscount * a.productBuyPrice)/100)
                            where b.discounttype=1';
                break;
            case "forCatWithoutDiscountMakeLastBuyPriceWithDiscountEQUALLastBuyPrice"://if no cat discount lastbuyprice withdiscount = lastbuyprice
                $sqlQuery[] = 'UPDATE product a
                            JOIN productcat b ON a.productCatId = b.productCatId
                            SET a.lastbuyprice_withDiscount = a.lastbuyprice
                            where b.discounttype=-1';
                break;
            case "forEmptyOrNullLastBuyPriceWithDiscountValueMakeItEqualToLastBuyPrice":
                $sqlQuery[] = 'UPDATE `product` SET `lastbuyprice_withDiscount` = `productBuyPrice`
                            where lastbuyprice_withDiscount = 0 or lastbuyprice_withDiscount is null';
                break;
            ####################################################################
            case "forEmptyOrNullLastBuyPriceValueMakeItEqualToBuyPrice":
                $sqlQuery[] = 'UPDATE `product` SET `lastbuyprice` = `productBuyPrice`
                            where lastbuyprice = 0 or lastbuyprice is null';
                break;
            case "makeLastBuyPriceWithDiscountEqualToBuyPrice":
                $sqlQuery[] = 'UPDATE `product` SET `lastbuyprice_withDiscount` = `productBuyPrice`';
                break;
            case "makeLastBuyPriceEqualToBuyPrice":
                $sqlQuery[] = 'UPDATE `product` SET `lastbuyprice` = `productBuyPrice`';
                break;
            ####################################################################
            case "replaceSpecialCharectersInProductNameWithDash":
                $sqlQuery[] = "update product set productName = REPLACE(productName,'/','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,'\\','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,';','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,',','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,'?','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,':','-')";
                $sqlQuery[] = "update product set productName = REPLACE(productName,'*','-')";

                break;
            /* -- cats-------------------------------------------------------- */
            case "StopNegativeSaleOnAllCategories":
                $sqlQuery[] = "UPDATE `productcat` SET `stopNegativeSale` = 1";

                break;
            /* -- DB -------------------------------------------------------- */
            case "emptyDB":
                $DBName = ConnectionProperty::getDatabase();
                $temp = $programSettingEX->truncateAllTablesGenerateQuery($DBName);
                foreach ($temp as $value) {
                    $sqlQuery[] = $value->programsettingsid;
                }
                break;
            /* -- bills -------------------------------------------------------- */
            case "reviewBills":
                $dateTimeNow = date('Y-m-d H:i:s');
                $sqlQuery[] = ' INSERT INTO sellbillreview (billid, reviewType, reviewuserid, sysdate,del)
                                SELECT sellbillid, 1, 1, "' . $dateTimeNow . '", 0 FROM sellbill';
                $sqlQuery[] = ' update sellbill set lastReviewType = 1,lastReviewUser = 1,lastReviewDateTime = "' . $dateTimeNow . '" ';
                $sqlQuery[] = ' INSERT INTO returnsellbillreview (billid, reviewType, reviewuserid, sysdate,del)
                                SELECT returnsellbillid, 1, 1, "' . $dateTimeNow . '", 0 FROM returnsellbill';
                $sqlQuery[] = ' update returnsellbill set lastReviewType = 1,lastReviewUser = 1,lastReviewDateTime = "' . $dateTimeNow . '" ';
                break;
            default:
                break;
        }
        //print_r($sqlQuery);
        foreach ($sqlQuery as $sql) {
            $programSettingEX->runSqlQuery($sql);
        }


        if ($type == "emptyDB")
            header("location:?do=logout");
        else
            header("location:?do=sucess");
    } catch (Exception $e) {
        echo $e;
        header("location:?do=error");
    }
} elseif ($do == "saveajax") {

    $type = $_POST['type'];
    $value = $_POST['value'];
    try {
        $sqlQuery = array();
        switch ($type) {
            ####################################################################
            case "copyRightsStatment":
                $sqlQuery[] = 'UPDATE `programsettings` SET copyRightsStatment = "' . $value . '" where programsettingsid = 1 ';
                break;
            case "remoteBackupLink":
                $sqlQuery[] = 'UPDATE `programsettings` SET remoteBackupLink = "' . $value . '" where programsettingsid = 1 ';
                break;
            case "remoteBackupUser":
                $sqlQuery[] = 'UPDATE `programsettings` SET remoteBackupUser = "' . $value . '" where programsettingsid = 1 ';
                break;
            case "remoteBackupPass":
                $sqlQuery[] = 'UPDATE `programsettings` SET remoteBackupPass = "' . $value . '" where programsettingsid = 1 ';
                break;
            case "remoteBackupFolder":
                $sqlQuery[] = 'UPDATE `programsettings` SET remoteBackupFolder = "' . $value . '" where programsettingsid = 1 ';
                break;
            case "doOpenEntry":
                $alldebt = R::getAll('select * from accountstree where del=0 and ((accountNature=0 and theValue > 0) or (accountNature=1 and theValue < 0))');
                $sumdebt = R::getCell('select sum(abs(theValue)) from accountstree where del=0 and ((accountNature=0 and theValue > 0) or (accountNature=1 and theValue < 0))');
                $allcredit = R::getAll('select * from accountstree where del=0 and ((accountNature=1 and theValue > 0) or (accountNature=0 and theValue < 0))');
                $sumcredit = R::getCell('select sum(abs(theValue)) from accountstree where del=0 and ((accountNature=1 and theValue > 0) or (accountNature=0 and theValue < 0))');

                $date = $_POST['openentryDate'];
                if (!isset($date) || empty($date)) {
                    $date = date("Y-m-d H:i:s");
                }
//                R::debug(true);
                R::exec('insert into dailyentry (totalcreditor,totaldebtor,thedate,dDateTime,userid) VALUES (' . $sumcredit . ',' . $sumdebt . ',"' . $date . '","' . $date . '",1)');
                $dailyentryid = R::getInsertId();
                foreach ($alldebt as $row) {
                    R::exec('insert into dailyentrydebtor (dailyentryid,accountstreeid,`value`) VALUES (' . $dailyentryid . ',' . $row['id'] . ',' . abs($row['theValue']) . ')');
                }
                foreach ($allcredit as $row) {
                    R::exec('insert into dailyentrycreditor (dailyentryid,accountstreeid,`value`) VALUES (' . $dailyentryid . ',' . $row['id'] . ',' . abs($row['theValue']) . ')');
                }
                break;
            ####################################################################
            default:
                break;
        }
//        print_r($sqlQuery);
        foreach ($sqlQuery as $sql) {
            $programSettingEX->runSqlQuery($sql);
        }



        //header("location:?do=sucess");
        echo 1;
    } catch (Exception $e) {
        //echo $e;
        //header("location:?do=error");
        echo -1;
    }
} elseif ($do == "SaveWithManyParameters") {

    $type = $_POST['type'];
    $recievedData = $_POST['dataToSend'];
    try {

        switch ($type) {
            case "calcTreeIds":

                $treeIdCalcTables = $recievedData['treeIdCalcTables'];
                $treeIdCalcItems = $recievedData['treeIdCalcItems'];
                /*

                 * ***** insert save that not exist in accountstree table using treeid = 0 after calcTreeIds for all tables
                  INSERT INTO accountstree
                  (name, customName, customNameEn, nameEn, parent, accountNature, theValue, theOrder, layingOrder, reportid, listId, notes, itemfrom, itemtype, itemtype2, itemtype3, userid, del, sysdate)

                  SELECT savename,savename,savename,savename,40,'0', '0', '0', '', '1', '1', '', '0', '3', '1', '', '1', '0', '2022-09-26 03:00:32'
                  FROM save where `treeId`<1;

                 *
                 * * ***** insert store that not exist in accountstree table using treeid = 0 after calcTreeIds for all tables
                  INSERT INTO accountstree
                  (name, customName, customNameEn, nameEn, parent, accountNature, theValue, theOrder, layingOrder, reportid, listId, notes, itemfrom, itemtype, itemtype2, itemtype3, userid, del, sysdate)

                  SELECT `storeName`,storeName,storeName,storeName, '49', '0', '0', '0', '', '1', '1', '', '0', '3', '1', '', '1', '0', '2022-09-26 03:39:05'
                  FROM store where `treeId`<1;
                 *
                 * * ***** insert supplier that not exist in accountstree table using treeid = 0 after calcTreeIds for all tables
                  UPDATE supplier SET treeId = '385' WHERE supplierid = 1;

                  INSERT INTO accountstree
                  (name, customName, customNameEn, nameEn, parent, accountNature, theValue, theOrder, layingOrder, reportid, listId, notes, itemfrom, itemtype, itemtype2, itemtype3, userid, del, sysdate)

                  SELECT `suppliername`,suppliername,suppliername,suppliername,'81', '1', '0', '0', '', '1', '1', '', '0', '1', '1', '', '1', '0', '2022-09-26 03:46:32'
                  FROM supplier where `treeId`<1;
                 *
                 *
                 *
                 * * ***** insert client that not exist in accountstree table using treeid = 0 after calcTreeIds for all tables
                  UPDATE client SET treeId = '384' WHERE clientid = 1;
                  INSERT INTO accountstree
                  (name, customName, customNameEn, nameEn, parent, accountNature, theValue, theOrder, layingOrder, reportid, listId, notes, itemfrom, itemtype, itemtype2, itemtype3, userid, del, sysdate)

                  SELECT `clientname`,clientname,clientname,clientname, '58', '0', '0', '0', '', '1', '1', '', '0', '3', '1', '', '1', '0', '2022-09-26 03:50:16'
                  FROM client where `treeId`<1;
                 *
                 */
//                $allTables = $recievedData['allTables'];
                $allTables = array(
                    'assets' => array('treeParent' => '2', 'treeColumn' => 'treeId', 'nameCol' => 'assetsName'),
                    'assetscat' => array('treeParent' => '2', 'treeColumn' => 'treeId', 'nameCol' => 'cattitel'),
                    'bankaccount' => array('treeParent' => '38', 'treeColumn' => 'treeId', 'nameCol' => 'accountname'),
                    'capital' => array('treeParent' => '120', 'treeColumn' => 'treeId', 'nameCol' => 'NoColumnForName'),
                    'client' => array('treeParent' => '57,58', 'treeColumn' => 'treeId', 'nameCol' => 'clientname'),
                    'expensestype' => array('treeParent' => '313, 237, 158', 'treeColumn' => 'treeId', 'nameCol' => 'expensestypename'),
                    'incometype' => array('treeParent' => '151', 'treeColumn' => 'treeId', 'nameCol' => 'incomeTypeName'),
                    'partner' => array('treeParent' => '9', 'treeColumn' => 'treeId', 'nameCol' => 'partnername'),
                    'project' => array('treeParent' => '23', 'treeColumn' => 'treeid', 'nameCol' => 'name'),
                    'save' => array('treeParent' => '40', 'treeColumn' => 'treeId', 'nameCol' => 'savename'),
                    'store' => array('treeParent' => '49', 'treeColumn' => 'treeId', 'nameCol' => 'storeName'),
                    'supplier' => array('treeParent' => '80,81', 'treeColumn' => 'treeId', 'nameCol' => 'suppliername'),
                    'employee' => array('treeParent' => '97', 'treeColumn' => 'treeId', 'nameCol' => 'employeeName'),
                );

                foreach ($allTables as $table => $tableData) {
                    if (in_array($table, $treeIdCalcTables) || $treeIdCalcTables[0] == "all") {
                        $nameCol = $tableData['nameCol'];
                        $treeColumn = $tableData['treeColumn'];
                        $treeParent = $tableData['treeParent'];
                        if ($table == "capital") {
                            $sql = "UPDATE $table
                                SET $table.$treeColumn = 50";
                        } else {
                            $sql = "UPDATE $table
                                JOIN accountstree ON (accountstree.customName = $table.$nameCol and accountstree.parent in($treeParent))
                                SET $table.$treeColumn = accountstree.id";
                            if ($treeIdCalcItems == 0)
                                $sql .= " where $table.$treeColumn<1";
                        }

                        $programSettingEX->runSqlQuery($sql);
                    }
                }

                break;
        }

        echo 1;
    } catch (Exception $e) {
        //echo $e;
        echo -1;
    }
} elseif ($do == "allMacOfMovement") {
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $withAddOption = $_GET['withAddOption'];
    //$limit = 15; //intval($_GET['page_limit']);
    $queryString .= ' and mac LIKE "%' . $name . '%" '; //' order by movementmanageid asc limit ' . $limit


    $macData = $macControlEX->queryAllMacDataFromMovementmanage($queryString);
    if (count($macData) > 0) {
        $i = 1;
        foreach ($macData as $data) {
            if ($withAddOption == 1 && $i == 1) {
                $row_array['id'] = "-2";
                $row_array['text'] = "اضافة جديد";
                array_push($return_arr, $row_array);
            }




            $row_array['id'] = $data->mac . '*' . $data->deviceType;
            if ($data->deviceType == "DESKTOP") {
                $row_array['text'] = '<img src="../views/default/images/upload/computer.png"> ';
            } elseif ($data->deviceType == "MOBILE") {
                $row_array['text'] = '<img src="../views/default/images/upload/mobile.png"> ';
            } elseif ($data->deviceType == "TABLET") {
                $row_array['text'] = '<img src="../views/default/images/upload/tablet.png"> ';
            }
            $row_array['text'] .= $data->mac;
            array_push($return_arr, $row_array);

            $i++;
        }
    }


//echo $return_arr;
    echo json_encode($return_arr);
} elseif ($do == "saveControlDevices") {
    $allowMobileLogin = (int) filter_input(INPUT_POST, 'allowMobileLogin');
    $allowedMobileUsers = filter_input(INPUT_POST, 'allowedMobileUsers', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $lanAllowType = (int) filter_input(INPUT_POST, 'lanAllowType');
    $allowedMAC = filter_input(INPUT_POST, 'allowedMAC');
    $wanAllowType = (int) filter_input(INPUT_POST, 'wanAllowType');
    $allowedUsers = filter_input(INPUT_POST, 'allowedUsers', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    try {

        $programSettingData->allowMobileLogin = $allowMobileLogin;
        $programSettingData->lanAllowType = $lanAllowType;
        $programSettingData->wanAllowType = $wanAllowType;
        $programSettingDAO->update($programSettingData);

        switch ($lanAllowType) {
            case 0://allowed from prog setting truncate table
                $macControlEX->truncate();
                break;
            case 1://forbidden
                $macControlEX->truncate();
                break;
            case 2://some allowed
                //forbid all by truncate
                $macControlEX->truncate();
                //allow some
                //$allowedMacs_str = '';
                foreach (explode(',', $allowedMAC) as $value) {
                    $mac = explode('*', $value)[0];
                    $deviceType = explode('*', $value)[1];
                    $mac = filter_var(trim($mac), FILTER_VALIDATE_MAC); //return mac or false
                    if ($mac !== false && ($deviceType == "DESKTOP" || $deviceType == "MOBILE" || $deviceType == "TABLET")) {
                        //$allowedMacs_str .= $value . ",";
                        $macControl->allowRemoteAccess = 0;
                        $macControl->deviceType = $deviceType;
                        $macControl->mac = $mac;
                        $macControl->del = 0;
                        $macControl->userid = $_SESSION['userid'];
                        $macControl->sysdate = date("Y-m-d H:i:s");
                        $macControlDAO->insert($macControl);
                    }
                }
                //$allowedMacs_str = rtrim($allowedMacs_str, ',');
                //$macControlEX->UpdateAllowRemoteAccess(0, "where mac in($allowedMacs_str)");
                break;
            default:
                break;
        }
        switch ($wanAllowType) {
            case 0://allowed
                $userEX->UpdateAllowRemoteAccess(0);
                break;
            case 1://forbidden
                $userEX->UpdateAllowRemoteAccess(1);
                break;
            case 2://some allowed
                //forbid all
                $userEX->UpdateAllowRemoteAccess(1);
                //allow some
                $allowedUsers_str = '';
                foreach ($allowedUsers as $value) {
                    $allowedUsers_str .= $value . ",";
                }
                $allowedUsers_str = rtrim($allowedUsers_str, ',');
                $userEX->UpdateAllowRemoteAccess(0, " and userid in($allowedUsers_str)");
                break;
            default:
                break;
        }
        switch ($allowMobileLogin) {
            case 0://allowed
                $userEX->UpdateAllowRemoteAccessMobile(0);
                break;
            case 1://forbidden
                $userEX->UpdateAllowRemoteAccessMobile(1);
                break;
            case 2://some allowed
                //forbid all
                $userEX->UpdateAllowRemoteAccessMobile(1);
                //allow some
                $allowedUsers_str = '';
                foreach ($allowedMobileUsers as $value) {
                    $allowedUsers_str .= $value . ",";
                }
                $allowedUsers_str = rtrim($allowedUsers_str, ',');
                $userEX->UpdateAllowRemoteAccessMobile(0, " and userid in($allowedUsers_str)");
                break;
            default:
                break;
        }



        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    $smarty->display("succes.html");
} elseif ($do == "error") {
    $smarty->display("error.html");
}

//here the global templates
//$smarty->assign('customValidation', 1);

if (empty($do) || $do == "show" || $do == "sucess" || $do == "error") {
    $smarty->assign("customgt4setting", 1);
    $smarty->display("footer.html");
}
/* ===============================
  function in this CONTROLLER
  ================================ */
?>