<?php

//the global file operation
include("../public/impOpreation.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");
//properities
require_once('../models/dao/PropertiesDAO.class.php');
require_once('../models/dto/Propertie.class.php');
require_once('../models/mysql/PropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/PropertiesMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//Relusergroupproperties
require_once('../models/dao/RelusergrouppropertiesDAO.class.php');
require_once('../models/dto/Relusergrouppropertie.class.php');
require_once('../models/mysql/RelusergrouppropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/RelusergrouppropertiesMySqlExtDAO.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');

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 :- usergroupCTRL

  OPERTATION in Controller

  1-load property data from properities tble
  2-display add form
  2- add in usergroup and relusergroupproperties tble
  3-display sucess or error
  4-display show form
  5-delete from usergroup tble
  6-edit in usergroup data

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

//include_once("../public/auth.php");
//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
$myProperitiesRecord = new PropertiesMySqlDAO();
$myProperitiesEx = new PropertiesMySqlExtDAO();

$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();

$myRelusergroup = new Relusergrouppropertie();
$myRelusergroupRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergroupEx = $myRelusergrouppropertieExt = new RelusergrouppropertiesMySqlExtDAO();

$myUserRecord = new UserMySqlDAO();

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

//check and use the condetion that suite this action
if (empty($do)) {
    $data = loadproperity();

    $smarty->assign("properityData", $data[0]);
    $smarty->assign("properityNum", $data[1]);


    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    /* $mantanceData = propmantance();
      print_r($mantanceData); */
    //here the smarty templates
    $smarty->display("usergroupview/add.html");
} elseif ($do == "add") {
    //    add();
    $allPropsJson = $_POST['allPropsJson'];
    foreach (json_decode($allPropsJson) as $key => $value) {
        $_POST[$key] = $value;
    }
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    $userGroupData = show();
    $smarty->assign("userGroupData", $userGroupData);
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("usergroupview/show.html");

    $smarty->assign('customUsergroup', 1);
    $smarty->assign('customCheck', 1);
} elseif ($do == "execute") {
    try {
        executeOperation();
        $userGroupData = show();
        $smarty->assign("userGroupData", $userGroupData);
        $smarty->display("usergroupview/show.html");

        $smarty->assign('customUsergroup', 1);
        $smarty->assign('customCheck', 1);
    } catch (Exception $e) {
        //echo $e;
        $smarty->display("error.html");
    }
} elseif ($do == "returndelete") { //returndelete
    include_once("../public/authentication.php");
    try {
        returndelete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    include_once("../public/authentication.php");
    try {
        $note = tempdelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deleteFinaly") {
    try {
        $note = deleteFinaly();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        echo $e;
        //header("location:?do=error");
    }
} elseif ($do == "edit") {
    $editData = edit();
    /* print_r('<pre>');
      print_r($editData[1]); */
    $smarty->assign("loadData", $editData[0]);
    $smarty->assign("loginSessionUsergroupId", $_SESSION['usergroupid']);
    //print_r('<pre>');
    $smarty->assign("properityData", $editData[1]);
    $smarty->assign("properityNum", $editData[2]);

    $smarty->display("usergroupview/edit.html");
} elseif ($do == "update") {
    $allPropsJson = $_POST['allPropsJson'];
    foreach (json_decode($allPropsJson) as $key => $value) {
        $_POST[$key] = $value;
    }
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    $editData = edit();
    $smarty->assign("loadData", $editData[0]);
    $smarty->assign("properityData", $editData[1]);
    $smarty->assign("properityNum", $editData[2]);

    $smarty->display("usergroupview/editprint.html");
} elseif ($_GET['do'] == "copy") {
    try {
        $usergroupid = (int) $_GET['id'];
        if ($usergroupid > 0) {
            copyUserGroup($usergroupid);
        } else {
            echo "wrong choice";
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
        //	echo $e;
    }
} elseif ($do == "sucess") {
    $smarty->display("succes.html");
} elseif ($do == "error") {
    $smarty->display("error.html");
}

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

$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */

// select from properity tbl
function loadproperity() {
    global $myProperitiesRecord;
    global $myProperitiesEx;

    // select all data from properity tbl
    //$properityData = $myProperitiesRecord->queryAll();
    $properityData = $myProperitiesEx->queryAllEX();
    //get count of selected Data
    $properityNum = count($properityData);
    return array($properityData, $properityNum);
}

function propmantance() {
    global $myProperitiesRecord;

    // select all data from properity tbl
    $mantanceData = $myProperitiesRecord->queryByPropertyparent(164);

    return $mantanceData;
}

// add in usergroup tbl
function add() {
    global $myUserGroup;
    global $myUserGroupRecord;
    global $myRelusergroup;
    global $myRelusergroupRecord;

    $userGroupName = $_POST['usergroupname'];
    $userGroupDescription = $_POST['usergroupdescription'];
    $startPage = $_POST['startpage'];
    $level = $_POST['level'];


    $savedailydate = $_POST['savedailydate'];
    $hidemenu = $_POST['hidemenu'];
    $editUserPrivlage = $_POST['editUserPrivlage'];
    $hidecat = $_POST['hidecat'];


    $itr = $_POST['itr'];


    $clientnegative = $_POST['clientnegative'];
    $suplliernegative = $_POST['suplliernegative'];
    $storenegative = $_POST['storenegative'];
    $priceupdate = $_POST['priceupdate'];
    $directDiscount = $_POST['directDiscount'];
    $percentageDiscount = $_POST['percentageDiscount'];
    $allowEditDelInBills = $_POST['allowEditDelInBills'];
    $allowEditDelInBuyBills = $_POST['allowEditDelInBuyBills'];

    $showsStorerQuantity = $_POST['showsStorerQuantity'];
    $showSellAllPrice = $_POST['showSellAllPrice'];
    $showSellHalfPrice = $_POST['showSellHalfPrice'];
    $showSellUnitPrice = $_POST['showSellUnitPrice'];
    $showBuyPrice = $_POST['showBuyPrice'];

    $productno = $_POST['productno'];
    $kempilano = $_POST['kempilano'];
    $productnotsellno = $_POST['productnotsellno'];
    $clientcheckno = $_POST['clientcheckno'];
    $suppliercheckno = $_POST['suppliercheckno'];
    $productRequist = $_POST['productRequist'];
    $otherRequist = $_POST['otherRequist'];
    $toWorkShopOrder = $_POST['toWorkShopOrder'];
    $insuranceBill = $_POST['insuranceBill'];
    $sellreportpricetype = $_POST['sellreportpricetype'];
    $netprofit = $_POST['netprofit'];
    $directSaveBills = $_POST['directSaveBills'];
    $seeAllHalls = (int) $_POST['seeAllHalls'];
    $homePageIcon = (int) $_POST['homePageIcon'];
    $autoKitchenPrint = (int) $_POST['autoKitchenPrint'];
    $sendKitchen = (int) $_POST['sendKitchen'];
    $printKitchen = (int) $_POST['printKitchen'];
    $endBill = (int) $_POST['endBill'];
    $endPrintBill = (int) $_POST['endPrintBill'];
    $takeAway = (int) $_POST['takeAway'];
    $delivery = (int) $_POST['delivery'];
    $hall = (int) $_POST['hall'];
    $showManualBackup = (int) $_POST['showManualBackup'];
    $deleteMovementManage = (int) $_POST['deleteMovementManage'];
    $allowBillDelete = (int) $_POST['allowBillDelete'];
    $billDeletePassword = $_POST['billDeletePassword'];
    $downloadClientPhones = (int) $_POST['downloadClientPhones'];
    $showstoredetailprice = (int) $_POST['showstoredetailprice'];
    $stopDiscountOfTotalControl = (int) $_POST['stopDiscountOfTotalControl'];
    $discountOfTotalControlEditable = (int) $_POST['discountOfTotalControlEditable'];
    $discountOfTotalControlMTGDA = (int) $_POST['discountOfTotalControlMTGDA']; //MTGDA more than group discount Allowed
    $kitchenPayedVal = (int) $_POST['kitchenPayedVal'];
    $kitchenPayedChange = (int) $_POST['kitchenPayedChange'];
    $showsIndexStatistics = (int) $_POST['showsIndexStatistics'];
    $showsIndexCharts = (int) $_POST['showsIndexCharts'];
    $showsIndexProductBelowLimitReport = (int) $_POST['showsIndexProductBelowLimitReport'];
    $restaurantplaystationpalyBtn = (int) $_POST['restaurantplaystationpalyBtn'];
    $restaurantDefaultPage = (int) $_POST['restaurantDefaultPage'];
    $mandobMethod = (int) $_POST['mandobMethod'];
    $addClientInBill = (int) $_POST['addClientInBill'];
    $addsupplierInBill = (int) $_POST['addsupplierInBill'];
    $hideBillPrices = (int) $_POST['hideBillPrices'];
    $showSerializeBtn = (int) $_POST['showSerializeBtn'];
    $showClientAndSupplierOne = (int) $_POST['showClientAndSupplierOne'];
    $dontChooseStore = (int) $_POST['dontChooseStore'];
    $allowStoreMoveUpdateDel = (int) $_POST['allowStoreMoveUpdateDel'];
    $showProfitInsideBill = (int) $_POST['showProfitInsideBill'];
    $storeSupervisorShow = (int) $_POST['storeSupervisorShow'];
    $reviewBillsAllowedTables = (isset($_POST['reviewBillsAllowedTables'])) ? (string) implode(",", $_POST['reviewBillsAllowedTables']) : '';
    $showSaveBalanceAfterClose = (int) $_POST['showSaveBalanceAfterClose'];
    $canEditAddDiscountPercentage = (int) $_POST['canEditAddDiscountPercentage'];
    $noBillEditIfTheirIsPayments = (int) $_POST['noBillEditIfTheirIsPayments'];

    //insert data in usergroup tbl
    $myUserGroup->priceupdate = $priceupdate;
    $myUserGroup->directDiscount = $directDiscount;
    $myUserGroup->percentageDiscount = $percentageDiscount;
    $myUserGroup->allowEditDelInBills = $allowEditDelInBills;
    $myUserGroup->allowEditDelInBuyBills = $allowEditDelInBuyBills;

    $myUserGroup->clientnegative = $clientnegative;
    $myUserGroup->suplliernegative = $suplliernegative;
    $myUserGroup->storenegative = $storenegative;

    $myUserGroup->currentdate = date("Y-m-d");
    $myUserGroup->conditions = 0;
    $myUserGroup->usergroupname = $userGroupName;
    $myUserGroup->startpage = $startPage;
    $myUserGroup->level = $level;
    $myUserGroup->savedailydate = $savedailydate;
    $myUserGroup->usergroupdescription = $userGroupDescription;
    $myUserGroup->hidemenu = $hidemenu;
    $myUserGroup->editUserPrivlage = $editUserPrivlage;
    $myUserGroup->hidecat = $hidecat;

    $myUserGroup->showsStorerQuantity = $showsStorerQuantity;
    $myUserGroup->showSellAllPrice = $showSellAllPrice;
    $myUserGroup->showSellHalfPrice = $showSellHalfPrice;
    $myUserGroup->showSellUnitPrice = $showSellUnitPrice;
    $myUserGroup->showBuyPrice = $showBuyPrice;

    $myUserGroup->productno = $productno;
    $myUserGroup->kempilano = $kempilano;
    $myUserGroup->productnotsellno = $productnotsellno;
    $myUserGroup->clientcheckno = $clientcheckno;
    $myUserGroup->suppliercheckno = $suppliercheckno;
    $myUserGroup->productRequist = $productRequist;
    $myUserGroup->otherRequist = $otherRequist;
    $myUserGroup->toWorkShopOrder = $toWorkShopOrder;
    $myUserGroup->insuranceBill = $insuranceBill;
    $myUserGroup->sellreportpricetype = $sellreportpricetype;
    $myUserGroup->netprofit = $netprofit;
    $myUserGroup->directSaveBills = $directSaveBills;
    $myUserGroup->seeAllHalls = $seeAllHalls;
    $myUserGroup->homePageIcon = $homePageIcon;
    $myUserGroup->autoKitchenPrint = $autoKitchenPrint;
    $myUserGroup->sendKitchen = $sendKitchen;
    $myUserGroup->printKitchen = $printKitchen;
    $myUserGroup->endBill = $endBill;
    $myUserGroup->endPrintBill = $endPrintBill;
    $myUserGroup->takeAway = $takeAway;
    $myUserGroup->delivery = $delivery;
    $myUserGroup->hall = $hall;
    $myUserGroup->showManualBackup = $showManualBackup;
    $myUserGroup->deleteMovementManage = $deleteMovementManage;
    $myUserGroup->allowBillDelete = $allowBillDelete;
    $myUserGroup->billDeletePassword = $billDeletePassword;
    $myUserGroup->reviewBillsAllowedTables = $reviewBillsAllowedTables;
    $myUserGroup->downloadClientPhones = $downloadClientPhones;
    $myUserGroup->showstoredetailprice = $showstoredetailprice;
    $myUserGroup->stopDiscountOfTotalControl = $stopDiscountOfTotalControl;
    $myUserGroup->discountOfTotalControlEditable = $discountOfTotalControlEditable;
    $myUserGroup->discountOfTotalControlMTGDA = $discountOfTotalControlMTGDA;
    $myUserGroup->kitchenPayedVal = $kitchenPayedVal;
    $myUserGroup->kitchenPayedChange = $kitchenPayedChange;
    $myUserGroup->showsIndexStatistics = $showsIndexStatistics;
    $myUserGroup->showsIndexCharts = $showsIndexCharts;
    $myUserGroup->showsIndexProductBelowLimitReport = $showsIndexProductBelowLimitReport;
    $myUserGroup->restaurantplaystationpalyBtn = $restaurantplaystationpalyBtn;
    $myUserGroup->restaurantDefaultPage = $restaurantDefaultPage;
    $myUserGroup->mandobMethod = $mandobMethod;
    $myUserGroup->addClientInBill = $addClientInBill;
    $myUserGroup->addsupplierInBill = $addsupplierInBill;
    $myUserGroup->hideBillPrices = $hideBillPrices;
    $myUserGroup->showSerializeBtn = $showSerializeBtn;
    $myUserGroup->showClientAndSupplierOne = $showClientAndSupplierOne;
    $myUserGroup->dontChooseStore = $dontChooseStore;
    $myUserGroup->allowStoreMoveUpdateDel = $allowStoreMoveUpdateDel;
    $myUserGroup->showProfitInsideBill = $showProfitInsideBill;
    $myUserGroup->storeSupervisorShow = $storeSupervisorShow;
    $myUserGroup->showSaveBalanceAfterClose = $showSaveBalanceAfterClose;
    $myUserGroup->canEditAddDiscountPercentage = $canEditAddDiscountPercentage;
    $myUserGroup->noBillEditIfTheirIsPayments = $noBillEditIfTheirIsPayments;



    $userGroupId = $myUserGroupRecord->insert($myUserGroup);

    //insert data in relusergroupproperties tbl
    $h = 1;
    for ($h = 1; $h <= $itr; $h++) {
        $propertyValue = $_POST['propertydefault' . $h . ''];
        $propertyId = $_POST['propertyid' . $h . ''];
        $theorder = $_POST['theorder' . $h . ''];

        $myRelusergroup->propertyid = $propertyId;
        $myRelusergroup->propertyvalue = $propertyValue;
        $myRelusergroup->usergroupid = $userGroupId;
        $myRelusergroup->theorder = $theorder;

        $myRelusergroupRecord->insert($myRelusergroup);
    }
}

// show the form
function show() {
    global $myUserGroupEx;

    //select all data from usergroup tbl
    $userGroupData = $myUserGroupEx->queryAllwithOrder();
    return $userGroupData;
}

function executeOperation() {
    global $myUserGroupRecord;
    global $myUserGroupEx;
    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

    $choosedItemArr = $_POST['choosedItem'];
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $usergroupid) {
            if ($operationType == '1') { //tempdelete
                $note = tempdelete($usergroupid);
            } elseif ($operationType == "2") { //returndelete
                $note = returndelete($usergroupid);
            } elseif ($operationType == "3") { //deleteFinaly
                $note = deleteFinaly($usergroupid);
            }

            if ($note != "success") {
                //get usergroup name
                $usergroupData = $myUserGroupRecord->load($usergroupid);
                if (count($usergroupData) > 0) {
                    $usergroupname = $usergroupData->usergroupname;
                    $outputString .= $usergroupname . ": " . $note . "<br/>";
                }
            } else {
                $outputString .= "تمت العملية بنجاح";
            }
            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function tempdelete($usergroupid = 0) {
    global $myUserGroupEx;
    global $myUserGroupRecord;

    if (empty($usergroupid) || $usergroupid == 0) {
        $usergroupid = $_GET['id'];
    }
    if (!empty($usergroupid)) {
        try {
            //temp delete from usergroup tbl
            $myUserGroupEx->deletetemp($usergroupid);
            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

function returndelete($usergroupid = 0) {
    global $myUserGroupEx;
    $note;
    if (empty($usergroupid) || $usergroupid == 0) {
        $usergroupid = $_GET['id'];
    }

    if (!empty($usergroupid)) {
        try {
            //return delete from usergroup tbl
            $myUserGroupEx->returndelete($usergroupid);
            $note = "success";
        } catch (Exception $e) {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

//finaly deleted from usergroup tbl
function deleteFinaly($userGroupId = 0) {
    global $myUserGroupRecord;
    global $myRelusergroupRecord;
    global $myUserRecord;
    $note;

    if (empty($userGroupId) || $userGroupId == 0) {
        //get variable
        $userGroupId = $_GET['id'];
    }

    if (!empty($userGroupId)) {
        //check if find usergroupid in user tbl
        $userValidation = $myUserRecord->queryByUsergroupid($userGroupId);
        if (count($userValidation) <= 0) {
            try {
                //delete from usergroup tbl and relusergroupproperties tbl
                $myRelusergroupRecord->deleteByUsergroupid($userGroupId);
                $myUserGroupRecord->delete($userGroupId);
                $note = "success";
            } catch (Exception $e) {
                $note = "حدث خطأ أثناء إتمام العملية";
            }
        } else {
            $note = "لا يمكنك حذف هذه المجموعة إلا بعد حذف المستخدم المرتبط به";
        }
    } else {
        $note = "حدث خطأ أثناء إتمام العملية";
    }
    return $note;
}

// edit in table
function edit() {
    global $myUserGroup;
    global $myUserGroupRecord;
    global $myRelusergroupEx;

    //get variable
    $userGroupId = $_GET['id'];
    //load data by usergroupid
    $loadData = $myUserGroupRecord->load($userGroupId);
    $loadData->reviewBillsAllowedTables = explode(",", $loadData->reviewBillsAllowedTables);

    // select all data from properity and relusergroupproperties tbl by usergroupid
    $properityData = $myRelusergroupEx->queryAllwithUsergroupid($userGroupId);
    //get count of selected Data
    $properityNum = count($properityData);
    return array($loadData, $properityData, $properityNum);
}

// update table
function update() {
    global $myUserGroup;
    global $myUserGroupRecord;
    global $myUserGroupEx;
    global $myRelusergroup;
    global $myRelusergroupRecord;


    $userGroupId = $_POST['usergroupid'];
    $myUserGroup = $myUserGroupRecord->load($userGroupId);
    //post variable
    $itr = isset($_POST['itr']) ? $_POST['itr'] : $myUserGroup->itr;

    $updateQueryString = getUpdateQuery();
    if (!empty($updateQueryString)) {
        $myUserGroupEx->updateByQueryString($updateQueryString);
    }

    //    //insert data in usergroup tbl
    //    $myUserGroup->priceupdate = isset($_POST['priceupdate']) ? $_POST['priceupdate'] : $myUserGroup->priceupdate;
    //    $myUserGroup->directDiscount = isset($_POST['directDiscount']) ? $_POST['directDiscount'] : $myUserGroup->directDiscount;
    //    $myUserGroup->percentageDiscount = isset($_POST['percentageDiscount']) ? $_POST['percentageDiscount'] : $myUserGroup->percentageDiscount;
    //    $myUserGroup->allowEditDelInBills = isset($_POST['allowEditDelInBills']) ? $_POST['allowEditDelInBills'] : $myUserGroup->allowEditDelInBills;
    //    $myUserGroup->allowEditDelInBuyBills = isset($_POST['allowEditDelInBuyBills']) ? $_POST['allowEditDelInBuyBills'] : $myUserGroup->allowEditDelInBuyBills;
    //
    //
    //    $myUserGroup->clientnegative = isset($_POST['clientnegative']) ? $_POST['clientnegative'] : $myUserGroup->clientnegative;
    //    $myUserGroup->suplliernegative = isset($_POST['suplliernegative']) ? $_POST['suplliernegative'] : $myUserGroup->suplliernegative;
    //    $myUserGroup->storenegative = isset($_POST['storenegative']) ? $_POST['storenegative'] : $myUserGroup->storenegative;
    //
    //    $myUserGroup->currentdate = isset($_POST['today']) ? $_POST['today'] : $myUserGroup->currentdate;
    //    $myUserGroup->conditions = isset($_POST['delete']) ? $_POST['delete'] : $myUserGroup->conditions;
    //    $myUserGroup->usergroupname = isset($_POST['usergroupname']) ? $_POST['usergroupname'] : $myUserGroup->usergroupname;
    //    $myUserGroup->usergroupid = $userGroupId;
    //    $myUserGroup->startpage = isset($_POST['startpage']) ? $_POST['startpage'] : $myUserGroup->startpage;
    //    $myUserGroup->level = isset($_POST['level']) ? $_POST['level'] : $myUserGroup->level;
    //
    //    $myUserGroup->savedailydate = isset($_POST['savedailydate']) ? $_POST['savedailydate'] : $myUserGroup->savedailydate;
    //    $myUserGroup->usergroupdescription = isset($_POST['usergroupdescription']) ? $_POST['usergroupdescription'] : $myUserGroup->usergroupdescription;
    //    $myUserGroup->hidemenu = isset($_POST['hidemenu']) ? $_POST['hidemenu'] : $myUserGroup->hidemenu;
    //    $myUserGroup->hidecat = isset($_POST['hidecat']) ? $_POST['hidecat'] : $myUserGroup->hidecat;
    //
    //    $myUserGroup->showsStorerQuantity = isset($_POST['showsStorerQuantity']) ? $_POST['showsStorerQuantity'] : $myUserGroup->showsStorerQuantity;
    //    $myUserGroup->showSellAllPrice = isset($_POST['showSellAllPrice']) ? $_POST['showSellAllPrice'] : $myUserGroup->showSellAllPrice;
    //    $myUserGroup->showSellHalfPrice = isset($_POST['showSellHalfPrice']) ? $_POST['showSellHalfPrice'] : $myUserGroup->showSellHalfPrice;
    //    $myUserGroup->showSellUnitPrice = isset($_POST['showSellUnitPrice']) ? $_POST['showSellUnitPrice'] : $myUserGroup->showSellUnitPrice;
    //    $myUserGroup->showBuyPrice = isset($_POST['showBuyPrice']) ? $_POST['showBuyPrice'] : $myUserGroup->showBuyPrice;
    //
    //    $myUserGroup->productno = isset($_POST['productno']) ? $_POST['productno'] : $myUserGroup->productno;
    //    $myUserGroup->kempilano = isset($_POST['kempilano']) ? $_POST['kempilano'] : $myUserGroup->kempilano;
    //    $myUserGroup->productnotsellno = isset($_POST['productnotsellno']) ? $_POST['productnotsellno'] : $myUserGroup->productnotsellno;
    //    $myUserGroup->clientcheckno = isset($_POST['clientcheckno']) ? $_POST['clientcheckno'] : $myUserGroup->clientcheckno;
    //    $myUserGroup->suppliercheckno = isset($_POST['suppliercheckno']) ? $_POST['suppliercheckno'] : $myUserGroup->suppliercheckno;
    //    $myUserGroup->productRequist = isset($_POST['productRequist']) ? $_POST['productRequist'] : $myUserGroup->productRequist;
    //    $myUserGroup->otherRequist = isset($_POST['otherRequist']) ? $_POST['otherRequist'] : $myUserGroup->otherRequist;
    //    $myUserGroup->toWorkShopOrder = isset($_POST['toWorkShopOrder']) ? $_POST['toWorkShopOrder'] : $myUserGroup->toWorkShopOrder;
    //    $myUserGroup->insuranceBill = isset($_POST['insuranceBill']) ? $_POST['insuranceBill'] : $myUserGroup->insuranceBill;
    //    $myUserGroup->sellreportpricetype = isset($_POST['sellreportpricetype']) ? $_POST['sellreportpricetype'] : $myUserGroup->sellreportpricetype;
    //    $myUserGroup->netprofit = isset($_POST['netprofit']) ? $_POST['netprofit'] : $myUserGroup->netprofit;
    //    $myUserGroup->hideproductcatid = isset($_POST['hideproductcatid']) ? $_POST['hideproductcatid'] : $myUserGroup->hideproductcatid;
    //    $myUserGroup->directSaveBills = isset($_POST['directSaveBills']) ? $_POST['directSaveBills'] : $myUserGroup->directSaveBills;
    //    $myUserGroup->seeAllHalls = isset($_POST['seeAllHalls']) ? (int) $_POST['seeAllHalls'] : $myUserGroup->seeAllHalls;
    //    $myUserGroup->homePageIcon = isset($_POST['homePageIcon']) ? (int) $_POST['homePageIcon'] : $myUserGroup->homePageIcon;
    //    $myUserGroup->autoKitchenPrint = isset($_POST['autoKitchenPrint']) ? (int) $_POST['autoKitchenPrint'] : $myUserGroup->autoKitchenPrint;
    //    $myUserGroup->sendKitchen = isset($_POST['sendKitchen']) ? (int) $_POST['sendKitchen'] : $myUserGroup->sendKitchen;
    //    $myUserGroup->printKitchen = isset($_POST['printKitchen']) ? (int) $_POST['printKitchen'] : $myUserGroup->printKitchen;
    //    $myUserGroup->endBill = isset($_POST['endBill']) ? (int) $_POST['endBill'] : $myUserGroup->endBill;
    //    $myUserGroup->endPrintBill = isset($_POST['endPrintBill']) ? (int) $_POST['endPrintBill'] : $myUserGroup->endPrintBill;
    //    $myUserGroup->takeAway = isset($_POST['takeAway']) ? (int) $_POST['takeAway'] : $myUserGroup->takeAway;
    //    $myUserGroup->delivery = isset($_POST['delivery']) ? (int) $_POST['delivery'] : $myUserGroup->delivery;
    //    $myUserGroup->hall = isset($_POST['hall']) ? (int) $_POST['hall'] : $myUserGroup->hall;
    //    $myUserGroup->showManualBackup = isset($_POST['showManualBackup']) ? (int) $_POST['showManualBackup'] : $myUserGroup->showManualBackup;
    //    $myUserGroup->deleteMovementManage = isset($_POST['deleteMovementManage']) ? (int) $_POST['deleteMovementManage'] : $myUserGroup->deleteMovementManage;
    //    $myUserGroup->allowBillDelete = isset($_POST['allowBillDelete']) ? (int) $_POST['allowBillDelete'] : $myUserGroup->allowBillDelete;
    //    $myUserGroup->billDeletePassword = isset($_POST['billDeletePassword']) ? $_POST['billDeletePassword'] : $myUserGroup->billDeletePassword;
    //    $myUserGroup->reviewBillsAllowedTables = isset($_POST['reviewBillsAllowedTables']) ? (string) implode(",", $_POST['reviewBillsAllowedTables']) : $myUserGroup->reviewBillsAllowedTables;
    //    $myUserGroup->downloadClientPhones = isset($_POST['downloadClientPhones']) ? $_POST['downloadClientPhones'] : $myUserGroup->downloadClientPhones;
    //
    //    $myUserGroupRecord->update($myUserGroup);
    //update data in relusergroupproperties tbl

    $h = 1;
    for ($h = 1; $h <= $itr; $h++) {
        $propertyValue = $_POST['propertydefault' . $h . ''];
        $propertyId = $_POST['propertyid' . $h . ''];
        $relusergrouppropertiesId = $_POST['relusergrouppropertiesid' . $h . ''];
        $theorder = $_POST['theorder' . $h . ''];
        if (isset($relusergrouppropertiesId) && !empty($relusergrouppropertiesId)) {
            $myRelusergroup->propertyid = $propertyId;
            $myRelusergroup->propertyvalue = $propertyValue;
            $myRelusergroup->usergroupid = $userGroupId;
            $myRelusergroup->theorder = $theorder;
            $myRelusergroup->relusergrouppropertiesid = $relusergrouppropertiesId;

            $myRelusergroupRecord->update($myRelusergroup);
        } elseif (isset($propertyId) && !empty($propertyId)) {
            $myRelusergroup->propertyid = $propertyId;
            $myRelusergroup->propertyvalue = $propertyValue;
            $myRelusergroup->usergroupid = $userGroupId;
            $myRelusergroup->theorder = $theorder;
            //$myRelusergroup->relusergrouppropertiesid = $relusergrouppropertiesId;

            $myRelusergroupRecord->insert($myRelusergroup);
        }
    }
    $fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
    fclose($fh);
    //update sessions
    if ($_SESSION['usergroupid'] == $userGroupId) {
        $_SESSION['hidecat'] = $myUserGroup->hidecat;
        $_SESSION['clientnegative'] = $myUserGroup->clientnegative;
        $_SESSION['suplliernegative'] = $myUserGroup->suplliernegative;
        $_SESSION['storenegative'] = $myUserGroup->storenegative;
    }
}

function copyUserGroup($usergroupid) {
    global $myUserGroup;
    global $myUserGroupRecord;
    global $myRelusergroup;
    global $myRelusergroupRecord;
    global $myRelusergrouppropertieExt;

    //get data
    $myUserGroup = $myUserGroupRecord->load($usergroupid);
    $myRelusergroup = $myRelusergroupRecord->queryByUsergroupid($usergroupid);

    ##1-insert usergroup data
    $myUserGroup->usergroupid = NULL;
    $myUserGroup->currentdate = date("Y-m-d");
    $usergroupid_new = $myUserGroupRecord->insert($myUserGroup);
    $myUserGroup->usergroupname = $myUserGroup->usergroupname . "_" . $usergroupid_new;
    $myUserGroupRecord->update($myUserGroup);

    ##1-insert user group rules data
    $insert_sql = "INSERT INTO `relusergroupproperties` (`usergroupid`, `propertyid`, `propertyvalue`) VALUES";
    foreach ($myRelusergroup as $value) {
        $insert_sql .= "(" . $usergroupid_new . ", " . $value->propertyid . ", " . $value->propertyvalue . "),";
    }
    $insert_sql = trim($insert_sql, ',');
    $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
}

function getUpdateQuery() {
    $query = '';
    if (isset($_POST['usergroupname']))
        $query .= ",usergroupname='" . $_POST['usergroupname'] . "'";

    if (isset($_POST['usergroupdescription']))
        $query .= ",usergroupdescription='" . $_POST['usergroupdescription'] . "'";

    //never changed
    //    if (isset($_POST['today']))
    //        $query.=",currentdate='" . $_POST['today'] . "'";

    if (isset($_POST['delete']))
        $query .= ",conditions=" . $_POST['delete'];

    if (isset($_POST['startpage']))
        $query .= ",startpage='" . $_POST['startpage'] . "'";

    if (isset($_POST['level']))
        $query .= ",level=" . $_POST['level'];

    if (isset($_POST['savedailydate']))
        $query .= ",savedailydate=" . $_POST['savedailydate'];

    if (isset($_POST['hidemenu']))
        $query .= ",hidemenu=" . $_POST['hidemenu'];

    if (isset($_POST['editUserPrivlage']))
        $query .= ",editUserPrivlage=" . $_POST['editUserPrivlage'];

    if (isset($_POST['hidecat']))
        $query .= ",hidecat=" . $_POST['hidecat'];

    if (isset($_POST['clientnegative']))
        $query .= ",clientnegative=" . $_POST['clientnegative'];

    if (isset($_POST['suplliernegative']))
        $query .= ",suplliernegative=" . $_POST['suplliernegative'];

    if (isset($_POST['storenegative']))
        $query .= ",storenegative=" . $_POST['storenegative'];

    if (isset($_POST['directDiscount']))
        $query .= ",directDiscount='" . $_POST['directDiscount'] . "'";

    if (isset($_POST['percentageDiscount']))
        $query .= ",percentageDiscount='" . $_POST['percentageDiscount'] . "'";

    if (isset($_POST['priceupdate']))
        $query .= ",priceupdate=" . $_POST['priceupdate'];

    if (isset($_POST['allowEditDelInBills']))
        $query .= ",allowEditDelInBills=" . $_POST['allowEditDelInBills'];

    if (isset($_POST['allowEditDelInBuyBills']))
        $query .= ",allowEditDelInBuyBills=" . $_POST['allowEditDelInBuyBills'];

    if (isset($_POST['showsStorerQuantity']))
        $query .= ",showsStorerQuantity=" . $_POST['showsStorerQuantity'];

    if (isset($_POST['showSellAllPrice']))
        $query .= ",showSellAllPrice=" . $_POST['showSellAllPrice'];

    if (isset($_POST['showSellHalfPrice']))
        $query .= ",showSellHalfPrice=" . $_POST['showSellHalfPrice'];

    if (isset($_POST['showSellUnitPrice']))
        $query .= ",showSellUnitPrice=" . $_POST['showSellUnitPrice'];

    if (isset($_POST['showBuyPrice']))
        $query .= ",showBuyPrice=" . $_POST['showBuyPrice'];

    if (isset($_POST['productno']))
        $query .= ",productno=" . $_POST['productno'];

    if (isset($_POST['kempilano']))
        $query .= ",kempilano=" . $_POST['kempilano'];

    if (isset($_POST['productnotsellno']))
        $query .= ",productnotsellno=" . $_POST['productnotsellno'];

    if (isset($_POST['clientcheckno']))
        $query .= ",clientcheckno=" . $_POST['clientcheckno'];

    if (isset($_POST['suppliercheckno']))
        $query .= ",suppliercheckno=" . $_POST['suppliercheckno'];

    if (isset($_POST['productRequist']))
        $query .= ",productRequist=" . $_POST['productRequist'];

    if (isset($_POST['otherRequist']))
        $query .= ",otherRequist=" . $_POST['otherRequist'];

    if (isset($_POST['toWorkShopOrder']))
        $query .= ",toWorkShopOrder=" . $_POST['toWorkShopOrder'];

    if (isset($_POST['insuranceBill']))
        $query .= ",insuranceBill=" . $_POST['insuranceBill'];

    if (isset($_POST['sellreportpricetype']))
        $query .= ",sellreportpricetype=" . $_POST['sellreportpricetype'];

    if (isset($_POST['netprofit']))
        $query .= ",netprofit=" . $_POST['netprofit'];

    if (isset($_POST['hideproductcatid']))
        $query .= ",hideproductcatid=" . $_POST['hideproductcatid'];

    if (isset($_POST['directSaveBills']))
        $query .= ",directSaveBills=" . $_POST['directSaveBills'];

    if (isset($_POST['seeAllHalls']))
        $query .= ",seeAllHalls=" . $_POST['seeAllHalls'];

    if (isset($_POST['homePageIcon']))
        $query .= ",homePageIcon=" . $_POST['homePageIcon'];

    if (isset($_POST['sendKitchen']))
        $query .= ",sendKitchen=" . (int) $_POST['sendKitchen'];

    if (isset($_POST['printKitchen']))
        $query .= ",printKitchen=" . (int) $_POST['printKitchen'];

    if (isset($_POST['endBill']))
        $query .= ",endBill=" . (int) $_POST['endBill'];

    if (isset($_POST['endPrintBill']))
        $query .= ",endPrintBill=" . (int) $_POST['endPrintBill'];

    if (isset($_POST['showManualBackup']))
        $query .= ",showManualBackup=" . $_POST['showManualBackup'];

    if (isset($_POST['autoKitchenPrint']))
        $query .= ",autoKitchenPrint=" . $_POST['autoKitchenPrint'];

    if (isset($_POST['takeAway']))
        $query .= ",takeAway=" . $_POST['takeAway'];

    if (isset($_POST['delivery']))
        $query .= ",delivery=" . $_POST['delivery'];

    if (isset($_POST['hall']))
        $query .= ",hall=" . $_POST['hall'];

    if (isset($_POST['deleteMovementManage']))
        $query .= ",deleteMovementManage=" . $_POST['deleteMovementManage'];

    if (isset($_POST['allowBillDelete']))
        $query .= ",allowBillDelete=" . $_POST['allowBillDelete'];

    if (isset($_POST['billDeletePassword']))
        $query .= ",billDeletePassword='" . $_POST['billDeletePassword'] . "'";

    if (isset($_POST['reviewBillsAllowedTables']))
        $query .= ",reviewBillsAllowedTables='" . (string) implode(",", $_POST['reviewBillsAllowedTables']) . "'";

    if (isset($_POST['downloadClientPhones']))
        $query .= ",downloadClientPhones=" . $_POST['downloadClientPhones'];

    if (isset($_POST['showstoredetailprice']))
        $query .= ",showstoredetailprice=" . $_POST['showstoredetailprice'];

    if (isset($_POST['stopDiscountOfTotalControl']))
        $query .= ",stopDiscountOfTotalControl=" . $_POST['stopDiscountOfTotalControl'];
    if (isset($_POST['discountOfTotalControlEditable']))
        $query .= ",discountOfTotalControlEditable=" . $_POST['discountOfTotalControlEditable'];
    if (isset($_POST['discountOfTotalControlMTGDA'])) ////MTGDA more than group discount Allowed
        $query .= ",discountOfTotalControlMTGDA=" . $_POST['discountOfTotalControlMTGDA'];

    if (isset($_POST['kitchenPayedVal']))
        $query .= ",kitchenPayedVal=" . $_POST['kitchenPayedVal'];
    if (isset($_POST['kitchenPayedChange']))
        $query .= ",kitchenPayedChange=" . $_POST['kitchenPayedChange'];
    if (isset($_POST['showsIndexStatistics']))
        $query .= ",showsIndexStatistics=" . $_POST['showsIndexStatistics'];
    if (isset($_POST['showsIndexCharts']))
        $query .= ",showsIndexCharts=" . $_POST['showsIndexCharts'];
    if (isset($_POST['showsIndexProductBelowLimitReport']))
        $query .= ",showsIndexProductBelowLimitReport=" . $_POST['showsIndexProductBelowLimitReport'];
    if (isset($_POST['restaurantplaystationpalyBtn']))
        $query .= ",restaurantplaystationpalyBtn=" . $_POST['restaurantplaystationpalyBtn'];
    if (isset($_POST['restaurantDefaultPage']))
        $query .= ",restaurantDefaultPage=" . $_POST['restaurantDefaultPage'];
    if (isset($_POST['mandobMethod']))
        $query .= ",mandobMethod=" . $_POST['mandobMethod'];
    if (isset($_POST['addClientInBill']))
        $query .= ",addClientInBill=" . $_POST['addClientInBill'];
    if (isset($_POST['addsupplierInBill']))
        $query .= ",addsupplierInBill=" . $_POST['addsupplierInBill'];
    if (isset($_POST['hideBillPrices']))
        $query .= ",hideBillPrices=" . $_POST['hideBillPrices'];
    if (isset($_POST['showSerializeBtn']))
        $query .= ",showSerializeBtn=" . $_POST['showSerializeBtn'];
    if (isset($_POST['showClientAndSupplierOne']))
        $query .= ",showClientAndSupplierOne=" . $_POST['showClientAndSupplierOne'];
    if (isset($_POST['dontChooseStore']))
        $query .= ",dontChooseStore=" . $_POST['dontChooseStore'];
    if (isset($_POST['allowStoreMoveUpdateDel']))
        $query .= ",allowStoreMoveUpdateDel=" . $_POST['allowStoreMoveUpdateDel'];
    if (isset($_POST['showProfitInsideBill']))
        $query .= ",showProfitInsideBill=" . $_POST['showProfitInsideBill'];
    if (isset($_POST['storeSupervisorShow']))
        $query .= ",storeSupervisorShow=" . $_POST['storeSupervisorShow'];
    if (isset($_POST['showSaveBalanceAfterClose']))
        $query .= ",showSaveBalanceAfterClose=" . $_POST['showSaveBalanceAfterClose'];
    if (isset($_POST['canEditAddDiscountPercentage']))
        $query .= ",canEditAddDiscountPercentage=" . $_POST['canEditAddDiscountPercentage'];
    if (isset($_POST['noBillEditIfTheirIsPayments']))
        $query .= ",noBillEditIfTheirIsPayments=" . $_POST['noBillEditIfTheirIsPayments'];
    //////////
    if ($query != '') {
        $query = ltrim($query, ',');
        $query = 'UPDATE usergroup SET ' . $query . ' WHERE usergroupid = ' . $_POST['usergroupid'];
    }
    return $query;
}
