<?php

//the global file operation
include("../public/impOpreation.php");

// get the config file
include_once("../public/config.php");
include("../library/uploadImages.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');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.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');
//Availableparcode
require_once('../models/dao/AvailableparcodeDAO.class.php');
require_once('../models/dto/Availableparcode.class.php');
require_once('../models/mysql/AvailableparcodeMySqlDAO.class.php');
require_once('../models/mysql/ext/AvailableparcodeMySqlExtDAO.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');
//Ebillsetting
require_once('../models/dao/EbillsettingDAO.class.php');
require_once('../models/dto/Ebillsetting.class.php');
require_once('../models/mysql/EbillsettingMySqlDAO.class.php');
require_once('../models/mysql/ext/EbillsettingMySqlExtDAO.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 :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */
$userID = $_SESSION['userid'];

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

//here goes the instances and general variables
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();
//Store
$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();

$productExt = new ProductMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Usergroup
$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$userGroupEX = new UsergroupMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//Ebillsetting
$eBillSetting = new Ebillsetting();
$eBillSettingDAO = new EbillsettingMySqlDAO();
$eBillSettingEX = new EbillsettingMySqlExtDAO();


$Programsettingdata;
//check and use the condetion that suite this action
if (empty($do)) {
    $transfersell = R::load('transfersell', 1);
    $smarty->assign('transfersell', $transfersell);


    $programsettingsdata = $ProgramsettingDAO->load(1);
    $programsettingsdata->restaurantServiceOn = explode(',', $programsettingsdata->restaurantServiceOn);
    $programsettingsdata->obgyPharmacyGroups = explode(',', $programsettingsdata->obgyPharmacyGroups);
    $smarty->assign('programsettingsdata', $programsettingsdata);

    $laterNakdiClientName = R::getCell('select clientname from client where clientid=' . (int) $programsettingsdata->laterNakdiClientId);
    $smarty->assign('laterNakdiClientName', $laterNakdiClientName);
    //
    $eBillSetting = $eBillSettingDAO->load(1);
    $smarty->assign('eBillSetting', $eBillSetting);
    $smarty->assign('userID', $userID);

    $allStores = $storeDAO->queryAll();
    $smarty->assign('allStores', $allStores);

    $userGroups = $userGroupDAO->queryAll();
    $smarty->assign("userGroups", $userGroups);

    $allCat = R::getAll('select * from productcat where conditions = 0 and isOptic != 2 and productCatId not in (select productCatParent from productcat where conditions  = 0 and isOptic != 2)');
    $smarty->assign('allCat', $allCat);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("programsettingsview/add.html");
} elseif ($do == "update") {
    try {
        update();
        header("location:programsettingsController.php");
    } catch (Exception $e) {
        header("location:?do=error");
        echo $e;
    }
} elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}




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

//******************    Functions    ************************//
//update row
function update() {
    global $ProgramsettingEX;
    global $ProgramsettingDAO;
    global $Programsetting;
    global $productExt;
    global $Programsettingdata;
    global $clientExt;
    global $availableParcodeEX;
    global $eBillSettingDAO;



    $programsettingsid = $_POST['programsettingsid'];
    $companyname = $_POST['companyname'];
    $address = $_POST['address'];
    $specializtion = $_POST['specializtion'];
    $phone = $_POST['phone'];
    $faxnumber = $_POST['faxnumber'];
    $email = $_POST['email'];
    $website = $_POST['website'];
    $logo = $_POST['logo'];
    $productbycodeimage = $_POST['productbycodeimage'];
    $roundnumbers = $_POST['roundnumbers'];
    $saveprinting = $_POST['saveprinting'];
    $deptprinting = $_POST['deptprinting'];
    $userid = $_SESSION["userid"];
    $printingpapersize = $_POST['printingpapersize'];
    $previousPrice = $_POST['previousPrice'];
    $searchvalue = $_POST['searchvalue'];
    $clientsearchvalue = $_POST['clientsearchvalue'];
    $searchlimit = (int) $_POST['searchlimit'];
    $parcode = $_POST['parcode'];
    $priceing = $_POST['priceing'];
    $lastprice = $_POST['lastprice'];
    $updateproductprice = (int) $_POST['updateproductprice'];

    $allowfinsldelete = $_POST['allowfinsldelete'];
    $updateclientprice = $_POST['updateclientprice'];
    $partition = $_POST['partition'];


    $taxcard = $_POST['taxcard'];
    $commercialregistration = $_POST['commercialregistration'];
    $licenseNo = $_POST['licenseNo'];
    $costcenter = $_POST['costcenter'];
    $expensesproduct = $_POST['expensesproduct'];

    $clinic = $_POST['clinic'];
    $workshop = $_POST['workshop'];
    $transport = $_POST['transport'];
    $manufacturing = $_POST['manufacturing'];
    $tamweenBakery = (int) $_POST['tamweenBakery'];
    $masterCopy = $_POST['masterCopy'];

    $workerbetweenstores = $_POST['workerbetweenstores'];
    $workshoptimeout = $_POST['workshoptimeout'];
    $drivertimeout = $_POST['drivertimeout'];
    $currency = $_POST['currancy'];
    $allowdateedit = $_POST['allowdateedit'];

    $clientcode = $_POST['clientcode'];
    $clientserial = $_POST['clientserial'];
    $expiredate = $_POST['expiredate'];
    $production = $_POST['production'];
    $description = $_POST['description'];
    $service = $_POST['service'];
    $date = $_POST['date'];
    $limitamount = $_POST['limitamount'];
    $webApiId = (int) $_POST['webApiId'];
    $measuringunit = $_POST['measuringunit'];
    $print_amount = $_POST['print_amount'];
    $billid = $_POST['billid'];
    $precentages = $_POST['precentages'];
    $realprice = $_POST['realprice'];
    $delegate_seller = $_POST['delegate_seller'];
    $storeserial = $_POST['storeserial'];
    $clientcodname = $_POST['clientcodname'];
    $clientfieldrequired = $_POST['clientfieldrequired'];
    $colortype = $_POST['colortype'];
    $nakdyOnly = $_POST['nakdyOnly'];
    $nakdyKashf = $_POST['nakdyKashf'];
    $discount_pres_direct = $_POST['discount_pres_direct'];
    $general_discount = $_POST['general_discount'];
    $sells_return = $_POST['sells_return'];
    $scunitname = empty($_POST['scunitname']) ? 0 : $_POST['scunitname'];
    $vatValue = (float) $_POST['vatValue'];
    $syncstructure = $_POST['syncstructure'];
    $showPrevPrices = (int) $_POST['showPrevPrices'];
    $showPrevDiscount = (int) $_POST['showPrevDiscount'];
    $showPrevPricesRet = (int) $_POST['showPrevPricesRet'];
    $showPrevDiscountRet = (int) $_POST['showPrevDiscountRet'];
    $isOpticProg = $_POST['isOpticProg'];

    $reportsPlusHours = (int) $_POST['reportsPlusHours'];
    $projectshownew = (int) $_POST['projectshownew'];
    $showparcode = (int) $_POST['showparcode'];

    $showM5zon = $_POST['showM5zon'];
    $restaurantStoreId = (int) $_POST['restaurantStoreId'];
    $restuarantPrintTimeout = (int) $_POST['restuarantPrintTimeout'];
    $isCafe = (int) $_POST['isCafe'];
    $isRestaurent = (int) $_POST['isRestaurent'];
    $commentClient = $_POST['commentClient'];
    $noOfDecimalPlaces = (int) $_POST['noOfDecimalPlaces'];
    $inventoryvaluation = (int) $_POST['inventoryvaluation'];
    $showCurrency = (int) $_POST['showCurrency'];
    $qrerp = (int) $_POST['qrerp'];
    $valueadded = (int) $_POST['valueadded'];
    $valueaddedbuy = (int) $_POST['valueaddedbuy'];
    $simpleAddClientInBill = (int) $_POST['simpleAddClientInBill'];
    $searchBarcodeInBill = (int) $_POST['searchBarcodeInBill'];
    $sendBillToRestaurant = (int) $_POST['sendBillToRestaurant'];
    $defaultUnitPriceAtBill = (int) $_POST['defaultUnitPriceAtBill'];
    $useListPrice = (int) $_POST['useListPrice'];
    $rulers = (int) $_POST['rulers'];
    $showStoreToDetail = (int) $_POST['showStoreToDetail'];
    $showBuyPriceAtProductddl = (int) $_POST['showBuyPriceAtProductddl'];
    $qrcodesh = $_POST['qrcodesh'];
    $printfoot = $_POST['printfoot'];
    $sellorder = $_POST['sellorder'];
    $numberprint = $_POST['numberprint'];
    $vatvalueqr = $_POST['vatvalueqr'];
    $imgprinthide = $_POST['imgprinthide'];
    $parcodeprinttype = $_POST['parcodeprinttype'];
    $parcodeprintwidth = (int) $_POST['parcodeprintwidth'];
    $parcodeprinttextsize = (int) $_POST['parcodeprinttextsize'];
    $parcodeprintCurr = $_POST['parcodeprintCurr'];
    $sizecolorDigits = $_POST['sizecolorDigits'];
    $ratioshow = $_POST['ratioshow'];
    $quantitynew = (int) $_POST['quantitynew'];
    $showBillOperationSearch = (int) $_POST['showBillOperationSearch'];
    $obygyFolder = $_POST['obygyFolder'];
    $clientsell = $_POST['clientsell'];
    $preorderperiod = $_POST['preorderperiod'];
    $importproduct = $_POST['importproduct'];
    $realestateunits = $_POST['realestateunits'];
    $expensesupplier = $_POST['expensesupplier'];
    $typebill = $_POST['typebill'];
    $roundnumbersbilltotal = (int) $_POST['roundnumbersbilltotal'];
    $enablequantityfractions = (int) $_POST['enablequantityfractions'];
    $noOfDecimalPlacesBillTotal = (int) $_POST['noOfDecimalPlacesBillTotal'];
    $sellordername = $_POST['sellordername'];
    $checkretsellclient = (int) $_POST['checkretsellclient'];
    $noBillEditTillPay = (int) $_POST['noBillEditTillPay'];
    $showDataOfficialContract = (int) $_POST['showDataOfficialContract'];

    $obgyPharmacyGroups = filter_input(INPUT_POST, 'obgyPharmacyGroups', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $obgyPharmacyGroups_str = '';
    foreach ($obgyPharmacyGroups as $value) {
        $obgyPharmacyGroups_str .= $value . ",";
    }
    $obgyPharmacyGroups_str = rtrim($obgyPharmacyGroups_str, ',');




    $timezone = $_POST['timezone'];
    if (!isset($timezone) || empty($timezone)) {
        $timezone = "Africa/Cairo";
    }
    $sumSameProductForStore = (int) filter_input(INPUT_POST, 'sumSameProductForStore');
    $editAllPrice = filter_input(INPUT_POST, 'editAllPrice');
    $productDays = filter_input(INPUT_POST, 'productDays');
    $parcodeDigits = filter_input(INPUT_POST, 'parcodeDigits');
    $specializedParcodeDigits = filter_input(INPUT_POST, 'specializedParcodeDigits');
    $usedParcode = filter_input(INPUT_POST, 'usedParcode');
    $thereIsRestTax = (int) filter_input(INPUT_POST, 'thereIsRestTax');
    $taxNameFlag = (int) filter_input(INPUT_POST, 'taxNameFlag');
    $restTaxVal = (float) filter_input(INPUT_POST, 'restTaxVal');
    $restPrintLang = (int) filter_input(INPUT_POST, 'restPrintLang');

    $clientDefaultDebtLimit = (float) filter_input(INPUT_POST, 'clientDefaultDebtLimit');
    $clientDefaultDebtLimitControl = (int) filter_input(INPUT_POST, 'clientDefaultDebtLimitControl');
    $affectAllClientDebtLimit_h = (int) filter_input(INPUT_POST, 'affectAllClientDebtLimit_h');
    $Inventoryevaluation = filter_input(INPUT_POST, 'Inventoryevaluation'); //تقييم المخزون
    $dailyEntryCostprice = filter_input(INPUT_POST, 'dailyEntryCostprice');
    $Profitevaluation = filter_input(INPUT_POST, 'Profitevaluation'); //تقييم الارباح
    $delivery = (int) filter_input(INPUT_POST, 'delivery'); //شحن وتوصيل
    $premiums = (int) filter_input(INPUT_POST, 'premiums'); //الاقساط
    $operationnumEdit = (int) filter_input(INPUT_POST, 'operationnumEdit');
    $unReviewBills = (int) filter_input(INPUT_POST, 'unReviewBills');
    $unReviewBillsPass = filter_input(INPUT_POST, 'unReviewBillsPass');
    $billReviewNote = filter_input(INPUT_POST, 'billReviewNote');
    $makeDailyEntry = filter_input(INPUT_POST, 'makeDailyEntry');
    $Fayedh_3 = (int) filter_input(INPUT_POST, 'Fayedh_3');
    $Fayedh_6 = (int) filter_input(INPUT_POST, 'Fayedh_6');
    $Fayedh_12 = (int) filter_input(INPUT_POST, 'Fayedh_12');
    $Fayedh_18 = (int) filter_input(INPUT_POST, 'Fayedh_18');
    $Fayedh_24 = (int) filter_input(INPUT_POST, 'Fayedh_24');
    $Fayedh_30 = (int) filter_input(INPUT_POST, 'Fayedh_30');
    $Fayedh_36 = (int) filter_input(INPUT_POST, 'Fayedh_36');
    $Fayedh_42 = (int) filter_input(INPUT_POST, 'Fayedh_42');
    $Fayedh_48 = (int) filter_input(INPUT_POST, 'Fayedh_48');
    $printSand = filter_input(INPUT_POST, 'printSand');
    $ClientShowTawla = filter_input(INPUT_POST, 'ClientShowTawla');
    $mandobCollectionRatio = (int) filter_input(INPUT_POST, 'mandobCollectionRatio');
    $takeAwayClient = (int) filter_input(INPUT_POST, 'takeAwayClient');
    $delivery = (int) filter_input(INPUT_POST, 'delivery');
    $takeAway = (int) filter_input(INPUT_POST, 'takeAway');
    $billRest = (int) filter_input(INPUT_POST, 'billRest');
    $suppIsClientToo = (int) filter_input(INPUT_POST, 'suppIsClientToo');
    $unitPriceAtsalesreport = (int) filter_input(INPUT_POST, 'unitPriceAtsalesreport');
    $storeRecieveType = (int) filter_input(INPUT_POST, 'storeRecieveType');
    $clientPhoneReq = (int) filter_input(INPUT_POST, 'clientPhoneReq');
    $addServiceToBill = (int) filter_input(INPUT_POST, 'addServiceToBill');
    $isCarBill = (int) $_POST['isCarBill'];
    $hall = (int) filter_input(INPUT_POST, 'hall');
    $restaurantServiceOn = ",$delivery,$takeAway,$hall,";

    $earlyrepayment = (int) $_POST['earlyrepayment'];
    $visaPay = (int) $_POST['visaPay'];
    $changeBuyPriceChangeSellInBuyBillCtrl = (int) $_POST['changeBuyPriceChangeSellInBuyBillCtrl'];
    $changeBuyPriceChangeSellInProductCtrl = (int) $_POST['changeBuyPriceChangeSellInProductCtrl'];
    $updateProUnitPricesOnPriceUpdate = (int) $_POST['updateProUnitPricesOnPriceUpdate'];
    $showBillCollectionSearch = (int) $_POST['showBillCollectionSearch'];
    $incomeclient = (int) $_POST['incomeclient'];
    $showserial = (int) $_POST['showserial'];
    $editservice = (int) $_POST['editservice'];
    $ebill = (int) $_POST['ebill'];

    //ebillsetting
    $eunitInTax = filter_input(INPUT_POST, 'eunitInTax');
    $eTaxNum = filter_input(INPUT_POST, 'eTaxNum');
    $eTaxNumBranch = filter_input(INPUT_POST, 'eTaxNumBranch');
    $eGovernorate = filter_input(INPUT_POST, 'eGovernorate');
    $eCity = filter_input(INPUT_POST, 'eCity');
    $eStreet = filter_input(INPUT_POST, 'eStreet');
    $eBuildingNum = filter_input(INPUT_POST, 'eBuildingNum');
    $eTaxType = filter_input(INPUT_POST, 'eTaxType');
    $eTaxTypeNum = filter_input(INPUT_POST, 'eTaxTypeNum');
    $eCompanyNameInTaxCard = filter_input(INPUT_POST, 'eCompanyNameInTaxCard');
    //
    $realestatedev = filter_input(INPUT_POST, 'realestatedev');
    $showprice4 = filter_input(INPUT_POST, 'showprice4');
    $showprice5 = filter_input(INPUT_POST, 'showprice5');
    $showprice6 = filter_input(INPUT_POST, 'showprice6');
    $showprice7 = filter_input(INPUT_POST, 'showprice7');
    $showprice8 = filter_input(INPUT_POST, 'showprice8');
    $showprice9 = filter_input(INPUT_POST, 'showprice9');
    $showprice10 = filter_input(INPUT_POST, 'showprice10');
    $showprice11 = filter_input(INPUT_POST, 'showprice11');
    $showprice12 = filter_input(INPUT_POST, 'showprice12');
    $showprice13 = filter_input(INPUT_POST, 'showprice13');
    $showpriceall = filter_input(INPUT_POST, 'showpriceall');
    $showpricehalf = filter_input(INPUT_POST, 'showpricehalf');
    $showpriceunit = filter_input(INPUT_POST, 'showpriceunit');

    $addclienttoproduct = filter_input(INPUT_POST, 'addclienttoproduct');

    $showbillstatus = filter_input(INPUT_POST, 'showbillstatus');
    $showbilldeliverydate = filter_input(INPUT_POST, 'showbilldeliverydate');


    $specialexpenses = filter_input(INPUT_POST, 'specialexpenses');

    $handle = new upload($_FILES['headerPrintSand']);
    $headerPrintSand = updateImages($handle, "headerPrintSand", '../views/default/images/upload', 250, 250);

    $handle = new upload($_FILES['headerPrint']);
    $headerPrint = updateImagesWithoutresiz($handle, "headerPrint", '../views/default/images/upload');

    $handle = new upload($_FILES['headerPrint12Right']);
    $headerPrint12Right = updateImagesWithoutresiz($handle, "headerPrint12Right", '../views/default/images/upload');

    $handle = new upload($_FILES['headerPrint12Left']);
    $headerPrint12Left = updateImagesWithoutresiz($handle, "headerPrint12Left", '../views/default/images/upload');

    $handle = new upload($_FILES['logo']);
    $image = updateImages($handle, "oldlogo", '../views/default/images/upload', 250, 250);

    $handle = new upload($_FILES['productbycodeimage']);
    $productbycodeimage = updateImagesWithoutresiz($handle, "oldproductbycodeimage", '../views/default/images/upload/productbycodeimage');
    $maintenance = (int) filter_input(INPUT_POST, 'maintenance');
    $valueaddeddiscount = (int) $_POST['valueaddeddiscount'];
    $ebillclient = (int) $_POST['ebillclient'];
    $clientdetail = (int) $_POST['clientdetail'];
    $changeOrderproduct = (int) filter_input(INPUT_POST, 'changeOrderproduct');
    $closingcustomeraccount = (int) filter_input(INPUT_POST, 'closingcustomeraccount');
    $shownameE = filter_input(INPUT_POST, 'shownameE');
    $showprocode = filter_input(INPUT_POST, 'showprocode');
    $showpartnumber = filter_input(INPUT_POST, 'showpartnumber');
    $showtype = filter_input(INPUT_POST, 'showtype');
    $showcompany = filter_input(INPUT_POST, 'showcompany');
    $showweight = filter_input(INPUT_POST, 'showweight');
    $showorigin = filter_input(INPUT_POST, 'showorigin');
    $showhscode = filter_input(INPUT_POST, 'showhscode');
    $showexpire = filter_input(INPUT_POST, 'showexpire');
    $showgrantduration = filter_input(INPUT_POST, 'showgrantduration');
    $showonline = filter_input(INPUT_POST, 'showonline');
    $showminappear = filter_input(INPUT_POST, 'showminappear');
    $showonlinecat = filter_input(INPUT_POST, 'showonlinecat');
    $showsellpercentage = filter_input(INPUT_POST, 'showsellpercentage');
    $showbuydiscount = filter_input(INPUT_POST, 'showbuydiscount');
    $preparingStore = filter_input(INPUT_POST, 'preparingStore');
    if (!$preparingStore)
        $preparingStore = 1;
    $showsearchfilter = filter_input(INPUT_POST, 'showsearchfilter');
    $medExCat = filter_input(INPUT_POST, 'medExCat');
    $laterNakdiClientId = (int) filter_input(INPUT_POST, 'laterNakdiClientId');
    $halfPriceStart = (int) filter_input(INPUT_POST, 'halfPriceStart');
    $allPriceStart = (int) filter_input(INPUT_POST, 'allPriceStart');


    //print_r($image);
    $alldata = $Programsettingdata = $ProgramsettingDAO->load(1);
    $oldParcodeDigits = $alldata->parcodeDigits;
    $oldSizecolorDigits = $alldata->sizecolorDigits;
    $oldcolortype = $Programsetting->colortype;
    $Programsetting = $alldata;
    $Programsetting->changeOrderproduct = $changeOrderproduct;
    $Programsetting->commentClient = $commentClient;
    $Programsetting->address = $address;
    $Programsetting->companyname = $companyname;
    $Programsetting->deptprinting = $deptprinting;
    $Programsetting->email = $email;
    $Programsetting->faxnumber = $faxnumber;
    $Programsetting->logo = $image;
    $Programsetting->headerPrint = $headerPrint;
    $Programsetting->headerPrintSand = $headerPrintSand;
    $Programsetting->headerPrint12Right = $headerPrint12Right;
    $Programsetting->headerPrint12Left = $headerPrint12Left;
    $Programsetting->productbycodeimage = $productbycodeimage;
    $Programsetting->phone = $phone;
    $Programsetting->printingpapersize = $printingpapersize;
    $Programsetting->roundnumbers = $roundnumbers;
    $Programsetting->saveprinting = $saveprinting;
    $Programsetting->specializtion = $specializtion;
    $Programsetting->website = $website;
    $Programsetting->userid = $_SESSION["userid"];

    $Programsetting->showPreviousPrice = 0; //$previousPrice;
    $Programsetting->searchvalue = $searchvalue;
    $Programsetting->clientsearchvalue = $clientsearchvalue;
    $Programsetting->searchlimit = $searchlimit;
    $Programsetting->parcode = $parcode; //$parcode;
    $Programsetting->priceing = 0; //$priceing;
    $Programsetting->lastprice = $lastprice;
    $Programsetting->updateproductprice = $updateproductprice;

    $Programsetting->allowfinsldelete = 0; //$allowfinsldelete;
    $Programsetting->updateclientprice = 0; //$updateclientprice;
    $Programsetting->partition = $partition;
    $Programsetting->taxcard = $taxcard;
    $Programsetting->commercialregistration = $commercialregistration;
    $Programsetting->licenseNo = $licenseNo;
    $Programsetting->costcenter = $costcenter;
    $Programsetting->expensesproduct = $expensesproduct;

    //fatma
    $Programsetting->clinic = $clinic;
    $Programsetting->workshop = $workshop;
    $Programsetting->transport = $transport;
    $Programsetting->manufacturing = $manufacturing;
    $Programsetting->tamweenBakery = $tamweenBakery;
    $Programsetting->masterCopy = $masterCopy;

    $Programsetting->workerbetweenstores = $workerbetweenstores;
    $Programsetting->workshoptimeout = $workshoptimeout;
    $Programsetting->drivertimeout = $drivertimeout;
    $Programsetting->currancy = $currency;
    $Programsetting->allowdateedit = $allowdateedit;


    $Programsetting->clientcode = $clientcode;
    $Programsetting->clientserial = $clientserial;
    $Programsetting->timezone = $timezone;
    $Programsetting->expiredate = $expiredate;
    $Programsetting->production = $production;
    $Programsetting->description = $description;
    $Programsetting->service = $service;
    $Programsetting->date = $date;
    $Programsetting->limitamount = $limitamount;
    $Programsetting->webApiId = $webApiId;
    $Programsetting->measuringunit = $measuringunit;
    $Programsetting->print_amount = $print_amount;
    $Programsetting->billid = $billid;
    $Programsetting->precentages = $precentages;
    $Programsetting->realprice = $realprice;
    $Programsetting->delegate_seller = $delegate_seller;
    $Programsetting->storeserial = $storeserial;

    $Programsetting->clientcodname = $clientcodname;
    $Programsetting->clientfieldrequired = $clientfieldrequired;
    $Programsetting->colortype = $colortype;
    if ($oldcolortype != $colortype) {
        unlink("../temp__cashedheader/cashedheader_" . $_SESSION['dbname'] . "_" . $_SESSION['userid'] . ".html");
    }
    $Programsetting->nakdyOnly = $nakdyOnly;
    $Programsetting->nakdyKashf = $nakdyKashf;
    $Programsetting->discount_pres_direct = $discount_pres_direct;
    $Programsetting->general_discount = $general_discount;
    $Programsetting->sells_return = $sells_return;
    $Programsetting->scunitname = $scunitname;
    $Programsetting->vatValue = $vatValue;
    $Programsetting->syncstructure = $syncstructure;
    $Programsetting->showPrevPrices = $showPrevPrices;
    $Programsetting->showPrevDiscount = $showPrevDiscount;
    $Programsetting->showPrevPricesRet = $showPrevPricesRet;
    $Programsetting->showPrevDiscountRet = $showPrevDiscountRet;
    $Programsetting->isOpticProg = $isOpticProg;
    $Programsetting->reportsPlusHours = $reportsPlusHours;
    $Programsetting->showM5zon = $showM5zon;
    $Programsetting->restaurantStoreId = $restaurantStoreId;
    $Programsetting->restuarantPrintTimeout = $restuarantPrintTimeout;
    $Programsetting->sumSameProductForStore = $sumSameProductForStore;
    $Programsetting->editAllPrice = $editAllPrice;
    $Programsetting->isCafe = $isCafe;
    $Programsetting->isRestaurent = $isRestaurent;
    $Programsetting->productDays = $productDays;
    $Programsetting->parcodeDigits = $parcodeDigits;
    $Programsetting->specializedParcodeDigits = $specializedParcodeDigits;
    $Programsetting->usedParcode = $usedParcode;
    $Programsetting->thereIsRestTax = $thereIsRestTax;
    $Programsetting->taxNameFlag = $taxNameFlag;
    $Programsetting->restTaxVal = $restTaxVal;
    $Programsetting->restPrintLang = $restPrintLang;
    $Programsetting->clientDefaultDebtLimit = $clientDefaultDebtLimit;
    $Programsetting->Inventoryevaluation = $Inventoryevaluation; //تقييم المخزون
    $Programsetting->dailyEntryCostprice = $dailyEntryCostprice;
    $Programsetting->Profitevaluation = $Profitevaluation; //تقييم الارباح
    $Programsetting->delivery = $delivery; //تقييم الارباح
    $Programsetting->premiums = $premiums; //الاقساط
    $Programsetting->operationnumEdit = $operationnumEdit; //تقييم الارباح
    $Programsetting->noOfDecimalPlaces = $noOfDecimalPlaces;
    $Programsetting->three_months = $Fayedh_3;
    $Programsetting->six_months = $Fayedh_6;
    $Programsetting->twelve_months = $Fayedh_12;
    $Programsetting->eighteen_months = $Fayedh_18;
    $Programsetting->twentyfour_months = $Fayedh_24;
    $Programsetting->thirty_months = $Fayedh_30;
    $Programsetting->sixthirty_months = $Fayedh_36;
    $Programsetting->fortytwo_months = $Fayedh_42;
    $Programsetting->fortyeight_months = $Fayedh_48;
    $Programsetting->mandobCollectionRatio = $mandobCollectionRatio;
    $Programsetting->earlyrepayment = $earlyrepayment;
    $Programsetting->visaPay = $visaPay;
    $Programsetting->printSand = $printSand;
    $Programsetting->clientShowTawla = $ClientShowTawla;
    $Programsetting->billRest = $billRest;
    $Programsetting->suppIsClientToo = $suppIsClientToo;
    $Programsetting->unitPriceAtsalesreport = $unitPriceAtsalesreport;
    $Programsetting->storeRecieveType = $storeRecieveType;
    $Programsetting->clientPhoneReq = $clientPhoneReq;
    $Programsetting->addServiceToBill = $addServiceToBill;
    $Programsetting->isCarBill = $isCarBill;
    $Programsetting->projectshownew = $projectshownew;
    $Programsetting->showparcode = $showparcode;
    $Programsetting->changeBuyPriceChangeSellInBuyBillCtrl = $changeBuyPriceChangeSellInBuyBillCtrl;
    $Programsetting->changeBuyPriceChangeSellInProductCtrl = $changeBuyPriceChangeSellInProductCtrl;
    $Programsetting->updateProUnitPricesOnPriceUpdate = $updateProUnitPricesOnPriceUpdate;
    $Programsetting->showBillCollectionSearch = $showBillCollectionSearch;
    $Programsetting->incomeclient = $incomeclient;
    $Programsetting->showserial = $showserial;
    $Programsetting->editservice = $editservice;
    $Programsetting->printfoot = $printfoot;
    $Programsetting->sellorder = $sellorder;
    $Programsetting->numberprint = $numberprint;
    $Programsetting->eunitInTax = $eunitInTax;
    $Programsetting->showStoreToDetail = $showStoreToDetail;
    $Programsetting->showBuyPriceAtProductddl = $showBuyPriceAtProductddl;
    $Programsetting->clientsell = $clientsell;
    $Programsetting->preorderperiod = $preorderperiod;
    $Programsetting->ebillclient = $ebillclient;
    $Programsetting->importproduct = $importproduct;
    $Programsetting->realestateunits = $realestateunits;
    $Programsetting->typebill = $typebill;
    $Programsetting->roundnumbersbilltotal = $roundnumbersbilltotal;
    $Programsetting->enablequantityfractions = $enablequantityfractions;
    $Programsetting->noOfDecimalPlacesBillTotal = $noOfDecimalPlacesBillTotal;
    $Programsetting->sellordername = $sellordername;



    if ($affectAllClientDebtLimit_h == 1) {
        $clientExt->updatedeptlimit($Programsetting->clientDefaultDebtLimit);
    }
    $Programsetting->clientDefaultDebtLimitControl = $clientDefaultDebtLimitControl;
    $Programsetting->unReviewBills = $unReviewBills;
    if ($Programsetting->unReviewBills == 0) {
        $Programsetting->unReviewBillsPass = $unReviewBillsPass;
    } else if ($Programsetting->unReviewBills == 1) {
        $Programsetting->unReviewBillsPass = "";
    }
    $Programsetting->billReviewNote = $billReviewNote;
    $Programsetting->makeDailyEntry = $makeDailyEntry;
    $Programsetting->takeAwayClient = $takeAwayClient;
    $Programsetting->restaurantServiceOn = $restaurantServiceOn;
    $Programsetting->inventoryvaluation = $inventoryvaluation;
    $Programsetting->showCurrency = $showCurrency;
    $Programsetting->qrerp = $qrerp;
    $Programsetting->valueadded = $valueadded;
    $Programsetting->valueaddedbuy = $valueaddedbuy;
    $Programsetting->simpleAddClientInBill = $simpleAddClientInBill;
    $Programsetting->searchBarcodeInBill = $searchBarcodeInBill;
    $Programsetting->sendBillToRestaurant = $sendBillToRestaurant;
    $Programsetting->defaultUnitPriceAtBill = $defaultUnitPriceAtBill;
    $Programsetting->useListPrice = $useListPrice;
    $Programsetting->rulers = $rulers;
    $Programsetting->quantitynew = $quantitynew;
    $Programsetting->showBillOperationSearch = $showBillOperationSearch;
    $Programsetting->obygyFolder = $obygyFolder;
    $Programsetting->obgyPharmacyGroups = $obgyPharmacyGroups_str;
    $Programsetting->qrcodesh = $qrcodesh;
    $Programsetting->maintenance = $maintenance;
    $Programsetting->vatvalueqr = $vatvalueqr;
    $Programsetting->imgprinthide = $imgprinthide;
    $Programsetting->parcodeprinttype = $parcodeprinttype;
    $Programsetting->parcodeprintwidth = $parcodeprintwidth;
    $Programsetting->parcodeprinttextsize = $parcodeprinttextsize;
    $Programsetting->parcodeprintCurr = $parcodeprintCurr;
    $Programsetting->sizecolorDigits = $sizecolorDigits;
    $Programsetting->ebill = $ebill;
    $Programsetting->valueaddeddiscount = $valueaddeddiscount;
    $Programsetting->clientdetail = $clientdetail;
    $Programsetting->specialexpenses = $specialexpenses;
    $Programsetting->ratioshow = $ratioshow;
    $Programsetting->expensesupplier = $expensesupplier;
    $Programsetting->realestatedev = $realestatedev;
    $Programsetting->showprice4 = $showprice4;
    $Programsetting->showprice5 = $showprice5;
    $Programsetting->showprice6 = $showprice6;
    $Programsetting->showprice7 = $showprice7;
    $Programsetting->showprice8 = $showprice8;
    $Programsetting->showprice9 = $showprice9;
    $Programsetting->showprice10 = $showprice10;
    $Programsetting->showprice11 = $showprice11;
    $Programsetting->showprice12 = $showprice12;
    $Programsetting->showprice13 = $showprice13;
    $Programsetting->showpriceall = $showpriceall;
    $Programsetting->showpricehalf = $showpricehalf;
    $Programsetting->showpriceunit = $showpriceunit;
    $Programsetting->showbillstatus = $showbillstatus;
    $Programsetting->showbilldeliverydate = $showbilldeliverydate;
    $Programsetting->addclienttoproduct = $addclienttoproduct;
    $Programsetting->shownameE = $shownameE;
    $Programsetting->showprocode = $showprocode;
    $Programsetting->showpartnumber = $showpartnumber;
    $Programsetting->showtype = $showtype;
    $Programsetting->showcompany = $showcompany;
    $Programsetting->showweight = $showweight;
    $Programsetting->showorigin = $showorigin;
    $Programsetting->showhscode = $showhscode;
    $Programsetting->showexpire = $showexpire;
    $Programsetting->showgrantduration = $showgrantduration;
    $Programsetting->showonline = $showonline;
    $Programsetting->showminappear = $showminappear;
    $Programsetting->showonlinecat = $showonlinecat;
    $Programsetting->showsellpercentage = $showsellpercentage;
    $Programsetting->showbuydiscount = $showbuydiscount;
    $Programsetting->preparingStore = $preparingStore;
    $Programsetting->showsearchfilter = $showsearchfilter;
    $Programsetting->medExCat = $medExCat;
    $Programsetting->laterNakdiClientId = $laterNakdiClientId;
    $Programsetting->halfPriceStart = $halfPriceStart;
    $Programsetting->allPriceStart = $allPriceStart;
    $Programsetting->checkretsellclient = $checkretsellclient;
    $Programsetting->noBillEditTillPay = $noBillEditTillPay;
    $Programsetting->showDataOfficialContract = $showDataOfficialContract;


    $oldEBillSetting = $eBillSettingDAO->load(1);
    $eBillSetting->eunitInTax = $eunitInTax;
    $eBillSetting->eTaxNum = $eTaxNum;
    $eBillSetting->eTaxNumBranch = $eTaxNumBranch;
    $eBillSetting->eGovernorate = $eGovernorate;
    $eBillSetting->eCity = $eCity;
    $eBillSetting->eStreet = $eStreet;
    $eBillSetting->eBuildingNum = $eBuildingNum;
    $eBillSetting->eTaxType = $eTaxType;
    $eBillSetting->eTaxTypeNum = $eTaxTypeNum;
    $eBillSetting->eCompanyNameInTaxCard = $eCompanyNameInTaxCard;
    if (count($oldEBillSetting) > 0) {
        $eBillSetting->id = 1;
        $eBillSettingDAO->update($eBillSetting);
    } else {
        $eBillSettingDAO->insert($eBillSetting);
    }

    $Programsetting->roundnumbersbilltotal = $roundnumbersbilltotal;
    $Programsetting->enablequantityfractions = $enablequantityfractions;
    $Programsetting->noOfDecimalPlacesBillTotal = $noOfDecimalPlacesBillTotal;
    $Programsetting->closingcustomeraccount = $closingcustomeraccount;

    //    print_r('<pre>');
    //    print_r($Programsetting);
    //    print_r('</pre>');
    // print_r($Programsetting);
    if (count($alldata) > 0) {

        $Programsetting->programsettingsid = 1;
        $ProgramsettingDAO->update($Programsetting);
        if ($syncstructure != $alldata->syncstructure) {
            //draw header again to feel the syncstructure show hide
            $fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
            fclose($fh);
        }

        if ($oldParcodeDigits != $parcodeDigits) { // if no of parcodes changed redo parcodes like in productparcodefixusingid
            //
            $dbname = ConnectionProperty::getDatabase();
            if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
                $dbname = $_SESSION['dbname'];
            }
            //
            if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
                $Programsettingdata->parcodeDigits = 5;
            }

            //check if it has rows
            $availableParcodeEX->truncate();
            ##write all parcodes possibilities
            $availableParcodeEX->callGenerateParcodesSP($Programsettingdata->parcodeDigits);
            ##remove used parcodes from possibilities ##edit line is also like this
            $availableParcodeEX->deleteUsedParcodesInproductTable();
        }
        if ($oldSizecolorDigits != $sizecolorDigits && $sizecolorDigits > 0) { // if no of sizecolorDigits changed redo parcode of sizecolorstoredetail
            //update sizecolorDigits
            $sql = "update sizecolorstoredetail set parcode = CONCAT(lpad(productid, $parcodeDigits, 0),lpad(sizeid, $sizecolorDigits, 0),lpad(colorid, $sizecolorDigits, 0));";
            $ProgramsettingEX->runSqlQuery($sql);
        }
    } else {
        //draw header again to feel the syncstructure show hide
        $fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
        fclose($fh);
        $ProgramsettingDAO->insert($Programsetting);
    }

    if ($Programsetting->qrerp == 0) {
        if ($sock = @fsockopen('www.google.com', 80)) {
            $path = '../views/default/images/upload/'
                    . $Programsettingdata->logo;
            $type = pathinfo($path, PATHINFO_EXTENSION);
            $data = file_get_contents($path);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            $qrerpuserpass = R::findOne('qrerpuserpass');
            $send_data = array(
                'companyname' => $companyname,
                'specializtion' => $specializtion,
                'address' => $address,
                'phone' => $phone,
                'faxnumber' => $faxnumber,
                'website' => $website,
                'email' => $email,
                'taxcard' => $taxcard,
                'commercialregistration' => $commercialregistration,
                'logo' => $base64,
                'auserid' => $qrerpuserpass->auser_id,
            );
            CURL_IT($send_data, 'http://shop.gt4host.com/qrerp/full/api/updateausers');
        }
    }

    ##
    affectTableStructureWithDecimalPlaces($noOfDecimalPlacesBillTotal, $noOfDecimalPlaces);
}

function affectTableStructureWithDecimalPlaces($noOfDecimalPlacesBillTotal, $noOfDecimalPlaces) {
    ##$noOfDecimalPlaces
    $columnsToAlter = array('sellbill' => ['sellbilltotalbill', 'sellbillaftertotalbill', 'sellbilltotalpayed', 'sellbillfinalbill', 'tax', 'totalafterdelivery', 'cashPayed', 'visaPayed'],
        'sellbilldetail' => ['sellbilldetailquantity', 'sellbilldetailprice', 'sellbilldetailtotalprice', 'discountvalue']);

    $totalNumDigits = 8 + $noOfDecimalPlaces;
    $newType = " DECIMAL($totalNumDigits,$noOfDecimalPlaces) NOT NULL";
    foreach ($columnsToAlter as $table => $columnsArr) {
        $columnsStr = implode(', ', array_map(function($column) use ($newType) {
                    return "MODIFY COLUMN $column $newType";
                }, $columnsArr));
        $sql = "ALTER TABLE $table $columnsStr;";
        R::exec($sql);
    }
}

function CURL_IT($data_arr, $url) {
    // set post fields
    $post = [
        'data_arr' => json_encode($data_arr), //encode it as it is array
    ];
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //print_r($response);
}

function addPreDigitsToNum($num) {
    global $Programsettingdata;
    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }
    $length = $Programsettingdata->parcodeDigits;

    $preDigits = '';
    if (strlen($num) != $length) {
        $noDigitsLeft = $length - strlen($num);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    return $preDigits . $num;
}
