<?php

//the global file operation
session_start();
ob_start();

//global varable
global $showoutside;

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

include_once("dailyentryfun.php");

//here the db files that include in the file
include("../public/include_dao.php");
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.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');
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');
//Unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.class.php');
//Productcatunit
require_once('../models/dao/ProductcatunitDAO.class.php');
require_once('../models/dto/Productcatunit.class.php');
require_once('../models/mysql/ProductcatunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatunitMySqlExtDAO.class.php');

//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');


//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');

//Menuurl
require_once('../models/dao/MenuurlDAO.class.php');
require_once('../models/dto/Menuurl.class.php');
require_once('../models/mysql/MenuurlMySqlDAO.class.php');
require_once('../models/mysql/ext/MenuurlMySqlExtDAO.class.php');

//
require_once('../models/dao/SizecolorDAO.class.php');
require_once('../models/dto/Sizecolor.class.php');
require_once('../models/mysql/SizecolorMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorMySqlExtDAO.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');

include("../library/uploadImages.php");


//get the do the action
$do = $_GET['do'];

//get the SESSION
$userID = $_SESSION["userid"];

$today = date("y-m-d");

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

  Controller Name :- expensestypeCTRL

  OPERTATION in Controller

  1-display add form
  2- add in Expensetype tble
  3-display sucess or error
  4-display show and delete
  5-display edit
  ======================== */

//here goes the instances and general variables
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
$myProductcatEx = new ProductcatMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport();
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Productunit
$productUnit = new Productunit();
$productUnitDAO = new ProductunitMySqlDAO();
$productUnitExt = new ProductunitMySqlExtDAO();

//Productserial
$Productserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();
//Productcatunit
$catUnit = new Productcatunit();
$catUnitDAO = new ProductcatunitMySqlDAO();
$catUnitExt = new ProductcatunitMySqlExtDAO();

//Sellbilldetail
$Sellbilldetail = new Sellbilldetail();
$SellbilldetailDAO = new SellbilldetailMySqlDAO();
$SellbilldetailEX = new SellbilldetailMySqlExtDAO();


//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//here goes the instances and general variables
$Menuurl = new Menuurl();
$MenuurlDAO = new MenuurlMySqlDAO();
$MenuurlEX = new MenuurlMySqlExtDAO();
//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();

$existArr = array();

//User
$userDAO = new UserMySqlDAO();
//client
$myClientEx = $clientEX = new ClientMySqlExtDAO();
//check and use the condetion that suite this action

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

$lastLevelCatIDS = array();
$catsIDS = "";

if (empty($do)) {
} elseif ($do == "isParent") {
    $isParent = checkForChildren();
    if (!empty($isParent) && count($isParent) > 0) {
        print "isParent";
    } else {
        print "isNotParent";
    }
} elseif ($do == "hasProducts") {
    $hasProducts = checkForProducts();
    if (!empty($hasProducts) && count($hasProducts) > 0)
        echo "yes";
    else
        echo "no";
} elseif ($do == "setSession") {
    $name = $_POST['name'];
    $value = $_POST['value'];
    if (isset($name) && !empty($name)) {
        $_SESSION[$name] = $value;
        echo $value;
    }
} elseif ($do == "edit") {
    $productsData = edit();
    $smarty->assign("productsData", $productsData);
    //		print("<pre>");
    //		print_r($productsData);
    //		print("</pre>");
    if (count($productsData) > 0) {
        $productUnitsData = getProductUnits($productsData->productId);

        $smarty->assign("productUnitsData", $productUnitsData);
        $smarty->assign("countProductUnits", count($productUnitsData));
    }

    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

    //get units
    $unitsData = getUnits();
    $smarty->assign("unitsData", $unitsData);

    $lastLevelCatIDS = array();
    array_push($lastLevelCatIDS, 0);
    getAllSubCatKeyVal(0, 2); //mode = 2 get last level cats
    $smarty->assign("alldata", $lastLevelCatIDS);
    //    $alldata = getProductCats();
    //    $smarty->assign("alldata", $alldata);

    $smarty->display("productview/editAjax.html");
    $smarty->assign("productScripts", 1);
} elseif ($do == "update") { //edit update
    //try
    {
        update();
        //header("location:productController.php");
        //echo "done";
    }
    //catch(Exception $e)
    {
        //echo $e;
    }
} elseif ($do == "checkName") {
    checkName();
} elseif ($do == "getproductbarcode") {
    $productdata = getproductbarcode();
    echo $productdata->parcode;
} elseif ($do == "changesortby") {
    $sortby = $_POST["sortbys"];
    $myid = $_POST["myid"];
    $productExt->updatesortby($myid, $sortby);
}
/* elseif($do == "getproductbarcode")
  {
  $productdata=getproductbarcode();
  echo $productdata->parcode;
  }
 */ elseif ($do == "getproductname") {
    $productdata = getproductbarcode();
    echo $productdata->productName;
} elseif ($do == "getproductprice") {
    $productdata = getproductbarcode();
    echo $productdata->productSellUnitPrice;
} elseif ($do == "search_code") {
    $etacodetype = trim(filter_input(INPUT_POST, 'etacodetype'));
    $etaCodeLookupValue = filter_input(INPUT_POST, 'etaCodeLookupValue');
    $etaParentCodeLookupValue = filter_input(INPUT_POST, 'etaParentCodeLookupValue');
    $etaCodeID = filter_input(INPUT_POST, 'etaCodeID');
    $etaCodeName = filter_input(INPUT_POST, 'etaCodeName');
    $etaCodeDescription = filter_input(INPUT_POST, 'etaCodeDescription');
    $etaTaxpayerRIN = filter_input(INPUT_POST, 'etaTaxpayerRIN');
    $etaParentCodeID = filter_input(INPUT_POST, 'etaParentCodeID');
    $response = CURL_eBill(array(), "https://try.al-ebda3.com/api/v1/product/codes?code_type=$etacodetype&CodeLookupValue=$etaCodeLookupValue&ParentCodeLookupValue=$etaParentCodeLookupValue&CodeID=$etaCodeID&CodeName=$etaCodeName&CodeDescription=$etaCodeDescription&TaxpayerRIN=$etaTaxpayerRIN&ParentCodeID=$etaParentCodeID", 'GET');
    $receivedata = json_decode($response);
    if ($receivedata->code == 200) {
        $smarty->assign("receivedata", $receivedata->data);
    } else {
        $smarty->assign("errorMsg", $receivedata->error[0]);
        $smarty->assign("receivedata", 0);
    }
    $smarty->display("productview/search_code.html");
} elseif ($do == "getproductpricen") {
    $productdata = getproductbarcode();
    echo $productdata->productSellHalfPrice;
} elseif ($do == "getproductpricenen") {
    $productdata = getproductbarcode();
    echo $productdata->productSellAllPrice;
} elseif ($do == "getproductdataForPrintParcode") {
    $productdata = getproductbarcode();
    $productcatdata = getproductcat();

    $productdata->productName = mb_convert_encoding($productdata->productName, 'UTF-8', 'UTF-8');
    $productcatdata->productCatName = mb_convert_encoding($productcatdata->productCatName, 'UTF-8', 'UTF-8');
    $retData = array(
        "parcode" => $productdata->parcode,
        "productName" => $productdata->productName,
        "cat" => $productcatdata->productCatName,
        "getproductprice" => $productdata->productSellUnitPrice,
        "getproductpricen" => $productdata->productSellHalfPrice,
        "getproductpricenen" => $productdata->productSellAllPrice
    );
    echo json_encode($retData);
} elseif ($do == "getproductcat") {
    $productdata = getproductcat();
    echo $productdata->productCatName;
} elseif ($do == "getproductserial") {
    $productdata = getproductserial();
    $itr = $_GET["itr"];
    $smarty->assign("productdata", $productdata);
    $smarty->assign("itr", $itr);
    $smarty->assign("serailcount", count($productdata));
    $smarty->display("productview/productserial.html");
} elseif ($do == "updatebarcode") {
    $productdata = updatebarcode();
    echo $productdata->parcode;
}
//getserail
elseif ($do == "getserail") {
    $alldata = getserail();
    $smarty->assign("alldata", $alldata);

    //print_r($alldata);
    $smarty->assign("serailcount", count($alldata));
    $smarty->display("printbillserailview/productserai.html");
} elseif ($do == "addCat") {
    try {
        $flag = addCat();
        echo $flag;
        //header("location:productController.php");
    } catch (Exception $e) {
        //header("location:?do=error");
    }
} elseif ($do == "catUnits") {
    $catUnitsData = getCatUnits();
    //print_r($catUnitsData);
    $smarty->assign("catUnitsData", $catUnitsData);

    //get units
    $unitsData = getUnits();
    $smarty->assign("unitsData", $unitsData);

    $smarty->display("productview/catUnits.html");
} elseif ($do == "generate") {
    echo generateParcode();
} elseif ($do == "checkbarcode") {
    checkbarcode();
} elseif ($do == "checkbarcodewithid") {
    checkbarcodewithid();
} elseif ($do == "checkUnitbarcode") {
    checkUnitbarcode();
} elseif ($do == "checkUnitbarcodewithid") {
    checkUnitbarcodewithid();
} elseif ($do == "repeatsearch") {
    $productid = $_POST["productid"];
    $parcode = $_POST["parcode"];

    $queryString = ' WHERE';
    if (isset($productid) && $productid != -1) {
        $queryString .= ' product.parcode = ' . $productid . ' AND';
    }

    if (isset($parcode)) {
        $queryString .= ' product.parcode LIKE "%' . $parcode . '%" AND';
    }
    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
    }





    if ($queryString == "") {
        //print_r('in if');
        // $today = date("Y-m-d");where  product.productId = -1
        $queryString .= '  ';
    }
    $productsData = $productExt->queryproductbyquerystring($queryString);
    $categories;
    foreach ($productsData as $productData) {
        $parentId = $productData->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);
        //
        $productData->productName = $productData->productName . '/' . $pathArr;
    }

    //print_r($productsData);
    $smarty->assign("productsData", $productsData);
    $smarty->display("productview/repeatajax.html");
}
##
# Edited by tarek .
//elseif ($do == "product_deleted") {
//
//    $productname = $_POST["productname"];
//    $parcode = $_POST["parcode"];
//    $productcat_deleted = $_POST["productcat_deleted"];
//    $queryString = ' AND';
//
//
//
//
//
//    if (isset($parcode)) {
//        $queryString .= ' product.parcode LIKE "%' . $parcode . '%" AND';
//    }
//
//    if (isset($productname)) {
//        $queryString .= ' product.productName LIKE "%' . $productname . '%" AND';
//    }
//    if (isset($productcat_deleted)) {
//        $queryString .= ' product.productCatId =' . $productcat_deleted;
//    }
//
//    $arr = explode(' ', $queryString);
//    if (isset($arr) && count($arr) > 0) {
//        $lastWord = end($arr);
//        if ($lastWord == 'AND') {//remove it
//            array_pop($arr);
//            //form the string again
//            $queryString = implode(' ', $arr);
//        }
//        if ($lastWord == 'WHERE') {//remove it
//            array_pop($arr);
//            //form the string again
//            $queryString = implode(' ', $arr);
//        }
//    }
//
//
//
//
//
//    if ($queryString == "") {
//        //print_r('in if');
//        // $today = date("Y-m-d");where  product.productId = -1
//        $queryString .= '  ';
//    }
//    $productsData = $productExt->queryproductdeletedbyquerystring($queryString);
//
//    //print_r($productsData);
//    $smarty->assign("productsData", $productsData);
//    $smarty->display("productview/repeatajax.html");
//}
elseif ($do == "product_deleted") {

    global $productExt;

    $categories;
    $row_array = array();
    $return_arr = array();

    //$name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];

    $productname = $_POST["productname"];
    $parcode = $_POST["parcode"];
    $productcat_deleted = $_POST["productcat_deleted"];
    $queryString = ' AND';

    if (isset($parcode)) {
        $queryString .= ' product.parcode LIKE "%' . $parcode . '%" AND';
    }

    if (isset($productname)) {
        $queryString .= ' product.productName LIKE "%' . $productname . '%" AND';
    }
    if (isset($productcat_deleted)) {
        $queryString .= ' product.productCatId =' . $productcat_deleted;
    }

    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
    }

    /*   <option value="0">جملة</option>
      <option value="1">تجزئة</option>
      <option value="2">نصف جملة</option>
     */



    $productsData = $productExt->queryByNameExtWithoutLimitdeleted_2($productname, $queryString);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $pro->productName = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


            //جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }


            array_push($return_arr, $row_array);
        }
    }


    //echo $return_arr;
    //echo json_encode($return_arr);
    //print_r($productsData);
    $smarty->assign("productsData", $productsData);
    $smarty->display("productview/repeatajax.html");
}
##
elseif ($do == "editoptid") {
    unset($_SESSION["productserialArray"]);

    //    $generatedParcode = generateParcode();
    //    $smarty->assign("generatedParcode", $generatedParcode);
    //get product categories
    $allParents = getProductCatParentOptic(); //exceptme
    $smarty->assign("allParents", $allParents);

    //get units
    $unitsData = getUnits();
    $smarty->assign("unitsData", $unitsData);

    getOpticProductData();
    $smarty->assign("gotoshow", 0);
    $smarty->display("productview/editopticproduct.html");
}
##
elseif ($do == "editopticdata") {
    try {
        editopticdata();
        echo 1;
    } catch (Exception $e) {
        //echo $e;
        echo -1;
    }
}
##
elseif ($do == "get_prices") {
    try {
        get_productcat_prices();
        //echo 1;
    } catch (Exception $e) {
        //echo $e;
        echo -1;
    }
}
##
elseif ($do == "m_productUpdate") {
    try {
        //m_productUpdate();
        updateProductCell();
        //echo 1;
    } catch (Exception $e) {
        echo $e;
        echo -1;
    }
} elseif ($do == "UpdateCatDescription") {
    try {
        //m_productUpdate();
        UpdateCatDescription();
        //echo 1;
    } catch (Exception $e) {
        echo $e;
        echo -1;
    }
}
##
//azzzz
elseif ($do == "A_productUpdate") {
    try {
        A_productUpdate();
        //echo 1;
    } catch (Exception $e) {
        echo $e;
        echo -1;
    }
} elseif ($do == "getImageDesc") {
    try {
        $productId = $_POST['pro_id'];

        getImageDesc($productId);
    } catch (Exception $e) {
        echo -1;
    }
} elseif ($do == "reviewunreview") {
    try {
        $productId = $_POST['pro_id'];
        $update = $productExt->updateReview($productId);
        if ($update) {
            echo 1;
        } else {
            echo 0;
        }
    } catch (Exception $e) {
        echo -1;
    }
} elseif ($do == "getDatabyajax") {
    try {
        showallajaxproducts();
    } catch (Exception $e) {
        echo -1;
    }
}
//azzzz
elseif ($do == "updatemenuorder") {
    try {
        updatemenuorder();
        //echo 1;
    } catch (Exception $e) {
        //echo $e;
        echo -1;
    }
} elseif ($do == "updatemenugroups") {
    try {
        updatemenugroups();
        echo 1;
    } catch (Exception $e) {
        //echo $e;
        echo -1;
    }
}
##
elseif ($do == "deleteFinaly") {
    $productId = $_POST["productId"];
    deleteFinaly($productId);
}
##
elseif ($do == "gellastlevelcats") {
    $row_array = array();
    $return_arr = array();
    $newProductOption = (int) $_REQUEST['newProductOption'];

    $lastLevelCatIDS = array();
    array_push($lastLevelCatIDS, 0);
    getAllSubCatKeyVal(0, 2); //mode = 2 get last level cats
    $name = $_GET['term'];

    if ($newProductOption == 1) {
        $row_array['id'] = -1;
        $row_array['text'] = 'تصنيف جديد';
        array_push($return_arr, $row_array);
    }
    //print_r($lastLevelCatIDS);
    if (count($lastLevelCatIDS) > 0) {
        foreach ($lastLevelCatIDS as $key => $value) {
            if ($key > 0 && (empty($name) || strpos($value, $name) !== FALSE)) {
                $row_array['id'] = $key;
                $row_array['text'] = $value;
                array_push($return_arr, $row_array);
            }
        }
    }
    echo json_encode($return_arr);
}
##
elseif ($do == "getsizecolor") {
    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $newOption = (int) $_REQUEST["newOption"];
    $type = (int) $_REQUEST["type"];


    $row_array = array();
    $return_arr = array();

    $resultData = $sizeColorEX->queryByNameExtWithoutLimit($name, " and type = $type ");
    if ($newOption == 1) {
        $row_array['id'] = '-1';
        if ($type == 0) {
            $row_array['text'] .= 'مقاس جديد';
        } else {
            $row_array['text'] .= 'لون جديد';
        }
        array_push($return_arr, $row_array);
    }
    if (count($resultData) > 0) {
        foreach ($resultData as $value) {
            $row_array['id'] = $value->id;
            $row_array['text'] = $value->name;
            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}
##
elseif ($do == "getproductcats") {
    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $row_array = array();
    $return_arr = array();

    $resultData = $productExt->queryAllProducts(" and productcat.productCatName LIKE '%" . $name . "%' ", " limit $limit ");
    foreach ($resultData as $value) {
        $parentId = $value->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);

        $row_array['id'] = $parentId;
        $row_array['text'] = $pathArr;
        array_push($return_arr, $row_array);
    }

    //echo $return_arr;
    echo json_encode($return_arr);
} elseif ($do == "getallcats") {
    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $withoutId = $_GET['withoutId'];

    $row_array = array();
    $return_arr = array();

    $resultData = $productCatExt->queryAllQueryStringSimple(" and productcat.productCatName LIKE '%" . $name . "%' ", " limit $limit ");
    foreach ($resultData as $value) {
        if ($withoutId && $withoutId == $value->productCatId)
            continue;
        $parentId = $value->productCatId;
        $pathArr = fetch_recursive($parentId, $categories);

        $row_array['id'] = $parentId;
        $row_array['text'] = $pathArr;
        array_push($return_arr, $row_array);
    }

    //echo $return_arr;
    echo json_encode($return_arr);
} elseif ($do == "getProductsSizesAndColors") {
    $productId = $_POST['productId'];
    $storeId = $_POST['storeId'];
    if (!$storeId) {
        $storeId = $_SESSION['storeid'];
    }
    $sizeColorStoreDetail = $sizeColorStoreDetailEX->queryByProductidEX($productId, " and storeid = " . $storeId);
    $smarty->assign('sizeColorStoreDetail', $sizeColorStoreDetail);
    $smarty->display('buyBillview/productsizecolorrow.html');
} elseif ($do == "getProductData") {
    $id = filter_input(INPUT_POST, 'id');
    $productData = $productDAO->load($id);
    echo json_encode($productData);
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function checkbarcodewithid_old()
{
    global $productDAO;
    global $productExt;
    //$_SESSION["productserialArray"]=0;
    $productserialArray = $_SESSION["productserialArray"];
    $barcod = $_REQUEST["barcod"];
    $productId = $_REQUEST["id"];
    $thisitr = $_REQUEST["thisitr"];

    //check if this parcode already exists
    $data = $productExt->queryWithParcodeandid($barcod, $productId);
    $flag;
    if (count($data) > 0 || @in_array($barcod, $productserialArray)) {
        $flag = 1;
    } else {
        $flag = 2;
    }

    if (isset($thisitr) && $thisitr >= 0) {
        $flag .= "," . $thisitr;
    }
    echo $flag;
}

function checkbarcode_old()
{
    global $productDAO;
    //$_SESSION["productserialArray"]=0;
    $productserialArray = $_SESSION["productserialArray"];

    $barcod = $_REQUEST["barcod"];
    $thisitr = $_REQUEST["thisitr"];

    //check if this parcode already exists
    $data = $productDAO->queryByParcode($barcod);
    // || @in_array($barcod, $productserialArray)
    $flag;
    if (count($data) > 0) {
        $flag = 1;
    } else {
        $flag = 2;
    }

    if (isset($thisitr) && $thisitr >= 0) {
        $flag .= "," . $thisitr;
    }
    echo $flag;
}

function checkbarcodewithid()
{
    global $productDAO;
    global $productExt;
    global $sizeColorStoreDetailDAO;
    global $availableParcodeDAO;
    global $Programsettingdata;
    //$_SESSION["productserialArray"]=0;
    $productserialArray = $_SESSION["productserialArray"];
    $barcod = $_REQUEST["barcod"];
    $productId = $_REQUEST["id"];
    $thisitr = $_REQUEST["thisitr"];

    $product = $productDAO->load($productId);
    $sizeColorStoreDetail = $sizeColorStoreDetailDAO->queryByProductid($productId);
    $productSizeColorParcodeArr = array();
    foreach ($sizeColorStoreDetail as $value) {
        array_push($productSizeColorParcodeArr, $value->parcode);
    }

    if ($product->parcode == $barcod || in_array($barcod, $productSizeColorParcodeArr)) {
        ##same parcode it is used check for it in db . in all products except this one
        //check if this parcode already exists
        $data = $productExt->queryWithParcodeandid($barcod, $productId);
        $flag;
        if (count($data) > 0 || $flagFromFile == 1 || @in_array($barcod, $productserialArray)) {
            $flag = 1;
        } else {
            $flag = 2;
        }
        $flag2 = 1;
    } else {
        $flag = 1;
        if ($Programsettingdata->usedParcode == 0) {
            //if value in table it is not repeated
            $res = $availableParcodeDAO->queryByValue($barcod);
            if (isset($res) && count($res) > 0) {
                $flag = 2;
                exit();
            }
        }
        //check if this parcode already exists in db
        $data = $productDAO->queryByParcode($barcod);
        $flag2;
        if (count($data) > 0) { //> 1 as now i check for barcode after in
            $flag2 = 1;
        } else {
            $flag2 = 2;
        }
    }

    $flagToreturn = 1;
    if ($flag == 2 || $flag2 == 2) {
        $flagToreturn = 2;
    }


    if (isset($thisitr) && $thisitr >= 0) {
        $flagToreturn .= "," . $thisitr;
    }
    echo $flagToreturn;
}

function checkbarcode()
{
    global $productDAO;
    global $availableParcodeDAO;
    global $Programsettingdata;

    $barcod = $_REQUEST["barcod"];
    $thisitr = $_REQUEST["thisitr"];


    $flag = 1;
    if ($Programsettingdata->usedParcode == 0) {
        //if value in table it is not repeated
        $res = $availableParcodeDAO->queryByValue($barcod);
        if (isset($res) && count($res) > 0) {
            $flag = 2;
            if (isset($thisitr) && $thisitr >= 0) {
                $flag .= "," . $thisitr;
            }
            echo $flag;
            return;
        }
    }

    //check if this parcode already exists in db
    $data = $productDAO->queryByParcode($barcod);
    $flag2;
    if (count($data) > 0) { //> 1 as now i check for barcode after in
        $flag2 = 1;
    } else {
        $flag2 = 2;
    }

    $flagToreturn = 1;
    if ($flag == 2 || $flag2 == 2) {
        $flagToreturn = 2;
    }

    if (isset($thisitr) && $thisitr >= 0) {
        $flagToreturn .= "," . $thisitr;
    }
    echo $flagToreturn;
    return;
}

function checkUnitbarcodewithid()
{
    global $productUnitExt;
    //$_SESSION["productserialArray"]=0;
    //$productserialArray = $_SESSION["productserialArray"];
    $barcod = $_REQUEST["barcod"];
    $porductunitId = (int) $_REQUEST["id"]; //productunitid
    $thisitr = $_REQUEST["thisitr"];

    //check if this parcode already exists in db
    $data = $productUnitExt->queryWithProUnitParcodeAndId($barcod, $porductunitId);
    $flag = 0;
    if (count($data) > 0) {
        $flag = 1;
    }

    if (isset($thisitr) && $thisitr >= 0) {
        $flag .= "," . $thisitr;
    }
    echo $flag;
    return;
}

function checkUnitbarcode()
{
    global $productUnitExt;

    $barcod = $_REQUEST["barcod"];
    $thisitr = $_REQUEST["thisitr"];

    //check if this parcode already exists in db
    $data = $productUnitExt->queryByProUnitParcode($barcod);
    $flag = 0;
    if (count($data) > 0) {
        $flag = 1;
    }


    if (isset($thisitr) && $thisitr >= 0) {
        $flag .= "," . $thisitr;
    }
    echo $flag;
    return;
}

function checkbarcode2($barcod)
{
    global $productDAO;
    global $availableParcodeDAO;
    global $Programsettingdata;
    $flag = 1;
    if ($Programsettingdata->usedParcode == 0) {
        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;

        if ($barcodeToRemove <= $biggestParcode) {

            //if value in table it is not repeated
            $res = $availableParcodeDAO->queryByValue($barcod);
            if (isset($res) && count($res) > 0) {
                $flag = 2;
                return $flag;
            }
        }
    }

    //check if this parcode already exists in db
    $data = $productDAO->queryByParcode($barcod);
    $flag2;
    if (count($data) > 0) { //> 1 as now i check for barcode after in
        $flag2 = 1;
    } else {
        $flag2 = 2;
    }

    $flagToreturn = 1;
    if ($flag == 2 || $flag2 == 2) {
        $flagToreturn = 2;
    }


    return $flagToreturn;
}

function generateParcode_old($length = 5)
{
    global $productDAO;
    //$_SESSION["productserialArray"]=0;

    $productserialArray = $_SESSION["productserialArray"];
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    //check if this parcode already exists
    $data = $productDAO->queryByParcode($randomString);
    if (count($data) > 0) {
        generateParcode();
    } elseif (@in_array($randomString, $productserialArray)) {

        generateParcode();
    } else {
        $productserialArray[$randomString] = $randomString;
        $_SESSION["productserialArray"] = $productserialArray;
        echo $randomString;
    }
}

function generateParcode()
{
    global $availableParcodeEX;
    $parcode = $availableParcodeEX->getAvailableParcodeValue();
    //check if this parcode already exists
    $data = checkbarcode2($parcode);
    if ($data != 2) {
        $parcode = generateParcode();
    }
    return $parcode;
}

function removeParcodeFromTable($barcodeToRemove, $barcodeToAdd = '')
{
    global $Programsettingdata;
    global $availableParcodeDAO;
    if ($Programsettingdata->usedParcode == 0) {
        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;

        if ($barcodeToRemove <= $biggestParcode) {
            $availableParcodeDAO->deleteByValue($barcodeToRemove);
            if (!empty($barcodeToAdd)) {
                $availableParcode = new stdClass();
                $availableParcode->value = $barcodeToAdd;
                $availableParcodeDAO->insert($availableParcode);
            }
        }
    }
}

function getproductserial()
{
    global $ProductserialDAO;
    global $sizeColorStoreDetailEX;

    $productId = $_GET['id'];
    $sizeId = 0;
    $colorId = 0;
    $sizeColorStoreDetailId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        //        $sizeId = $productIdComplex[1];
        //        $colorId = $productIdComplex[2];
        //        $storeid = 1;
        //        $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $storeid, $sizeId, $colorId);
        //        $productsData = $productDAO->load($productId);
        //        $productsData->parcode = $sizeColorStoreDetailData->parcode;
        //        $productsData->productName = $productsData->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
    }
    $productsData = $ProductserialDAO->queryByProductid($productId);
    return $productsData;
}

function edit()
{
    global $productExt;

    $productId = $_GET['id'];
    $productsData = $productExt->loadExtNew($productId);
    return $productsData;
}

function updatebarcode()
{
    global $productExt;
    global $product;
    global $productDAO;

    $productId = $_GET['id'];
    $newbarcod = $_GET['newbarcod'];

    $productsData = $productDAO->load($productId);
    ##check for barcode
    $flag = checkbarcode2($newbarcod);
    if ($flag == 1) {
        //parcode is repeated get another one
        $newbarcod = generateParcode();
    }
    removeParcodeFromTable($newbarcod, $productsData->parcode);

    $productsData->productId = $productId;
    $productsData->parcode = $newbarcod;
    $productDAO->update($productsData);

    //$productExt->updatebarcode($product);
    //$productsData = $productDAO->load($productId);
    return $productsData;
}

function getproductbarcode()
{
    global $productDAO;
    global $Programsettingdata;
    global $sizeColorStoreDetailEX;

    $productId = $_GET['id'];
    $parcodeTypeToPrint = (int) $_GET['parcodeTypeToPrint'];

    $sizeId = 0;
    $colorId = 0;
    $sizeColorStoreDetailId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
        $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeId, $colorId);
        $productsData = $productDAO->load($productId);
        $productsData->parcode = $sizeColorStoreDetailData->parcode;
        $productsData->productName = $productsData->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
    } else {
        $productsData = $productDAO->load($productId);
        if ($parcodeTypeToPrint == 1) {
            $productsData->parcode = useSpecializedParcodeDigits($productsData->parcode, $productsData->productId, $Programsettingdata->specializedParcodeDigits);
        }
    }

    return $productsData;
}

function getproductcat()
{
    global $productExt;
    global $productDAO;
    global $productCatExt;
    global $sizeColorStoreDetailEX;

    $productId = $_GET['id'];
    $sizeId = 0;
    $colorId = 0;
    $sizeColorStoreDetailId = 0;
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
        $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeId, $colorId);
        $productsData = $productExt->loadProduct($productId);
        $productsData->parcode = $sizeColorStoreDetailData->parcode;
        $productsData->productName = $productsData->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
    } else {
        $productsData = $productExt->loadProduct($productId);
    }


    return $productsData;
}

//productCat
function getProductCats()
{
    //to use the variable outside the funcion
    global $productCatExt;

    //كل التصنيفات التي ليست parent لأي تصنيف آخر
    $alldata = $productCatExt->queryAllChildrenExt2();
    return $alldata;
}

function checkForChildren()
{
    global $productCatExt;

    $productCatId = $_GET['id'];
    //$childData = $productCatExt->queryByParentExt($productCatId);
    $childData = $productCatExt->getChilds($productCatId);

    return $childData;
}

function get_productcat_prices()
{
    global $productCatExt;
    global $Programsettingdata;

    $productCatId = (int) $_POST['productCatId'];
    if ($productCatId == 0) {
        $prices_Data->buypricereal = 0;
        $prices_Data->buytotal = 0;
        $prices_Data->buyhalf = 0;
        $prices_Data->buypart = 0;
        if ($Programsettingdata->showprice4 == 1)
            $prices_Data->price4 = 0;
        if ($Programsettingdata->showprice5 == 1)
            $prices_Data->price5 = 0;
        if ($Programsettingdata->showprice6 == 1)
            $prices_Data->price6 = 0;
        if ($Programsettingdata->showprice7 == 1)
            $prices_Data->price7 = 0;
        if ($Programsettingdata->showprice8 == 1)
            $prices_Data->price8 = 0;
        if ($Programsettingdata->showprice9 == 1)
            $prices_Data->price9 = 0;
        if ($Programsettingdata->showprice10 == 1)
            $prices_Data->price10 = 0;
        if ($Programsettingdata->showprice11 == 1)
            $prices_Data->price11 = 0;
        if ($Programsettingdata->showprice12 == 1)
            $prices_Data->price12 = 0;
        if ($Programsettingdata->showprice13 == 1)
            $prices_Data->price13 = 0;
    } else {
        //$childData = $productCatExt->queryByParentExt($productCatId);
        $prices_Data = $productCatExt->productcat_prices($productCatId);
    }


    $prices_array = array('buypricereal' => $prices_Data->buypricereal, 'buytotal' => $prices_Data->buytotal, 'buyhalf' => $prices_Data->buyhalf, 'buypart' => $prices_Data->buypart, 'price4' => $prices_Data->price4, 'price5' => $prices_Data->price5, 'price6' => $prices_Data->price6, 'price7' => $prices_Data->price7, 'price8' => $prices_Data->price8, 'price9' => $prices_Data->price9, 'price10' => $prices_Data->price10, 'price11' => $prices_Data->price11, 'price12' => $prices_Data->price12, 'price13' => $prices_Data->price13);
    // if (isset($prices_Data->price4))
    //     $prices_array["price4"]  = $prices_Data->price4;
    echo json_encode($prices_array);
    // print_r($prices_array);
    //    return $childData;
}

function checkForProducts()
{
    global $productExt;

    $productCatId = $_GET['id'];
    $childData = $productExt->queryByProductCatIdNotdeletedExt($productCatId);
    return $childData;
}

function getUnits()
{
    global $unitDAO;

    $unitsData = $unitDAO->queryByCondition(0);
    return $unitsData;
}

function getProductUnits($productId)
{
    global $productUnitExt;
    global $catUnitExt;

    $productUnitData = $productUnitExt->queryByProductidExt($productId);

    return $productUnitData;
}

function getCatUnits()
{
    global $catUnitExt;
    global $smarty;
    $catid = $_GET['catid'];
    $productItr = $_GET['productItr'];
    $unitItr = $_GET['unitItr'];
    if (isset($catid) && isset($productItr) && isset($unitItr)) {
        $catUnitsData = $catUnitExt->queryByProductCatidExt($catid);
        $smarty->assign("productItr", $productItr);
        $smarty->assign("unitItr", $unitItr);
    }
    return $catUnitsData;
}

function update()
{
    global $productExt;
    global $productDAO;
    global $product;
    global $productUnitDAO;
    global $productUnit;
    global $productUnitExt;
    global $buyBillDetailExt;
    global $SellbilldetailEX;
    global $SellbilldetailDAO;
    global $productCatDAO;
    global $Programsettingdata;
    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    $storeId = 1;

    $productId = (int) $_POST['productId'];
    $productCatId = $_POST['productCatId'];
    $productItr = $_POST['productItr'];
    //for($i=1;$i<=$productItr;$i++)
    //{
    $productName = $_POST['productName1'];
    $productDescription = $_POST['productDescription1'];
    $conditions = $_POST['conditions'];
    $productBuyPrice = $_POST['productBuyPrice1'];
    $parcode = $_POST['parcode1'];
    $expireDate = (int) $_POST['expireDate1'];
    $productSellAllPrice = $_POST['productSellAllPrice1'];
    $productSellHalfPrice = $_POST['productSellHalfPrice1'];
    $productSellUnitPrice = $_POST['productSellUnitPrice1'];
    $price4 = $_POST['price4_1'];
    $price5 = $_POST['price5_1'];
    $price6 = $_POST['price6_1'];
    $price7 = $_POST['price7_1'];
    $price8 = $_POST['price8_1'];
    $price9 = $_POST['price9_1'];
    $price10 = $_POST['price10_1'];
    $price11 = $_POST['price11_1'];
    $price12 = $_POST['price12_1'];
    $price13 = $_POST['price13_1'];
    $productDate = $_POST['productDate1'];
    $limitamount = $_POST['limitamount1'];
    $productDescription = $_POST['productDescription1'];
    $manufacture = $_POST['manufacture'];
    $productQuantity = $_POST['productquantity1'];
    $inMenu = $_POST['inMenu1'];
    $clientid = $_POST['clientid1'];


    $productBuyPrice = round($productBuyPrice, 2);
    $productSellAllPrice = round($productSellAllPrice, 2);
    $productSellHalfPrice = round($productSellHalfPrice, 2);
    $productSellUnitPrice = round($productSellUnitPrice, 2);
    $price4 = round($price4, 2);
    $price5 = round($price5, 2);
    $price6 = round($price6, 2);
    $price7 = round($price7, 2);
    $price8 = round($price8, 2);
    $price9 = round($price9, 2);
    $price10 = round($price10, 2);
    $price11 = round($price11, 2);
    $price12 = round($price12, 2);
    $price13 = round($price13, 2);
    $productbuypricereal = round($productbuypricereal, 2);

    $productbuypricereal = $_POST['productbuypricereal1'];
    $buypricereal_precentage = $_POST['buypricereal_precentage1'];
    $buytotal_precentage = $_POST['buytotal_precentage1'];
    $buyhalf_precentage = $_POST['buyhalf_precentage1'];
    $buypart_precentage = $_POST['buypart_precentage1'];

    $productbuypricereal = round($productbuypricereal, 2);
    $buypricereal_precentage = round($buypricereal_precentage, 2);
    $buytotal_precentage = round($buytotal_precentage, 2);
    $buyhalf_precentage = round($buyhalf_precentage, 2);
    $buypart_precentage = round($buypart_precentage, 2);

    $isservice = $_POST['isservice1'];
    if ($isservice == 1) {
        $productBuyPrice = 0;
        $productQuantity = 0;
    }
    $productData = $productDAO->load($productId);
    $productBuyPriceOld = (float) $productData->productBuyPrice;

    ###############################
    $erpDB = $_POST["erpDB"];
    $detection_id = $_POST["detection_id"];
    $investigation_id = $_POST["investigation_id"];
    $sessionDBName = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $sessionDBName = $_SESSION['dbname'];
    }
    //choose erpDB user has choosen in obygy_app
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = 1; //tempppppppppppppppp
        if (empty($productName)) {
            $productName = 'obj_app_detection';
        }
        //$cat_id
        if (!isset($_POST['productCatId']) || empty($_POST['productCatId']) || $_POST['productCatId'] == "obygy") {
            $catName = $_POST['obygy_cat_name'];
            if (empty($catName)) {
                $catName = 'Services'; //'obygy services';
            }

            $catData = $productCatDAO->queryByProductCatName($catName);

            if (count($catData) > 0) {
                $productCatId = $catData[0]->productCatId;
            } else {
                $productCatId = addCatByNameOnly($catName);
            }
        }
        $parcode = $productData->parcode;
    }
    #################################
    ##check for barcode
    $flag = checkbarcode($parcode);
    if ($flag == 1) {
        //parcode is repeated get another one
        $parcode = generateParcode();
    }
    removeParcodeFromTable($parcode, $productData->parcode);
    //update product
    $productData->conditions = $conditions;
    $productData->limitamount = $limitamount;
    $productData->parcode = $parcode;
    $productData->expireDate = $expireDate;
    $productData->productBuyPrice = $productBuyPrice;
    $productData->productCatId = $productCatId;
    $productData->productDate = $productDate;
    $productData->productDescription = $productDescription;
    $productData->productName = $productName;
    $productData->productSellAllPrice = $productSellAllPrice;
    $productData->productSellHalfPrice = $productSellHalfPrice;
    $productData->productSellUnitPrice = $productSellUnitPrice;
    $productData->price4 = $price4;
    $productData->price5 = $price5;
    $productData->price6 = $price6;
    $productData->price7 = $price7;
    $productData->price8 = $price8;
    $productData->price9 = $price9;
    $productData->price10 = $price10;
    $productData->price11 = $price11;
    $productData->price12 = $price12;
    $productData->price13 = $price13;
    $productData->productbuypricereal = $productbuypricereal;
    $productData->buypricereal_precentage = $buypricereal_precentage;
    $productData->buytotal_precentage = $buytotal_precentage;
    $productData->buyhalf_precentage = $buyhalf_precentage;
    $productData->buypart_precentage = $buypart_precentage;
    $productData->userId = $_SESSION['userid'];
    $productData->type = $manufacture;
    $productData->isService = $isservice;

    $productData->productId = $productId;
    $productData->inMenu = $inMenu;
    $productData->obygyDetectionId = $detection_id;
    $productData->obygyInvestigationId = $investigation_id;
    $productData->clientid = $clientid;

    $productDAO->update($productData);

    if (!empty($productId)) {
        //1- delete all product unit associated with this product
        //productunitid
        $allmyunitdata = $productUnitDAO->queryByProductid($productId);
        foreach ($allmyunitdata as $myunitdata) {
            $allbuydata = $buyBillDetailExt->queryAllbyproductunitid($myunitdata->productunitid);
            $myselldata = $SellbilldetailEX->queryAllbyproductunitid($myunitdata->productunitid);

            //print_r($myselldata);
            //if(count($allbuydata) == 0 &&  count($myselldata) == 0)
            {

                /* echo 'deleted  id =  '.$myunitdata->productunitid.'<br>';
                  $productUnitDAO->delete($myunitdata->productunitid);
                  echo '<br> '; */
            }
            //else
            {

                //echo 'update id =  '.$myunitdata->productunitid.' <br>';
                $productUnitExt->updatecondation($myunitdata->productunitid);
            }
        }


        //2- insert product units again with the new ones if any
        $unitsItr = $_POST['unitsItr1'];
        $Unitdone = 0;
        for ($j = 1; $j <= $unitsItr; $j++) {
            //print("for");
            $productunit = $_POST['productunit1' . $j];
            $productnumber = $_POST['productnumber1' . $j];
            $productunitid = $_POST['productunitid' . $j];
            $proUnitParcode = $_POST['proUnitParcode1' . $j];
            $proUnitSellAllPrice = (float) $_POST['proUnitSellAllPrice1' . $j];
            $proUnitSellHalfPrice = (float) $_POST['proUnitSellHalfPrice1' . $j];
            $proUnitSellUnitPrice = (float) $_POST['proUnitSellUnitPrice1' . $j];
            $proUnitBuyPrice = (float) $_POST['proUnitBuyPrice1' . $j];
            if (!empty($productunit) && $productunit != '-1' && !empty($productnumber)) {
                if (empty($proUnitParcode))
                    $proUnitParcode = addPreDigitsToNum2($productId, 5) . addPreDigitsToNum2($productunit, 2);

                if (empty($proUnitSellAllPrice) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                    $proUnitSellAllPrice = $product->productSellAllPrice * $productnumber;

                if (empty($proUnitSellHalfPrice) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                    $proUnitSellHalfPrice = $product->productSellHalfPrice * $productnumber;

                if (empty($proUnitSellUnitPrice) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                    $proUnitSellUnitPrice = $product->productSellUnitPrice * $productnumber;

                if (empty($proUnitBuyPrice) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                    $proUnitBuyPrice = $product->productBuyPrice * $productnumber;


                //insert into productunit tbl
                $productUnit->conditions = 0;
                $productUnit->productid = $productId;
                $productUnit->productnumber = $productnumber;
                $productUnit->productunitdate = $today;
                $productUnit->unitid = $productunit;
                $productUnit->userid = $_SESSION['userid'];
                $productUnit->proUnitParcode = $proUnitParcode;
                $productUnit->proUnitSellAllPrice = $proUnitSellAllPrice;
                $productUnit->proUnitSellHalfPrice = $proUnitSellHalfPrice;
                $productUnit->proUnitSellUnitPrice = $proUnitSellUnitPrice;
                $productUnit->proUnitBuyPrice = $proUnitBuyPrice;

                if (isset($productunitid) && $productunitid > 0) {
                    //echo 'update id =  '.$productunitid.' <br>';
                    $productUnit->productunitid = $productunitid;
                    $productunitid = $productUnitDAO->update($productUnit);
                } else {
                    //echo 'insert id =  '.$productunitid.' <br>';
                    $productUnitDAO->insert($productUnit);
                }
                $Unitdone = 1;
            }
        }

        //print_r($Unitdone);
        if ($Unitdone == 0) {
            //	print_r('in if');
            $productUnit->conditions = 0;
            $productUnit->productid = $productId;
            $productUnit->productnumber = 1;
            $productUnit->productunitdate = $today;
            $productUnit->unitid = 1;
            $productUnit->userid = $_SESSION['userid'];
            $productUnit->proUnitParcode = addPreDigitsToNum2($productId, 5) . addPreDigitsToNum2($productUnit->unitid, 2);
            $productUnit->proUnitSellAllPrice = $product->productSellAllPrice;
            $productUnit->proUnitSellHalfPrice = $product->productSellHalfPrice;
            $productUnit->proUnitSellUnitPrice = $product->productSellUnitPrice;
            $productUnit->proUnitBuyPrice = $product->productBuyPrice;

            $productUnitDAO->insert($productUnit);
        }
    }


    ##dailyEntry
    if ($productBuyPriceOld != $productBuyPrice) {
        //$rid = reverseEntryWithItsID($productData->dailyentryId);// no need new entry will be with the diff in price
        //////////////////////////Imsert in daily entry
        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $productInStoreData = R::getAll('select productquantity,treeId
            from storedetail
            join store on store.storeId = storedetail.storeid
            where productquantity !=0 and productid=' . $productId);
        foreach ($productInStoreData as $value) {
            #calc
            $changeInPrice = $productBuyPrice - $productBuyPriceOld; //diff might be negative
            $entryValue = $changeInPrice * $value['productquantity']; //quantity might be -ve too
            $dailyEntry->entryComment = "تعديل منتج ($productName) السعر من ($productBuyPriceOld) الى ($productBuyPrice) و الكميه (" . (float) $value['productquantity'] . ")";
            #entry
            $dailyEntryDebtorArray = array();
            $dailyEntryCreditorArray = array();
            $dailyEntryDebtor->value = $dailyEntryCreditor->value = abs($entryValue);

            if ($entryValue > 0) {
                $dailyEntryDebtor->accountstreeid = $value['treeId'];
                $dailyEntryCreditor->accountstreeid = 53;
            } else {
                $dailyEntryDebtor->accountstreeid = 53;
                $dailyEntryCreditor->accountstreeid = $value['treeId'];
            }
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
            //$did = $returnedData[1];
        }
    }

    $product = $productDAO->load($productId);

    //update product
    $product->type = $type;
    $product->conditions = $conditions;
    $product->limitamount = $limitamount;
    $product->parcode = $parcode;
    $product->productBuyPrice = $productBuyPrice;
    $product->productCatId = $productCatId;
    $product->productDate = $productDate;
    $product->productDescription = $productDescription;
    $product->productName = $productName;
    $product->productSellAllPrice = $productSellAllPrice;
    $product->productSellHalfPrice = $productSellHalfPrice;
    $product->productSellUnitPrice = $productSellUnitPrice;
    $product->userId = $_SESSION['userid'];
    $product->inMenu = $inMenu;
    $product->productId = $productId;
    //$product->dailyentryId = $did;

    $productDAO->update($product);
    //go back to your db
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $sessionDBName;
        unset($_SESSION['userid']); //tempppppppppppppppp
    }
    //}
    //write in the xml file
    //createXMLFile();
}

function m_productUpdate()
{


    global $productExt;
    global $productDAO;
    global $product;

    $productId = $_POST['pro_id'];
    $pro_name = $_POST['pro_name'];
    $pro_allprice = $_POST['pro_allprice'];
    $pro_halfprice = $_POST['pro_halfprice'];
    $pro_unitPrice = $_POST['pro_unitPrice'];
    $pro_catid = (int) $_POST['pro_catid'];
    $pro_buyprice = $_POST['pro_buyprice'];
    $inMenu = (int) $_POST['$inMenu'];
    $handle = new upload($_FILES['pro_Image']);
    $image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/product_image');
    reduceImageSize($image);
    $pro_Description = $_POST['pro_Description'];

    if (empty($pro_name) && empty($pro_allprice) && empty($pro_halfprice) && empty($pro_unitPrice) && empty($pro_buyprice) && empty($pro_catid)) {
        return false;
    }

    $rowData = $productDAO->load($productId);

    if (!empty($pro_name)) {
        $productName = $pro_name;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $rowData->productSellUnitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productDescription = $rowData->productDescription;
        $productImage = $rowData->logo;
    }
    if (!empty($pro_buyprice)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $rowData->productSellUnitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $pro_buyprice;
        $productDescription = $rowData->productDescription;
        $productImage = $rowData->logo;
    }
    if (!empty($pro_allprice)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $pro_allprice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $rowData->productSellUnitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productDescription = $rowData->productDescription;
        $productImage = $rowData->logo;
    }
    if (!empty($pro_halfprice)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $pro_halfprice;
        $productSellUnitPrice = $rowData->productSellUnitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productDescription = $rowData->productDescription;
        $productImage = $rowData->logo;
    }
    if (!empty($pro_unitPrice)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $pro_unitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productImage = $rowData->logo;
        $productDescription = $rowData->productDescription;
    }

    if (!empty($image)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $pro_unitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productImage = $image;
        $productDescription = $rowData->productDescription;
    }

    if (!empty($pro_Description)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $pro_unitPrice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productImage = $rowData->logo;

        $productDescription = $pro_Description;
    }

    if (!empty($pro_allprice) && !empty($pro_halfprice) && !empty($pro_unitPrice) && !empty($pro_Description) && !empty($image)) {
        $productName = $rowData->productName;
        $productSellAllPrice = $pro_allprice;
        $productSellHalfPrice = $pro_allprice;
        $productSellUnitPrice = $pro_allprice;
        $productCatId = $rowData->productCatId;
        $productBuyPrice = $rowData->productBuyPrice;
        $productDescription = $pro_Description;
        $productImage = $image;
    }

    if (!empty($pro_catid) && $pro_catid > 0) {
        $productCatId = $pro_catid;
        $productName = $rowData->productName;
        $productSellAllPrice = $rowData->productSellAllPrice;
        $productSellHalfPrice = $rowData->productSellHalfPrice;
        $productSellUnitPrice = $rowData->productSellUnitPrice;
        $productBuyPrice = $rowData->productBuyPrice;
        $productDescription = $rowData->productDescription;
        $productImage = $rowData->logo;
    }

    $rowData->productId = $productId;
    $rowData->productName = $productName;
    $rowData->productSellAllPrice = $productSellAllPrice;
    $rowData->productSellHalfPrice = $productSellHalfPrice;
    $rowData->productSellUnitPrice = $productSellUnitPrice;
    $rowData->productCatId = $productCatId;
    $rowData->productBuyPrice = $productBuyPrice;
    $rowData->productDescription = $productDescription;
    $rowData->logo = $productImage;
    $rowData->inMenu = $inMenu;

    //    print_r($product);

    $productDAO->update($rowData);
    onlineTempProductFunc($productId, 1);
}

//fatma
function updateProductCell()
{
    global $productDAO;
    global $productCatDAO;
    global $productUnitExt;
    global $Programsettingdata;

    $productId = $_POST['pro_id'];
    $type = $_POST['type'];
    $value = $_POST['value'];
    $isOptic = (int) $_POST['isOptic'];
    $username = $_POST['username'];

    if (empty($productId) || empty($type)) {
        return false;
    }
    if ($isOptic == 2) {
        $rowData = $productCatDAO->load($productId);
        $catProducts = $productDAO->queryByProductCatId($productId);
        switch ($type) {
            case 'name':
            case 'nameNew':
                $rowData->productCatName = $value;
                $productCatDAO->update($rowData);
                onlineTempCategoryFunc($productId, 1);
                break;
            case 'pro_catid':
                $rowData->productCatParent = $value;
                $productCatDAO->update($rowData);
                onlineTempCategoryFunc($productId, 1);
                break;
            case 'Description':
            case 'DescriptionNew':
                $rowData->productCatDescription = $value;
                $productCatDAO->update($rowData);
                onlineTempCategoryFunc($productId, 1);
                break;
            case 'allprice':
            case 'allpriceNew':
                foreach ($catProducts as $pro) {
                    $pro->productSellAllPrice = $value;
                    if ($Programsettingdata->editAllPrice == 1) {
                        $pro->productSellHalfPrice = $value;
                        $pro->productSellUnitPrice = $value;
                    }
                    $productDAO->update($pro);
                    onlineTempProductFunc($pro->productId, 1);
                    if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                        $sql = "UPDATE productunit SET proUnitSellAllPrice  = $value * productnumber ";
                        if ($Programsettingdata->editAllPrice == 1) {
                            $sql .= " ,proUnitSellHalfPrice = $value * productnumber,proUnitSellUnitPrice = $value * productnumber";
                        }
                        $sql .= " WHERE productid = $pro->productId";
                        $productUnitExt->updateQuery($sql);
                    }
                }
                break;
            case 'halfprice':
            case 'halfpriceNew':
                foreach ($catProducts as $pro) {
                    $pro->productSellHalfPrice = $value;
                    $productDAO->update($pro);
                    onlineTempProductFunc($pro->productId, 1);
                    if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                        $sql = "UPDATE productunit SET proUnitSellHalfPrice = $value * productnumber WHERE productid = $pro->productId";
                        $productUnitExt->updateQuery($sql);
                    }
                }
                break;
            case 'unitPrice':
            case 'unitPriceNew':
                foreach ($catProducts as $pro) {
                    $pro->productSellUnitPrice = $value;
                    $productDAO->update($pro);
                    onlineTempProductFunc($pro->productId, 1);
                    if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                        $sql = "UPDATE productunit SET proUnitSellUnitPrice = $value * productnumber WHERE productid = $pro->productId";
                        $productUnitExt->updateQuery($sql);
                    }
                }
                break;
            case 'buyprice':
            case 'buypriceNew':
                foreach ($catProducts as $rowData) {
                    if ($value != $rowData->productBuyPrice) {
                        //
                        $meanbuyprice = ($rowData->meanbuyprice + $value) / 2;
                        //                $meanbuyprice_withDiscount = round($meanbuyprice_withDiscountNew, 2); // fatma
                        $meanbuyprice_withDiscount = ($rowData->meanbuyprice_withDiscount + $value) / 2; //azmy
                        $lastbuyprice_withTax = ($rowData->lastbuyprice_withTax + $value) / 2; //fatma
                        $meanbuyprice_withTax = ($rowData->meanbuyprice_withTax + $value) / 2; //fatma
                        //
                        $product->meanbuyprice = round($meanbuyprice, 2);
                        $product->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, 2);
                        $product->lastbuyprice_withTax = round($lastbuyprice_withTax, 2);
                        $product->meanbuyprice_withTax = round($meanbuyprice_withTax, 2);
                        //
                        $rowData->meanbuyprice = round($meanbuyprice, 2);
                        $rowData->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, 2);
                        $rowData->lastbuyprice_withTax = round($lastbuyprice_withTax, 2);
                        $rowData->meanbuyprice_withTax = round($meanbuyprice_withTax, 2);
                    }
                    $rowData->productBuyPrice = $value;
                    $productDAO->update($rowData);
                    onlineTempProductFunc($rowData->productId, 1);
                    if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                        $sql = "UPDATE productunit SET proUnitBuyPrice  = $value * productnumber WHERE productid = $pro->productId";
                        $productUnitExt->updateQuery($sql);
                    }
                }

                break;
        }
    } else {
        $rowData = $productDAO->load($productId);
        switch ($type) {
            case 'name':
            case 'nameNew':
                $rowData->productName = $value;
                break;
            case 'allprice':
            case 'allpriceNew':
                $rowData->productSellAllPrice = $value;
                if ($Programsettingdata->editAllPrice == 1) {
                    $rowData->productSellHalfPrice = $value;
                    $rowData->productSellUnitPrice = $value;
                }
                if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                    $sql = "UPDATE productunit SET proUnitSellAllPrice  = $value * productnumber ";
                    if ($Programsettingdata->editAllPrice == 1) {
                        $sql .= " ,proUnitSellHalfPrice = $value * productnumber,proUnitSellUnitPrice = $value * productnumber";
                    }
                    $sql .= " WHERE productid = $productId";
                    $productUnitExt->updateQuery($sql);
                }
                break;
            case 'halfprice':
            case 'halfpriceNew':
                $rowData->productSellHalfPrice = $value;
                if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                    $sql = "UPDATE productunit SET proUnitSellHalfPrice = $value * productnumber WHERE productid = $productId";
                    $productUnitExt->updateQuery($sql);
                }
                break;
            case 'unitPrice':
            case 'unitPriceNew':
                $rowData->productSellUnitPrice = $value;
                if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                    $sql = "UPDATE productunit SET proUnitSellUnitPrice = $value * productnumber WHERE productid = $productId";
                    $productUnitExt->updateQuery($sql);
                }
                break;
            case 'price4':
                $rowData->price4 = $value;
                break;
            case 'price5':
                $rowData->price5 = $value;
                break;
            case 'price6':
                $rowData->price6 = $value;
                break;
            case 'price7':
                $rowData->price7 = $value;
                break;
            case 'price8':
                $rowData->price8 = $value;
                break;
            case 'price9':
                $rowData->price9 = $value;
                break;
            case 'price10':
                $rowData->price10 = $value;
                break;
            case 'price11':
                $rowData->price11 = $value;
                break;
            case 'price12':
                $rowData->price12 = $value;
                break;
            case 'price13':
                $rowData->price13 = $value;
                break;
            case 'buyprice':
            case 'buypriceNew':
                if ($value != $rowData->productBuyPrice) {
                    //
                    $meanbuyprice = ($rowData->meanbuyprice + $value) / 2;
                    //                $meanbuyprice_withDiscount = round($meanbuyprice_withDiscountNew, 2); // fatma
                    $meanbuyprice_withDiscount = ($rowData->meanbuyprice_withDiscount + $value) / 2; //azmy
                    $lastbuyprice_withTax = ($rowData->lastbuyprice_withTax + $value) / 2; //fatma
                    $meanbuyprice_withTax = ($rowData->meanbuyprice_withTax + $value) / 2; //fatma
                    //
                    $product->meanbuyprice = round($meanbuyprice, 2);
                    $product->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, 2);
                    $product->lastbuyprice_withTax = round($lastbuyprice_withTax, 2);
                    $product->meanbuyprice_withTax = round($meanbuyprice_withTax, 2);
                    //
                    $rowData->meanbuyprice = round($meanbuyprice, 2);
                    $rowData->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, 2);
                    $rowData->lastbuyprice_withTax = round($lastbuyprice_withTax, 2);
                    $rowData->meanbuyprice_withTax = round($meanbuyprice_withTax, 2);

                    ##
                    priceDiffDailyEntry($productId, $value);
                }
                $rowData->productBuyPrice = $value;
                if ($Programsettingdata->updateProUnitPricesOnPriceUpdate == 0) {
                    $sql = "UPDATE productunit SET proUnitBuyPrice  = $value * productnumber WHERE productid = $productId";
                    $productUnitExt->updateQuery($sql);
                }
                break;
            case 'pro_catid':
                $rowData->productCatId = $value;
                break;
            case 'Description':
            case 'DescriptionNew':
                $rowData->productDescription = $value;
                $rowData->updatebyuser = $username;
                break;
            case 'online':
            case 'online':
                $rowData->online = $value;
                break;
        }
        $productDAO->update($rowData);
        onlineTempProductFunc($productId, 1);
    }
}

//azmy
function A_productUpdate()
{


    global $productExt;
    global $productDAO;
    global $product;


    $x = $_POST['itracolum'];
    $productId = $_POST['pro_id'];
    $file_name = $_POST['file_name'];
    $handle = new upload($_FILES[$file_name]);
    $image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/product_image');
    reduceImageSize($image);
    // $rowData = $productDAO->load($productId);
    $username = $_POST['username'];
    if ($x == 0) {
        $x = '';
    }

    $productImage = $image;
    $col = logo . $x;
    $product->productId = $productId;
    $product->$col = $productImage;

    //    onlineTempProductFunc(5, 1);
    $productDAO->update1($product, $x, $username);

    //$src = hosturl.'/views/default/images/product_image/'.$image;
    echo $image;
}

//azmy

function createXMLFile()
{

    global $productDAO;

    $productsData = $productDAO->queryByConditions(0);
    if (count($productsData) > 0) {
        //*************** write in xml files **************//
        $newTags = '<?xml version="1.0" encoding="utf-8"?>';
        $newTags .= '<document>';
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathString = fetch_recursive($parentId, $categories);

            $pathString = $pathString . '/' . $pro->productName;

            //emptying xml files
            $productXMLFile = @fopen("productXML.xml", "r+");
            if ($productXMLFile !== false) {
                ftruncate($productXMLFile, 0);
                fclose($productXMLFile);
            }

            //replace something in the file string
            $newTags .= "\n<product>
                                                             <id>" . $pro->productId . "</id>
                                                             <title> " . $pro->productName . " </title>
                                                             <path>" . $pathString . "</path>
                                                             <buyPrice>" . $pro->productBuyPrice . "</buyPrice>
                                                             </product>";

            //write in sitemap.xml
            file_put_contents('productXML.xml', $newTags);
        }
        $newTags .= '</document>';
        //*******************************************************//
    }
}

// add in productCat tbl
function addCat()
{
    global $productCatDAO;
    global $productCatExt;
    global $productCat;
    global $catUnit;
    global $catUnitDAO;
    global $today;
    //print("addCat2<br>");
    $productCatName = $_REQUEST['productCatName'];
    $productCatDescription = $_REQUEST['productCatDescription'];
    $parent = (int) $_REQUEST['parent'];
    if (empty($parent) || $parent == -1) {
        $parent = 0;
    }
    $flag = 0;
    if (!empty($productCatName) && $productCatName != '' && !empty($parent)) {
        if (count($productCatExt->queryByParentAndProductcatNameExt($parent, $productCatName)) == 0) {

            $productCat->discounttype = 0;
            $productCat->selldiscount = 0;
            $productCat->buydiscount = 0;

            $productCat->conditions = 0;
            $productCat->productCatDate = $today;
            $productCat->productCatDescription = $productCatDescription;
            $productCat->productCatName = $productCatName;
            $productCat->productCatParent = $parent;
            $productCat->userId = $_SESSION['userid'];
            $productCat->isOptic = 0;
            $productCat->inMenu = 0;
            //print_r($productCat);

            $productCatId = $productCatDAO->insert($productCat);

            if (!empty($productCatId)) {
                onlineTempCategoryFunc($productCatId, 1);
                $flag = 0;
                $cat_unitsItr = $_POST['cat_unitsItr'];
                //print("cat_unitsItr: ".$cat_unitsItr);
                for ($j = 1; $j <= $cat_unitsItr; $j++) {
                    $productunit = $_POST['productcatunit' . $j];
                    $cat_productnumber = $_POST['cat_productnumber' . $j];
                    //print("<br>productunit: ".$productunit."<br>cat_productnumber: ".$cat_productnumber);
                    if (!empty($productunit) && $productunit != '-1' && !empty($cat_productnumber)) {
                        //insert into productunit tbl
                        $catUnit->conditions = 0;
                        $catUnit->productcatid = $productCatId;
                        $catUnit->productnumber = $cat_productnumber;
                        $catUnit->productcatunitdate = $today;
                        $catUnit->unitid = $productunit;
                        $catUnit->userid = $_SESSION['userid'];

                        $catUnitDAO->insert($catUnit);
                    }
                }
            }
        } else {
            $flag = 2;
            echo $flag;
        }
    } else {
        $flag = 1;
        echo $flag;
    }
    return $flag;
}

function getserail()
{
    global $Productserial;
    global $ProductserialDAO;
    global $ProductserialEX;


    $billid = $_REQUEST["billid"];
    $type = $_REQUEST["type"];
    $alldata = $ProductserialEX->queryWithbillid($billid, $type);

    return $alldata;
}

##for optic

function getProductCatParentOptic()
{
    global $productCatDAO;

    $allParents = $productCatDAO->queryByCondition(0);
    return $allParents;
}

function getOpticProductData()
{
    global $product;
    global $productDAO;
    global $productExt;

    //Productcat
    global $productCat;
    global $productCatDAO;

    global $productUnit;
    global $productUnitDAO;
    global $productUnitExt;

    global $smarty;

    //1-cat data
    $id = $_GET["id"];
    $catData = $productCatDAO->load($id);
    $smarty->assign("catData", $catData);
    //2-products data
    $productData = $productExt->queryByProductCatIdWithCount($catData->productCatId);
    //    foreach ($productData as $pro) {
    //        $tempData = $productUnitDAO->queryByProductid($pro->productId);
    //        foreach ($tempData as $value) {
    //            $pro->productUnitIds .= $value->productunitid . ",";
    //        }
    //        $pro->productUnitIds = rtrim($pro->productUnitIds, ",");
    //    }
    $smarty->assign("productData", $productData);
    $smarty->assign("productDataCount", count($productData));
    //3-get units
    if ($productData[0]->productId > 0) {
        $productUnitsData = $productUnitDAO->queryByProductid($productData[0]->productId);
        foreach ($productUnitsData as $data) {
            foreach ($productData as $value) {
                $tempData = $productUnitExt->queryWithProductIdAndUnitIdSimple($value->productId, $data->unitid);
                foreach ($tempData as $finally) {
                    $data->myids .= $finally->productunitid . "-" . $finally->productid . ",";
                }
            }
        }

        foreach ($productUnitsData as $value) {
            $value->myids = rtrim($value->myids, ",");
            $value->productunitid = $value->myids;
        }

        $smarty->assign("productUnitsData", $productUnitsData);
        $smarty->assign("productUnitsDataCount", count($productUnitsData));
    }
}

function editopticdata()
{
    $currentType = filter_input(INPUT_POST, "currentType");
    if ($currentType == 0) {
        editOpticProductWithSizeColor();
    } /* elseif ($currentType == 1) {
      addOpticProductWithOutSizeColor();
      } */
}

function editOpticProductWithSizeColor()
{
    global $product;
    global $productDAO;
    global $productExt;

    //Productcat
    global $productCat;
    global $productCatDAO;


    global $productUnitDAO;
    global $productUnitExt;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $existArr;

    global $today;

    $catid = filter_input(INPUT_POST, "catid_hide");
    $productCat = $productCatDAO->load($catid);

    $parent = filter_input(INPUT_POST, "opticproductcatid");
    $catname = filter_input(INPUT_POST, "name");
    $description = filter_input(INPUT_POST, "description");

    $productCat->productCatName = $catname;
    $productCat->productCatDescription = $description;
    $productCat->productCatParent = $parent;
    $productCat->productCatDate = $today;
    $productCat->userId = $_SESSION['userid'];
    $productCat->conditions = 0;
    $productCat->isOptic = 2;

    $productCatDAO->update($productCat);

    //get old ids
    $oldProductIds = array();
    $newProductIds = array();
    $productData = $productDAO->queryByProductCatId($productCat->productCatId);

    foreach ($productData as $value) {
        array_push($oldProductIds, $value->productId);
    }

    //from here it work like addOpticProductWithOutSizeColor()
    $limitamount = filter_input(INPUT_POST, "limitamount");
    $productBuyPrice = filter_input(INPUT_POST, "productBuyPrice");
    $productSellAllPrice = filter_input(INPUT_POST, "productSellAllPrice");
    $productSellHalfPrice = filter_input(INPUT_POST, "productSellHalfPrice");
    $productSellUnitPrice = filter_input(INPUT_POST, "productSellUnitPrice");

    $sizecoloritr = filter_input(INPUT_POST, "sizecoloritr");
    for ($i = 0; $i < $sizecoloritr; $i++) {
        $productid = filter_input(INPUT_POST, "product_hideid" . $i);
        if (isset($productid) && !empty($productid)) {
            $product = $productDAO->load($productid);
        }
        $oldproductunitIds = filter_input(INPUT_POST, "productunit_hideids" . $i);

        $productName = filter_input(INPUT_POST, "sizecolorname" . $i);
        $parcode = filter_input(INPUT_POST, "parcode" . $i);
        $productquantity = filter_input(INPUT_POST, "quantity" . $i);
        $comment = filter_input(INPUT_POST, "comment" . $i);
        ###################################################################
        ##prcode if not empty check and use it ==> as checkbarcode must be used before insert if user write his own parcode
        if (!empty($parcode)) {
            $parcode = addPreDigitsToNum($parcode);
            ##check for barcode
            $flag = checkbarcode2($parcode);
            if ($flag == 1) {
                //parcode is repeated get another one
                $parcode = generateParcode();
            }
            removeParcodeFromTable($parcode);
        } else {
            //will do it after insert use parcode from pro id comming now
        }
        ###################################################################

        $product->productName = $productName;
        $product->productDescription = $comment;
        $product->productCatId = $catid;
        $product->productBuyPrice = $productBuyPrice;
        $product->productSellAllPrice = $productSellAllPrice;
        $product->productSellHalfPrice = $productSellHalfPrice;
        $product->productSellUnitPrice = $productSellUnitPrice;
        $product->limitamount = $limitamount;
        $product->parcode = $parcode;

        if (isset($productid) && !empty($productid)) {
            //$product->dailyentryId = $product->dailyentryId;....
        } else {
            $product->dailyentryId = 0;
            $product->type = 0;
            $product->sellingtype = 0;
            $product->expireDate = NULL;
            $product->isService = 0;
        }

        $product->inMenu = $inMenu;
        $product->isOptic = 2;


        $product->conditions = 0;
        $product->productDate = date('Y-m-d');
        $product->userId = $_SESSION['userid'];

        if (isset($productName) && $productName != "") {
            if (isset($productid) && !empty($productid)) {
                unset($arr[array_search($productid, $oldProductIds)]);
                $productDAO->update($product);
            } else {
                $productid = $productDAO->insert($product);
                ################################################################
                ##this is prcode if empty
                if (empty($parcode)) {
                    $parcode = addPreDigitsToNum($productid);

                    ##check for barcode
                    $flag = checkbarcode2($parcode);
                    if ($flag == 1) {
                        //parcode is repeated get another one
                        $parcode = generateParcode();
                    }
                    removeParcodeFromTable($parcode);
                    $product->parcode = $parcode;
                    $productDAO->update($product);
                }
                ##############################################################
                addOpticProductStoredata($productid, $productquantity);

                //////////////////////////Imsert in daily entry
                $dailyEntry->dDateTime = date('Y-m-d H:i:s');
                $dailyEntry->entryComment = 'إضافة منتج بصريات ' . $productName . ' الكمية ' . $productquantity;

                $dailyEntryDebtorArray = array();
                $dailyEntryCreditorArray = array();

                $dailyEntryDebtor->accountstreeid = 382;
                $dailyEntryDebtor->value = $productBuyPrice * $productquantity;

                $dailyEntryCreditor->accountstreeid = 121;
                $dailyEntryCreditor->value = $productBuyPrice * $productquantity;

                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);

                $did = $returnedData[1];

                $rowData = $productDAO->load($productid);
                $rowData->dailyentryId = $did;
                $productDAO->update($rowData);
            }


            if (!empty($productid)) {
                editOpticProductUnit($productid, $oldproductunitIds);
            }
        }

        array_push($newProductIds, $productid);
    }


    $productData = $productExt->queryByProductCatIdWithCount($productCat->productCatId);
    //3-get units
    $productUnitIdsToDel = array();
    if ($productData[0]->productId > 0) {
        $productUnitsData = $productUnitDAO->queryByProductid($productData[0]->productId);
        foreach ($productUnitsData as $data) {
            foreach ($productData as $value) {
                $tempData = $productUnitExt->queryWithProductIdAndUnitIdSimple($value->productId, $data->unitid);
                foreach ($tempData as $finally) {
                    if (!in_array($finally->productunitid, $existArr)) {
                        array_push($productUnitIdsToDel, $finally->productunitid);
                    }
                }
            }
        }
    }

    //now delete other units
    foreach ($productUnitIdsToDel as $value) {
        $productUnitDAO->delete($value);
    }


    //this will returns the values in $oldProductIds that are not present in $newProductIds, it will not return the values in $newProductIds that are not in $oldProductIds.
    $productsToDel = array_diff($oldProductIds, $newProductIds);
    //now delete other products
    foreach ($productsToDel as $value) {
        //$productDAO->delete($value);
        $productData = $productDAO->load($value);
        $rid = reverseEntryWithItsID($productData->dailyentryId);
        $productData->conditions = 1;
        $productData->dailyentryId = $rid[1];
        $productDAO->update($productData);
    }
}

function editOpticProductUnit($productId, $oldproductunitIds)
{
    //Opticproductunit
    global $productUnit;
    global $productUnitDAO;
    global $productUnitExt;
    global $existArr;
    global $today;

    ##$oldproductunitIds not used but i may need it later
    //$oldproductunitIdsArr = explode(",", $oldproductunitIds);
    $Unitdone = 0;
    $unitsitr = filter_input(INPUT_POST, "unitsitr");

    for ($i = 0; $i < $unitsitr; $i++) {
        $productUnit = new Productunit;
        $productUnitid = filter_input(INPUT_POST, "productUnit_hideid" . $i);
        $productUnitidArr = explode(",", $productUnitid);
        $idsToUpdate = '';
        foreach ($productUnitidArr as $value) {
            $value = explode("-", $value);
            if ($value[1] == $productId) {
                $idsToUpdate .= $value[0] . ",";
                array_push($existArr, $value[0]);
            }
        }
        $unitid = filter_input(INPUT_POST, "unitid" . $i);
        $productnumber = filter_input(INPUT_POST, "unitno" . $i);

        if (!empty($unitid) && $unitid != '-1' && !empty($productnumber)) {
            //insert into productunit tbl
            $productUnit->conditions = 0;
            $productUnit->productid = $productId;
            $productUnit->productnumber = $productnumber;
            $productUnit->productunitdate = $today;
            $productUnit->unitid = $unitid;
            $productUnit->userid = $_SESSION['userid'];

            if (isset($idsToUpdate) && !empty($idsToUpdate)) {
                $idsToUpdate = rtrim($idsToUpdate, ",");
                $productUnit->productunitid = $idsToUpdate;
                //$productUnitDAO->update($productUnit);
                $productUnitExt->updateEX($productUnit);
            } else {
                $id = $productUnitDAO->insert($productUnit);
                array_push($existArr, $id);
            }

            $Unitdone = 1;
        }
    }


    if ($Unitdone == 0) {

        $productUnit->conditions = 0;
        $productUnit->productid = $productId;
        $productUnit->productnumber = 1;
        $productUnit->productunitdate = $today;
        $productUnit->unitid = 1;
        $productUnit->userid = $_SESSION['userid'];

        $productUnitDAO->insert($productUnit);
    }
}

function addOpticProductStoredata($productId, $productquantity)
{
    global $storeDetail;
    global $storeDetailDAO;

    global $storeReport;
    global $storeReportDAO;
    global $today;
    //insert into storedetail tbl
    $storeDetail->productid = $productId;
    $storeDetail->productquantity = $productquantity;
    $storeDetail->storedetaildate = $today;
    $storeDetail->storeid = 1;
    $storeDetail->userid = $_SESSION['userid'];

    $storeDetailDAO->insert($storeDetail);

    //insert into storereport tbl
    $storeReport->processname = "إضافة منتج";
    $storeReport->productafter = $productquantity;
    $storeReport->productbefore = 0;
    $storeReport->productquantity = $productquantity;
    $storeReport->storeid = 1;
    $storeReport->storereportdate = $today;
    $storeReport->storereportmodelid = $productId;
    $storeReport->storereporttype = 0;
    $storeReport->tablename = "productController.php/addoptic";
    $storeReport->userid = $_SESSION['userid'];
    $storeReport->productid = $productId;

    $storeReportDAO->insert($storeReport);
}

function getAllSubCatKeyVal($catid, $mode)
{
    global $productCatExt;
    global $productCatDAO;
    global $catsIDS;
    global $lastLevelCatIDS;
    //mode = 1 get all sub cats
    //mode = 2 get last level cats

    $result = $productCatExt->queryByParentExt2($catid);
    if (count($result) > 0) {
        foreach ($result as $data) {
            if ($mode == 1) {
                $catsIDS .= "," . $data->productCatId;
                getAllSubCatKeyVal($data->productCatId, $mode);
            } elseif ($mode == 2) {
                $childData = $productCatExt->queryByParentExt2($data->productCatId);
                if (count($childData) > 0) {
                    getAllSubCatKeyVal($data->productCatId, $mode);
                } else {
                    if (!empty($data->productCatId)) {
                        $lastLevelCatIDS[$data->productCatId] = $data->productCatName;
                    }
                }
            }
        }
    } else {
        //        if ($mode == 2) {
        //            $childData = $productCatExt->queryByParentExt2($data->productCatId);
        //            if (count($childData) > 0) {
        //                getAllSubCatKeyVal($data->productCatId, $mode);
        //            } else {
        //                if (!empty($data->productCatId)) {
        //                    $lastLevelCatIDS[$data->productCatId] = $data->productCatName;
        //                }
        //            }
        //        }
    }
}

function fetch_recursive($parentid, $categories)
{
    global $myProductcatEx;
    //print($parentid."<br>");
    $catData = $myProductcatEx->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        //if($newParentId != 0 && isset($newParentId))
        {
            //$newParentName = $catData->parentName;
            //$categories .= $newParentName.'/';
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

function deleteFinaly($productId)
{
    global $productDAO;
    global $productExt;

    ###############################
    $erpDB = $_POST["erpDB"];
    $sessionDBName = ConnectionProperty::getDatabase();
    if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
        $sessionDBName = $_SESSION['dbname'];
    }
    //choose erpDB user has choosen in obygy_app
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = 1; //tempppppppppppppppp
    }
    #################################
    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($productId)) {
            $productId = $_GET['id'];
        }

        $productData = $productDAO->load($productId);
        $rid = reverseEntryWithItsID($productData->dailyentryId, 1);
        $productData->conditions = 2;
        $productData->dailyentryId = $rid[1];
        $productDAO->update($productData);
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

//# by tarek , update menu order .

function updatemenuorder()
{

    //to use the variable out side the funcion
    global $Menuurl;
    global $MenuurlDAO;
    global $MenuurlEX;

    //post variable
    $menuurlid = $_POST['menuurlid'];
    $orderno = $_POST['orderno'];

    $oldData = $MenuurlDAO->load($menuurlid);
    $Menuurl->menuurl = $oldData->menuurl;
    $Menuurl->urlimage = $oldData->urlimage;
    $Menuurl->urltitle = $oldData->urltitle;
    $Menuurl->usergroupid = $oldData->usergroupid;

    $Menuurl->orderno = $orderno;
    $Menuurl->menuurlid = $menuurlid;

    $MenuurlDAO->update($Menuurl);
}

function updatemenugroups()
{

    //to use the variable out side the funcion
    global $Menuurl;
    global $MenuurlDAO;
    global $MenuurlEX;

    //post variable
    $menuurlid = $_POST['menuurlid'];
    $usergroupname = $_POST['groups'];
    $finalname = "-1,";
    foreach ($usergroupname as $myname) {
        $finalname = $finalname . $myname . ",";
    }
    $finalname = substr($finalname, 0, -1);


    $oldData = $MenuurlDAO->load($menuurlid);
    $oldData->usergroupid = $finalname;
    $MenuurlDAO->update($oldData);
}

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;
}

function useSpecializedParcodeDigits($parcode, $productId, $specializedParcodeDigits)
{
    $preDigits = '';
    if (strlen($productId) != $specializedParcodeDigits) {
        $noDigitsLeft = $specializedParcodeDigits - strlen($productId);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    $newParcode = 'i' . $preDigits . $productId;
    return $newParcode;
}

//this way save image ratio of width ,height
function reduceImageSize($imageName)
{
    global $hosturl_f;

    //    $fn = $_FILES['logo' . $i]['tmp_name'];
    //    $size = getimagesize($fn);
    //    $newDim = getNewWidthHeightAfterReduce($size[0], $size[1]);
    //    $width = $newDim[0];
    //    $height = $newDim[1];

    $statusMsg = '';
    if (!empty($imageName) && $imageName != "." && $imageName != "no image") {
        ####get product image
        // File upload path
        $targetFilePath = "../views/default/images/product_image/" . $imageName;
        list($width, $height, $type, $attr) = getimagesize($targetFilePath);

        $originalWidth = $width;
        $originalHeight = $height;
        $newDim = getNewWidthHeightAfterReduce($width, $height);
        $width = $newDim[0];
        $height = $newDim[1];

        //        $theImageURL = $hosturl_f . "/views/default/images/product_image/$imageName";//dont work for linux? not sure some times it works sometimes no
        $theImageURL = "../views/default/images/product_image/$imageName"; //this one is more guaranteed
        $src = imagecreatefromstring(file_get_contents($theImageURL));
        $dst = imagecreatetruecolor($width, $height);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
        imagedestroy($src);
        imagepng($dst, $targetFilePath); // adjust format as needed
        imagedestroy($dst);
    }
}

function getNewWidthHeightAfterReduce($width, $height)
{
    $ratio = $width / $height; // width/height

    if ($ratio > 1) {
        $width = 500;
        $height = 500 / $ratio;
    } else {
        $width = 500 * $ratio;
        $height = 500;
    }
    return array($width, $height);
}

function getImageDesc($productId)
{
    global $productDAO;
    $alldata = $productDAO->load($productId);
    echo json_encode($alldata);
}

function showallajaxproducts()
{
    global $productExt;
    global $userDAO;

    $sIndexColumn = "product.productId";

    /* DB table to use */
    //stable what is after from in sql statment
    ##this was right statment but slow
    $sTable = " product
                    LEFT JOIN storedetail ON product.productId = storedetail.productid
                    LEFT JOIN productcat ON product.productCatId = productcat.productCatId";

    $aColumns = array(
        'product.productId',
        'product.productName',
        'product.productCatId',
        'product.logo',
        'product.logo1',
        'product.logo2',
        'product.logo3',
        'product.logo4',
        'product.logo5',
        'product.logo6',
        'product.logo7',
        'storedetail.productquantity',
        'product.productDescription',
        'product.online',
        'productcat.productCatName'
    );

    // Indexed column (used for fast and accurate table cardinality)

    $sC = array(
        'product.productName',
        'product.logo',
        'product.logo1',
        'product.logo2',
        'product.logo3',
        'product.logo4',
        'product.logo5',
        'product.logo6',
        'product.logo7',
        'storedetail.productquantity',
        'product.productDescription',
        'productcat.productCatName',
        'product.online',
        'product.username'
    );

    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
            intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'] - 1; //this - 1 is because first column is not counted as it is checkbox
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
                  " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "product.productId") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }

    //    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }
    $store = $_REQUEST['store'];
    $level = filter_input(INPUT_POST, 'level');
    $productCatId = filter_input(INPUT_POST, 'productCatId' . $level);
    if (empty($productCatId) || $productCatId == -1) {
        $productCatId = filter_input(INPUT_POST, 'productCatId' . ($level - 1));
    }

    $queryString .= ' product.conditions = 0 AND product.reviewType  = 1 AND'; ///
    //
    if (isset($store) && $store != "-1" && $store != "-2") {
        $queryString .= ' storedetail.storeid = ' . $store . ' AND';
    }
    if (isset($productCatId) && $productCatId != "-1") {
        $queryString .= ' product.productCatId in( ' . $productCatId . ') AND';
    }
    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //        print("<br>queryString: ".$queryString."<br>");
    }

    $sWhere .= $queryString;

    //        //----------------------------------------------------------------------

    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
    //        echo $sQuery;
    $rResult = $productExt->runSelectQuery($sQuery);
    //var_dump($rResult);
    /* Data set length after filtering */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as productId  FROM  $sTable $sWhere "; //$sOrder
    $rResultFilterTotal = $productExt->runSelectQuery($sQuery);
    foreach ($rResultFilterTotal as $oneis) {
        $countis = $oneis->productId;
    }
    $iFilteredTotal = $countis;
    /* Total data set length */
    $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as productId FROM  $sTable";
    $rResultTotal = $productExt->runSelectQuery($sQuery);


    foreach ($rResultTotal as $oneis) {
        $countit = $oneis->productId;
    }
    $iTotal = $countit;
    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    foreach ($rResult as $aRow) {

        $userData = $userDAO->load($_SESSION['userid']); //
        $aRow->username = $userData->username;
        $row = array();
        for ($i = 0; $i < count($sC); $i++) {
            switch ($sC[$i]) {
                case "product.productName":
                    $row[] = $aRow->productName . "/" . $aRow->productCatName;
                    break;
                case "product.logo":
                    $row[] = '<img src="../views/default/images/product_image/' . $aRow->logo . ' "  class="file-img img-thumbnail"/>';
                    break;
                case "product.logo1":
                    $row[] = '<div>' . '<img src="../views/default/images/product_image/' . $aRow->logo1 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo2 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo3 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo4 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo5 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo6 . '"  class="file-img img-thumbnail"/>'
                        . '<img src="../views/default/images/product_image/' . $aRow->logo7 . '"  class="file-img img-thumbnail"/>' . '</div>';
                    break;
                case "product.productDescription":
                    $row[] = $aRow->productDescription;
                    break;
                case "product.online":
                    $row[] = $aRow->online;
                    break;
                case "storedetail.productquantity":
                    $row[] = $aRow->productquantity;
                    break;

                case "product.username":
                    $row[] = $aRow->username;
                    break;
            }
        }
        $output['data'][] = $row;
        $rowno++;
    }
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

function UpdateCatDescription()
{
    global $productCatDAO;

    $productCatId = $_POST['pro_id'];
    $type = $_POST['type'];
    $value = $_POST['value'];

    if (empty($productCatId) || empty($type)) {
        return false;
    }
    $rowData = $productCatDAO->load($productCatId);
    switch ($type) {
        case 'productCatDescription':
            $rowData->productCatDescription = $value;
            $productCatDAO->update($rowData);
            break;
    }
}

function addPreDigitsToNum2($num, $length = 2)
{
    global $Programsettingdata;

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

function CURL_eBill($data_arr, $url, $method = 'GET')
{
    $post = $data_arr;
    $token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJldGEtYnJva2VyIiwiYXVkIjoiZXRhLWJyb2tlciIsImp0aSI6IkpXVG4xblZIeVUiLCJpYXQiOjE2NTU1NDIwNjMuODkyMX0.M6MZ1qojF5GqFYb-7CA3DBA90Th9hCFv3VCC9WwdpvU";
    // header('Content-Type: application/json'); // Specify the type of data
    $ch = curl_init($url);
    //header
    $authorization = "Authorization: Bearer $token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', $authorization)); // Inject the token into the


    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);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    return $response;
}

function getClients()
{
    global $clientEX;
    global $userDAO;
    $userData = $userDAO->load($_SESSION['userid']);
    $queryString = '';
    if ($userData->viewclients == 0) {
        $queryString .= ' AND client.userid =' . $_SESSION['userid'];
    }
    $clientsData = $clientEX->queryByCondition($queryString);
    return $clientsData;
}

function priceDiffDailyEntry($productId, $productBuyPrice)
{ //$productBuyPrice is the new buy price
    $storeDetail = R::getAll('select productquantity,store.storeId,store.treeId
                        from storedetail
                        join store on store.storeId =storedetail.storeid
                        where productid = ' . $productId);
    $proData = R::getRow('select productName,productBuyPrice from product where productId = ' . $productId);
    foreach ($storeDetail as $sdata) {
        #calc
        $priceDiff = ($productBuyPrice - $proData['productBuyPrice']) * $sdata['productquantity']; //quantity might be -ve too

        $dailyEntry->entryComment = "تعديل منتج (" . $proData['productName'] . ") السعر من (" . $proData['productBuyPrice'] . ") الى ($productBuyPrice) و الكميه (" . (float) $sdata['productquantity'] . ")";

        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = abs($priceDiff);
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = abs($priceDiff);
        if ($priceDiff > 0) { //price increased
            //من المخزن
            $dailyEntryDebtor->accountstreeid = $sdata['treeId'];
            //فروقات اعاده تقييم بضاعه
            $dailyEntryCreditor->accountstreeid = 53;
        } elseif ($priceDiff < 0) { //price decreased
            //فروقات اعاده تقييم بضاعه
            $dailyEntryDebtor->accountstreeid = 53;
            //الى المخزن
            $dailyEntryCreditor->accountstreeid = $sdata['treeId'];
        }
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $productId, "productController.php?do=edit&id=$productId");
        //                        $did = $returnedData[1];
        //                        return $did;
    }
}
