<?php

session_start();
ob_start();
//the global file operation
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("addOneSimpleReturn", "addsizeColorToProductAjax", "editAjax");
if (!in_array($do, $ajaxDoArr)) {
    include("../public/impOpreation.php");
}
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

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

include_once("dailyentryfun.php");

//here the db files that include in the file
include("../public/include_dao.php");
include("../library/uploadImages.php");
include '../library/Classes/PHPExcel/IOFactory.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');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');
//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');

//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.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');
//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');


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

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//
require_once('../models/dao/ProductingredientsDAO.class.php');
require_once('../models/dto/Productingredient.class.php');
require_once('../models/mysql/ProductingredientsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductingredientsMySqlExtDAO.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');
//
require_once('../models/dao/SizecolorstoredetailDAO.class.php');
require_once('../models/dto/Sizecolorstoredetail.class.php');
require_once('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.class.php');
//Storemovement
require_once('../models/dao/StoremovementDAO.class.php');
require_once('../models/dto/Storemovement.class.php');
require_once('../models/mysql/StoremovementMySqlDAO.class.php');
require_once('../models/mysql/ext/StoremovementMySqlExtDAO.class.php');
//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');
//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');
//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');
//get the do the action
$do = $_GET['do'];

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

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

  Controller Name :- productController

  OPERTATION in Controller

  1- display add form, add product cat and product with ajax
  2- add in product tbl
  2.1- insert into product unit tbl
  2.2- insert into storedetail tbl
  2.3- insert new row into storereport tbl
  3- display show and tempdelete
  4- edit product
  5- update product
  5.1- update product tbl with productId
  5.2- delete product units associated to this product from productunit tbl, then insert it again
  6- تقرير الأصناف وسعر الشراء
  ======================== */

//here the global
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("header.html");
}
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//here goes the instances and general variables
//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = 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();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Productunit
$productUnit = new Productunit();
$productUnitDAO = new ProductunitMySqlDAO();
$productUnitExt = new ProductunitMySqlExtDAO();
//progsetting
$Programsettings = new Programsetting();
$ProgramsettingsDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingsExt = new ProgramsettingsMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();


$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();
//Sellbilldetail
$Sellbilldetail = new Sellbilldetail();
$SellbilldetailDAO = new SellbilldetailMySqlDAO();
$SellbilldetailEX = new SellbilldetailMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

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

//Productingredient
$productIngredients = new Productingredient();
$productIngredientsDAO = new ProductingredientsMySqlDAO();
$productIngredientsEX = new ProductingredientsMySqlExtDAO();

//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Storemovement
$Storemovement = new Storemovement();
$StoremovementDAO = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();
//Returnsellbilldetail
$myReturnsellbilldetail = new Returnsellbilldetail();
$myReturnsellbilldetailRecord = new ReturnsellbilldetailMySqlDAO();
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();
//Productserial
$Productserial = $myProductserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = $myProductserialEx = new ProductserialMySqlExtDAO();

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


//User
$userDAO = new UserMySqlDAO();

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

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
$noOfDecimalPlaces = 2; //($Programsettingdata->roundnumbers == 0) ? 0 : (int) $Programsettingdata->noOfDecimalPlaces;

$smarty->assign("today", $today);

//make sure parcode file is created
$dbname = ConnectionProperty::getDatabase();
if (isset($_SESSION['dbname']) && !empty($_SESSION['dbname'])) {
    $dbname = $_SESSION['dbname'];
}

avalableParcodes();

/////////////////////////////

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

//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    unset($_SESSION["productserialArray"]);

    $generatedParcode = generateParcode();
    $smarty->assign("generatedParcode", $generatedParcode);


    $vehicletypes = R::findAll('vehicletypes', 'del < 2');
    $smarty->assign('vehicletypes', $vehicletypes);

    $companyproduces = R::findAll('companyproduces', 'del < 2');
    $smarty->assign('companyproduces', $companyproduces);

    //get product categories
    $allParents = getProductCatParents();
    $smarty->assign("allParents", $allParents);

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

    //    // here the function that do the action
    //    $outputString = display_children(0, 0);  //display the tree
    //    $smarty->assign("treeHTML", $outputString);
    // $smarty->assign("productScripts", 1);

    $smarty->assign("customProductCat", 1);

    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    //here the smarty templates
    $smarty->display("productview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    try {

        $don = add();
        $productIndexType = $_POST['productindextype'];

        if ($productIndexType == '0') {
            $url = "productController.php";
        } else {
            $url = "productController.php?do=show";
        }
        $smarty->assign('urldirect', $url);
        if ($don == 1) {
            $note = "تمت العملية بنجاح";
        } elseif ($don == 0) {
            $note = "لم تقوم باضافه وحده قياس  فتم اختيار وحده القياس  الرئيسيه";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        $url = "productController.php";
        $smarty->assign('urldirect', $url);
        $note = "حدث خطأ ... يرجى المحاولة مرة أخرى";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "addOneSimpleReturn") { //only one product added and productid is needed
    try {
        $id = add();
        echo $id;
    } catch (Exception $e) {
        echo -1;
    }
} elseif ($do == "addsizeColorToProductAjax") { //so we can add single sizeColor to existing product
    try {
        $productId = (int) $_POST["productId"];
        //        $productBuyPrice = (float) $_POST["productBuyPrice"];
        //        $productSellUnitPrice = (float) $_POST["productSellUnitPrice"];
        //make sure its sizecolor product
        $productExt->updatehasSizeColor(1, $productId);
        $product = $productDAO->load($productId);
        if ($product->hasSizeAndColor == 1) { //منتج بمقاسات و الوان
            addProductSizeAndColor($productId, $product->productBuyPrice, $product->productSellUnitPrice);
        }
        echo $id;
    } catch (Exception $e) {
        echo -1;
    }
} elseif ($do == "repeat") {

    $allproduct = $productExt->getProductsCount();
    $allproductdata = $productExt->queryAllrepateparcode($allproduct->productId);
    $smarty->assign("allproductdata", $allproductdata);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $productnumber = $_POST["productnumber"];
    if (isset($productnumber) && $productnumber > 0) {
        $productsData = $productExt->queryAllrepateparcode($productnumber);
    }
    $smarty->assign("productsData", $productsData);
    $smarty->display("productview/repeat.html");
} elseif ($do == "deleted") {

    /*
      $productnumber = $_POST["productnumber"];
      $productId = $_POST["productId"];

      if (isset($productId) && $productId !=  '-1') {
      $productsData = $productExt->queryAlldeletedproductwithid($productId);
      }
      if (isset($productnumber) && $productnumber >= 0) {
      $productsData = $productExt->queryAlldeletedproduct($productnumber);
      }
      elseif(empty($productnumber)){
      $productnumber = 0;
      $productsData = $productExt->queryAlldeletedproduct(0);
      }

      // $allproduct = count($productDAO->queryAll());
      $allproductdata = $productDAO->queryByConditions(1);
      $smarty->assign("allproductdata", $allproductdata);
     */
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $alldata = getProductCatsForShow();
    $smarty->assign("alldata", $alldata);
    // $smarty->assign("settlementstoreshow", 1);
    //$smarty->assign("productsData", $productsData);
    $smarty->display("productview/deleted.html");
} elseif ($do == "show") {
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    include_once("../public/authentication.php");

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    /* $alldata = getProductCatsForShow();
      $smarty->assign("alldata", $alldata); */

    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    $productCatId0 = filter_input(INPUT_POST, 'productCatId0');
    $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));
    }
    $smarty->assign('productCatId', $productCatId);
    ##choose a product
    $productId = filter_input(INPUT_POST, 'product');
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    } else {
        $productId = (int) $productId;
    }


    ##start searching ...
    if (isset($productId) && $productId > 0) {
        $myproduct = $productDAO->load($productId);
        $productCatId = $myproduct->productCatId;
        $message = "عرض منتج :" . $myproduct->productName;
        $smarty->assign('message', $message);

        ##get subcat of cat
        $catsIDS = '' . $productCatId;
        $productsData = $productExt->queryByProductCatIdInExt($catsIDS, '', " and product.productId = $myproduct->productId ");

        $editCat = filter_input(INPUT_POST, 'editCat');
        $smarty->assign('editCat', $editCat);

        $showQuantity = filter_input(INPUT_POST, 'showQuantity');
        $smarty->assign('showQuantity', $showQuantity);

        foreach ($productsData as $data) {
            if ($showQuantity == 1) {
                if ($data->isOptic == 2) {
                    ##currentQuantity
                    $productWithColor = $productExt->queryByProductCatIdWithCount($data->productId);
                    $data->productDataSOC = json_encode($productWithColor);
                    $data->productDataSAC = '[]';
                    $data->productDataING = '[]';
                    $data->currentQuantity = 0;
                    foreach ($productWithColor as $sizeColor) {
                        $data->currentQuantity += $sizeColor->sumProductQuantity;
                    }
                    ##price
                    if ($data->isOptic == 2) {
                        $prices = $productExt->getPriceOfOptic($data->productId); // $data->productId ==== product.productCatId when isoptic = 2
                        $data->productBuyPrice = $prices->productBuyPrice;
                        $data->productSellAllPrice = $prices->productSellAllPrice;
                        $data->productSellHalfPrice = $prices->productSellHalfPrice;
                        $data->productSellUnitPrice = $prices->productSellUnitPrice;
                    }
                } elseif ($data->hasSizeAndColor == 1) {
                    $sizeColorStoreDetail = $sizeColorStoreDetailEX->getSumProductQuantityInAllStores($data->productId);
                    $data->productDataSAC = json_encode($sizeColorStoreDetail);
                    $data->productDataSOC = '';
                    $data->productDataING = '[]';
                    $data->productData = '';
                    ##currentQuantity
                    $details = $productExt->getProductQuantity($data->productId, '');
                    $data->currentQuantity = (float) $details->sumProductQuantity;
                } else {
                    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($data->productId);
                    $data->productDataING = json_encode($ingridients);
                    $data->productDataSAC = '[]';
                    $data->productDataSOC = '';
                    $data->productData = '';
                    ##currentQuantity
                    $details = $productExt->getProductQuantity($data->productId, '');
                    $data->currentQuantity = (float) $details->sumProductQuantity;
                }
            }
            if ($editCat != 1) {
                $cat = $productCatDAO->load($data->productCatId);
                $data->productCatName = $cat->productCatName;
            }
        }
        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);


        $alldata = getProductCats($productCatId);
        $smarty->assign("alldata", $alldata);


        $smarty->assign('productsData', $productsData);
    } elseif (isset($productCatId) && $productCatId != "-1" && $productCatId != "0") {
        $mycatdata = $productCatDAO->load($productCatId);
        $message = "عرض المنتجات للتصنيف:" . $mycatdata->productCatName;
        $smarty->assign('message', $message);

        ##get subcat of cat
        $catsIDS = '' . $productCatId;
        getAllSubCat($productCatId, 1); //mode = 1 get all sub cats
        //        $productsData = $productExt->queryByProductCatIdInExt($catsIDS);
        ## get results
        $productsDataFromProducts = R::getAll('SELECT product.productId,product.productName,product.isOptic,product.hasSizeAndColor,product.conditions,product.productCatId
                , product.productBuyPrice,product.productSellAllPrice,product.productSellHalfPrice,product.productSellUnitPrice,product.price4,product.price5,product.price6,product.price7,product.price8 , product.logo , product.productDescription,
                product.parcode,product.logo1,product.logo2,product.logo3,product.logo4,product.logo5,product.logo6,product.logo7,product.reviewType,product.online,product.updatebyuser
                FROM product where product.conditions = 0 and product.isOptic != 2 and product.productCatId in(' . $catsIDS . ')'); //$queryString
        $productsDataFromCats = R::getAll('SELECT product.productCatId as productId,product.productCatName as productName ,product.isOptic,0 as hasSizeAndColor,product.conditions,product.productCatParent as productCatId
                ,-1 as productBuyPrice ,-1 as productSellAllPrice,-1 as productSellHalfPrice,-1 as productSellUnitPrice , product.logo,product.productCatDescription as productDescription
                ,product.opticServices,-1 as logo1 ,-1 as logo2 ,-1 as logo3 ,-1 as logo4 ,-1 as logo5,-1 as logo6,-1 as logo7 ,-1 as reviewType ,-1 as online,-1 as updatebyuser
                FROM productcat as product where product.conditions = 0 and product.isOptic = 2 and product.productCatId in(' . $catsIDS . ')'); //$queryString2
        list($productCatIdsArr, $productIdsFromProductsArr) = [[], []];
        foreach ($productsDataFromProducts as $value) {
            $productCatIdsArr[] = $value['productCatId'];
            $productIdsFromProductsArr[] = $value['productId'];
            $tempDataArr[] = $value;
        }
        list($productCatIdsOpticArr) = [[]];
        foreach ($productsDataFromCats as $value) {
            $productCatIdsOpticArr[] = $value['productId'];
            $tempDataArr[] = $value;
        }
        $productCatIdsOpticArr = !empty($productCatIdsOpticArr) ? array_unique($productCatIdsOpticArr) : [0];
        $productIdsFromProductsArr = !empty($productIdsFromProductsArr) ? array_unique($productIdsFromProductsArr) : [0];

        $storeDetailDataArrProducts = R::getAll('SELECT productid,sum(productquantity) as productquantity
                FROM storedetail
                where productid in(' . implode(',', $productIdsFromProductsArr) . ')  group by productid');
        $storeDetailDataArrProducts = customArrayIndexOne($storeDetailDataArrProducts, 'productid');
        unset($productsDataFromProducts, $productsDataFromCats, $productIdsFromProductsArr);
        $productsData = $tempDataArr;

        ## get catname
        $productCatIdsArr = !empty($productCatIdsArr) ? array_unique($productCatIdsArr) : [0];
        $productCatDataArr = R::getAll('select productCatId,productCatName from productcat where productCatId in(' . implode(',', $productCatIdsArr) . ')');
        $productCatDataArr = customArrayIndexOne($productCatDataArr, 'productCatId');

        $tempDataArr = array();
        list($productIdsHasSizeAndColorArr, $productIdsCollectiveArr) = [[]];
        foreach ($productsData as $value) {
            $value['productCatName'] = $productCatDataArr[$value['productCatId']]['productCatName'];
            $value['productquantity'] = (float) $storeDetailDataArrProducts[$value['productId']]['productquantity'];
            if ($value['hasSizeAndColor'] == 1)
                $productIdsHasSizeAndColorArr[] = $value['productId'];
            elseif ($value['isOptic'] != 2)
                $productIdsCollectiveArr[] = $value['productId'];


            $obj = new stdClass();
            foreach ($value as $key1 => $value1) {
                $obj->$key1 = $value1;
            }
            $tempDataArr[] = $obj;
            //$tempDataArr[] = $value;
        }
        $productsData = $tempDataArr;
        $productIdsHasSizeAndColorArr = !empty($productIdsHasSizeAndColorArr) ? array_unique($productIdsHasSizeAndColorArr) : [0];
        $productIdsCollectiveArr = !empty($productIdsCollectiveArr) ? array_unique($productIdsCollectiveArr) : [0];


        ##getting data of each product type "optic , collective ,sizecolor"
        #1- optic
        $opticDetails = R::getAll('SELECT product.*,storedetail.storeid,SUM(storedetail.productquantity) AS sumProductQuantity
                            FROM product
                            JOIN storedetail
                            ON storedetail.productid = product.productId WHERE productCatId in(' . implode(',', $productCatIdsOpticArr) . ')  and product.conditions = 0 group by storedetail.productid');
        $opticDetails = customArrayIndexMany($opticDetails, 'productCatId');
        $tempArr = array();
        foreach ($opticDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $opticDetails = $tempArr;
        #2- sizecolor
        $SCProductsDetails = R::getAll('SELECT productid,parcode,sum(quantity) as quantity,size.name as sizeName,color.name as colorName
                FROM sizecolorstoredetail
                left join sizecolor as size on size.id=sizecolorstoredetail.sizeid
                left join sizecolor as color on color.id=sizecolorstoredetail.colorid
                WHERE productid in(' . implode(',', $productIdsHasSizeAndColorArr) . ') group by productid,sizeid,colorid order by sizecolorstoredetail.id asc');
        $SCProductsDetails = customArrayIndexMany($SCProductsDetails, 'productid');
        $tempArr = array();
        foreach ($SCProductsDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $SCProductsDetails = $tempArr;
        #3- ingredients of collective pro
        $collectiveProductDetails = R::getAll('SELECT productingredients.* ,product.productName ,product.productBuyPrice , unit.unitName
                ,productBuyPrice,lastbuyprice,lastbuyprice_withDiscount,meanbuyprice,meanbuyprice_withDiscount
                ,productnumber
                FROM productingredients
                JOIN product
			 ON product.productId = productingredients.ingridientId
		JOIN productunit
			 ON  productunit.productunitid=productingredients.unitId
		JOIN unit
         	 ON unit.unitId= productunit.unitid
                WHERE productingredients.productId in(' . implode(',', $productIdsCollectiveArr) . ')');
        $collectiveProductDetails = customArrayIndexMany($collectiveProductDetails, 'productId');
        $tempArr = array();
        foreach ($collectiveProductDetails as $key => $value) {
            foreach ($value as $value1) {
                $obj = new stdClass();
                foreach ($value1 as $key2 => $value2) {
                    $obj->$key2 = $value2;
                }
                $tempArr[$key][] = $obj;
            }
        }
        $collectiveProductDetails = $tempArr;


        $editCat = filter_input(INPUT_POST, 'editCat');
        $smarty->assign('editCat', $editCat);

        $showQuantity = filter_input(INPUT_POST, 'showQuantity');
        $smarty->assign('showQuantity', $showQuantity);

        foreach ($productsData as $data) {
            if ($showQuantity == 1) {
                if ($data->isOptic == 2) {
                    ##currentQuantity
                    //                    $productWithColor = $productExt->queryByProductCatIdWithCount($data->productId);
                    $productWithColor = $opticDetails[$data->productId];
                    $data->productDataSOC = json_encode($productWithColor);
                    $data->productDataSAC = '[]';
                    $data->productDataING = '[]';
                    $data->currentQuantity = 0;
                    foreach ($productWithColor as $sizeColor) {
                        $data->currentQuantity += $sizeColor->sumProductQuantity;
                    }
                    ##price
                    if ($data->isOptic == 2) {
                        //$prices = $productExt->getPriceOfOptic($data->productId); // $data->productId ==== product.productCatId when isoptic = 2
                        $data->productBuyPrice = $productWithColor[0]->productBuyPrice; //$prices->productBuyPrice;
                        $data->productSellAllPrice = $productWithColor[0]->productSellAllPrice; //$prices->productBuyPrice;$prices->productSellAllPrice;
                        $data->productSellHalfPrice = $productWithColor[0]->productSellHalfPrice; //$prices->productBuyPrice;$prices->productSellHalfPrice;
                        $data->productSellUnitPrice = $productWithColor[0]->productSellUnitPrice; //$prices->productBuyPrice;$prices->productSellUnitPrice;
                    }
                } elseif ($data->hasSizeAndColor == 1) {
                    //                    $sizeColorStoreDetail = $sizeColorStoreDetailEX->getSumProductQuantityInAllStores($data->productId);
                    $sizeColorStoreDetail = $SCProductsDetails[$data->productId];
                    $data->productDataSAC = json_encode($sizeColorStoreDetail);
                    $data->productDataSOC = '';
                    $data->productDataING = '[]';
                    $data->productData = '';
                    ##currentQuantity
                    //$details = $productExt->getProductQuantity($data->productId, '');
                    //                    $data->currentQuantity = (float) $details->sumProductQuantity;
                    $data->currentQuantity = 0;
                    foreach ($sizeColorStoreDetail as $sizeColor) {
                        $data->currentQuantity += $sizeColor->quantity;
                    }
                } else {
                    //                    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($data->productId);
                    $ingridients = isset($collectiveProductDetails[$data->productId]) ? $collectiveProductDetails[$data->productId] : [];
                    $data->productDataING = json_encode($ingridients);
                    $data->productDataSAC = '[]';
                    $data->productDataSOC = '';
                    $data->productData = '';
                    ##currentQuantity
                    //                    $details = $productExt->getProductQuantity($data->productId, '');
                    //                    $data->currentQuantity = (float) $details->sumProductQuantity;
                    $data->currentQuantity = $data->productquantity;
                    //                    foreach ($ingridients as $row) {
                    //                        $data->currentQuantity += $row->quantity;
                    //                    }
                }
            }
            //            if ($editCat != 1) {
            //                $cat = $productCatDAO->load($data->productCatId);
            //                $data->productCatName = $cat->productCatName;
            //            }
        }
        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);


        $alldata = getProductCats($productCatId);
        $smarty->assign("alldata", $alldata);

        $smarty->assign('productsData', $productsData);
    } elseif ($productCatId0 == "-1") {
        show();
    }


    $smarty->assign("customCheck", 1);
    $smarty->assign('customUsergroup', 1);
    $smarty->assign("productScripts", 1);
    $smarty->display("productview/show.html");
} elseif ($do == "showNew") {
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    include_once("../public/authentication.php");

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    /* $alldata = getProductCatsForShow();
      $smarty->assign("alldata", $alldata); */

    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);


    $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));
    }
    $productId = filter_input(INPUT_POST, 'product');
    $isOptic = filter_input(INPUT_POST, 'proIsOptic');
    if (!isset($isOptic) || empty($isOptic)) {
        $isOptic = 0;
    }
    if ($isOptic == 2 && $searchtype == 1) {
        $productCatId = $productId;
    }
    $smarty->assign('productCatId', $productCatId);
    if (isset($productId) && !empty($productId) && $productId != -1) {
        $proData = $productDAO->load($productId);
        $message = "عرض منتج :" . $proData->productName;
        $smarty->assign('message', $message);
        if ($proData->isOptic == 2) {
            $prices = $productExt->getPriceOfOptic($proData->productCatId);

            $proData->productBuyPrice = $prices->productBuyPrice;
            $proData->productSellAllPrice = $prices->productSellAllPrice;
            $proData->productSellHalfPrice = $prices->productSellHalfPrice;
            $proData->productSellUnitPrice = $prices->productSellUnitPrice;
        }

        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);


        //        $alldata = getProductCats($productCatId);
        //        $smarty->assign("alldata", $alldata);

        $productsData[0] = $proData;
        $smarty->assign('productsData', $productsData);
    } else if (isset($productCatId) && $productCatId != "-1" && $productCatId != "0") {
        $mycatdata = $productCatDAO->load($productCatId);
        $message = "عرض المنتجات للتصنيف:" . $mycatdata->productCatName;
        $smarty->assign('message', $message);

        ##get subcat of cat
        $catsIDS = '' . $productCatId;
        getAllSubCat($productCatId, 1); //mode = 1 get all sub cats
        $productsData = $productExt->queryByProductCatIdInExt($catsIDS, '', ' and product.conditions = 0 ');


        foreach ($productsData as $data) {
            if ($data->isOptic == 2) {
                $prices = $productExt->getPriceOfOptic($data->productCatId);

                $data->productBuyPrice = $prices->productBuyPrice;
                $data->productSellAllPrice = $prices->productSellAllPrice;
                $data->productSellHalfPrice = $prices->productSellHalfPrice;
                $data->productSellUnitPrice = $prices->productSellUnitPrice;
            }
        }
        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);


        $alldata = getProductCats($productCatId);
        $smarty->assign("alldata", $alldata);


        $smarty->assign('productsData', $productsData);
    }
    //show();

    $smarty->assign("customCheck", 1);
    $smarty->assign('customUsergroup', 1);
    $smarty->assign("productScripts", 1);
    $smarty->display("productview/showNew.html");
} elseif ($do == "executeOperation") {
    try {
        executeOperation();

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


//azmy
elseif ($do == "showImage") {
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);
    include_once("../public/authentication.php");


    $allstores = $storeDAO->queryAll();
    $smarty->assign("allstores", $allstores);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);


    $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));
    }
    $productId = filter_input(INPUT_POST, 'product');
    $isOptic = filter_input(INPUT_POST, 'proIsOptic');
    $stoid = filter_input(INPUT_POST, 'store');

    if (!isset($isOptic) || empty($isOptic)) {
        $isOptic = 0;
    }
    if ($isOptic == 2 && $searchtype == 1) {
        $productCatId = $productId;
    }
    $smarty->assign('productCatId', $productCatId);
    $smarty->assign('productId', $productId);

    $chk = filter_input(INPUT_POST, 'image');
    $smarty->assign('chk', $chk);

    if (isset($productId) && !empty($productId) && $productId != -1) {
        if ($stoid == -1 || $stoid == -2) {
        } else {
            $querystore = 'and storedetail.storeid = ' . $stoid . '';
        }
        $proData = $productExt->loadByidandstoreid($productId, $querystore);
        $message = "عرض منتج :" . $proData->productName;
        $smarty->assign('message', $message);
        $proData->quan = $proData->productquantity;
        $userData = $userDAO->load($_SESSION['userid']); //
        $username = $userData->username;
        $proData->username = $userData->username;
        $smarty->assign('username', $username);

        if ($proData->isOptic == 2) {
            $prices = $productExt->getPriceOfOptic($proData->productCatId);
            $proData->logo = $prices->logo;
            $proData->productDescription = $prices->productDescription;
            $proData->quan = $proData->productquantity;
        }

        $mycatdata = $productCatDAO->load($proData->productCatId);
        $productCatDescription = $mycatdata->productCatDescription;
        $smarty->assign('productCatDescription', $productCatDescription);
        $smarty->assign('productCatId', $proData->productCatId);


        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);


        //        $alldata = getProductCats($productCatId);
        //        $smarty->assign("alldata", $alldata);

        $productsData[0] = $proData;
        $smarty->assign('productsData', $productsData);
    } else if (isset($productCatId) && $productCatId != "-1" && $productCatId != "0") {
        $mycatdata = $productCatDAO->load($productCatId);
        $message = "عرض المنتجات للتصنيف:" . $mycatdata->productCatName;
        $smarty->assign('message', $message);

        $productCatDescription = $mycatdata->productCatDescription;
        $smarty->assign('productCatDescription', $productCatDescription);
        $smarty->assign('productCatId', $mycatdata->productCatId);

        $userData = $userDAO->load($_SESSION['userid']); //
        $smarty->assign('username', $userData->username);

        if ($stoid == -1 || $stoid == -2) {
        } else {
            $querystore = 'and storedetail.storeid in( ' . $stoid . ')';
        }
        ##get subcat of cat
        $catsIDS = '' . $productCatId;
        getAllSubCat($productCatId, 1); //mode = 1 get all sub cats
        $productsData = $productExt->queryByProductCatIdInExt($catsIDS, $querystore, ' and product.conditions = 0 ');
        foreach ($productsData as $data) {
            $userData = $userDAO->load($_SESSION['userid']); //
            $data->username = $userData->username;
            if ($stoid == -1 || $stoid == -2) {
            } else {
                $querystore = 'and storedetail.storeid in( ' . $stoid . ')';
            }
            $storeDe = $storeDetailExt->getProductQuantityInAllStores($data->productId, $querystore);
            $data->productquantity = $storeDe;
            if ($data->isOptic == 2) {
                $prices = $productExt->getPriceOfOptic($data->productCatId);
                $data->logo = $prices->logo;
                $data->productDescription = $prices->productDescription;
                $data->productquantity = $storeDe;
            }
        }
        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']); //
        $smarty->assign("userGroupData", $userGroupData);

        $alldata = getProductCats($productCatId);
        $smarty->assign("alldata", $alldata);
        $smarty->assign('productsData', $productsData);
    }
    //show();

    $smarty->assign("customCheck", 1);
    $smarty->assign('customUsergroup', 1);
    $smarty->assign("productScripts", 1);
    $smarty->display("productview/showimage.html");
} elseif ($do == "executeOperation2") {
    try {
        executeOperation();

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

//azmy
elseif ($do == "returndelete") { //returndelete
    include_once("../public/authentication.php");

    try {
        $isOptic = (int) $_GET["optic"];
        if ($isOptic == 0 || $isOptic == 1) {
            returndelete();
        } elseif ($isOptic == 2) {
            $catId = (int) $_GET["id"];
            $cat = $productCatDAO->load($catId);
            $cat->conditions = 0;
            $productCatDAO->update($cat);
            $products = $productDAO->queryByProductCatId($catId);
            foreach ($products as $value) {
                $note = returndelete($value->productId);
            }
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    include_once("../public/authentication.php");
    try {
        $isOptic = (int) $_GET["optic"];
        if ($isOptic == 0 || $isOptic == 1) {
            $note = tempdelete();
        } elseif ($isOptic == 2) {
            $catId = (int) $_GET["id"];
            $cat = $productCatDAO->load($catId);
            $cat->conditions = 1;
            $productCatDAO->update($cat);
            $products = $productDAO->queryByProductCatId($catId);
            foreach ($products as $value) {
                $note = tempdelete($value->productId);
            }
        }

        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") { //edit  product
    include_once("../public/authentication.php");
    $productsData = edit();
    $smarty->assign("productsData", $productsData);

    if (count($productsData) > 0) {
        $productUnitsData = getProductUnits($productsData->productId);
        $smarty->assign("productUnitsData", $productUnitsData);
        $smarty->assign("countProductUnits", count($productUnitsData));
    }

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

    $alldata = getProductCats($productsData->productCatId);
    $smarty->assign("alldata", $alldata);
    $smarty->assign("customPrint", 1);
    $smarty->assign("productScripts", 1);
    $smarty->display("productview/editprint.html");
} elseif ($do == "edit" || $do == "editAjax") { //edit  product
    //include_once("../public/authentication.php");
    if ($do == "editAjax") {
        $productId = $_GET['id'];
        $sizeId = 0;
        $colorId = 0;
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
        }
        $_GET['id'] = $productId;
        //
        $lastSellNote = (int) $_GET['lastSellNote'];
        if ($lastSellNote == 1) {
            $lastSellDataOfProduct = $SellbilldetailEX->getLastSellDataOfProduct($productId, $sizeId, $colorId);
            if (isset($lastSellDataOfProduct)) {
                $smarty->assign("lastSellDataOfProduct", $lastSellDataOfProduct);
            }
            $lastBuyDataOfProduct = $buyBillDetailExt->getLastBuyDataOfProduct($productId, $sizeId, $colorId);
            if (isset($lastBuyDataOfProduct)) {
                if ($lastBuyDataOfProduct->discounttype == 0 && $lastBuyDataOfProduct->discountvalue > 0) { //old row cal discount percentage
                    $lastBuyDataOfProduct->discounttype = ($lastBuyDataOfProduct->discountvalue / ($lastBuyDataOfProduct->discountvalue + $lastBuyDataOfProduct->buybilldetailtotalprice)) * 100;
                    $lastBuyDataOfProduct->discounttype = round($lastBuyDataOfProduct->discounttype, 2);
                }
                $smarty->assign("lastBuyDataOfProduct", $lastBuyDataOfProduct);
            }
        }
    }
    $productsData = edit();
    $smarty->assign("productsData", $productsData);

    if (count($productsData) > 0) {
        $productUnitsData = getProductUnits($productsData->productId);
        $smarty->assign("productUnitsData", $productUnitsData);
        $smarty->assign("countProductUnits", count($productUnitsData));
    }


    $accountsTreeOrdered = array();
    getTreeAccounts(142, $productsData->treeId);

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

    $alldata = getProductCats($productsData->productCatId);
    $smarty->assign("alldata", $alldata);

    $vehicletypes = R::findAll('vehicletypes', 'del < 2');
    $smarty->assign('vehicletypes', $vehicletypes);

    $companyproduces = R::findAll('companyproduces', 'del < 2');
    $smarty->assign('companyproduces', $companyproduces);


    $productId = $_GET['id'];
    ifCollectiveGetData($productId);
    ifHasSizeANDColorGetData($productsData);
    $smarty->assign("productionRate", 1);
    $smarty->assign("productScripts", 1);


    $productsData->displayWidth = $productsData->displayHeight = 0;
    if (!empty($productsData->logo) && $productsData->logo != "." && $productsData->logo != "no image") {
        ####get product image
        // File upload path
        $targetFilePath = "../views/default/images/product_image/" . $productsData->logo;
        list($width, $height, $type, $attr) = getimagesize($targetFilePath);

        $productsData->displayWidth = $width / 3;
        $productsData->displayHeight = $height / 3;
    }
    if ($do == "editAjax") {
        $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);
        $smarty->assign("userGroupData", $userGroupData);

        $smarty->display("productview/details.html");
    } else {
        $smarty->display("productview/edit.html");
    }
} elseif ($do == "update") { //edit update
    //    var_dump(addParcodeToImage("logo", $_POST['oldlogo'], "../views/default/images/product_image/", "i000157"));
    //    die();
    include_once("../public/authentication.php");
    try {
        $don = update();
        $url = "productController.php?do=show";
        $smarty->assign('urldirect', $url);
        if ($don == 1) {
            $note = "تمت العملية بنجاح";
        } elseif ($don == 0) {
            $note = "لم تقوم باضافه وحده قياس  فتم اختيار وحده القياس الرئيسيه";
        }
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        $url = "productController.php";
        $smarty->assign('urldirect', $url);
        $note = "حدث خطأ ... يرجى المحاولة مرة أخرى";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "deleteFinaly") { //tempdelete
    include_once("../public/authentication.php");

    try {

        $isOptic = (int) $_GET["optic"];
        if ($isOptic == 0 || $isOptic == 1) {
            $productid = (int) $_GET['id'];
            deleteFinaly($productid);
        } elseif ($isOptic == 2) {
            $catId = (int) $_GET["id"];
            $cat = $productCatDAO->load($catId);
            $cat->conditions = 2;
            $productCatDAO->update($cat);
            $products = $productDAO->queryByProductCatId($catId);
            foreach ($products as $value) {
                deleteFinaly($value->productId);
            }
        }


        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "showbarcode") {
    global $ProgramsettingsDAO;
    //include_once("../public/authentication.php");




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


    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $companyname = $ProgramsettingsDAO->load(1);
    /* $allproduct=$productDAO->queryByConditions(0);
      $smarty->assign("allproduct",$allproduct); */
    $smarty->assign(companyname, $companyname->companyname);

    //get store for quantity
    $userdata = $userDAO->load($_SESSION['userid']);
    $storeid = $userdata->userstoreid;
    // if ($userdata->userstoreid == 0) {
    //     $storeid = 1;
    // }
    $smarty->assign("storeid", $storeid);

    $smarty->assign("productScripts", 1);
    $smarty->display("productview/addproduct.html");
} elseif ($do == "showbarcodenew") {
    global $ProgramsettingsDAO;
    //include_once("../public/authentication.php");




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


    $companyname = $ProgramsettingsDAO->load(1);
    /* $allproduct=$productDAO->queryByConditions(0);
      $smarty->assign("allproduct",$allproduct); */
    $smarty->assign(companyname, $companyname->companyname);


    $smarty->assign("productScripts", 1);
    $smarty->display("productsParcode/show1.html");
} elseif ($do == "showbarcodedetailed") {
    global $ProgramsettingsDAO;
    //include_once("../public/authentication.php");


    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

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


    $companyname = $ProgramsettingsDAO->load(1);
    /* $allproduct=$productDAO->queryByConditions(0);
      $smarty->assign("allproduct",$allproduct); */
    $smarty->assign(companyname, $companyname->companyname);

    //get store for quantity
    $userdata = $userDAO->load($_SESSION['userid']);
    $storeid = $userdata->userstoreid;
    if ($userdata->userstoreid == 0) {
        $storeid = 1;
    }
    $smarty->assign("storeid", $storeid);

    $smarty->assign("productScripts", 1);
    $smarty->display("productview/addproductdedetailed.html");
}
/////////////////////////////////////////barcode fro buy bill by hazem //////////////////////////////
elseif ($do == "showbarcodebuybill") {
    global $ProgramsettingsDAO;
    $companyname = $ProgramsettingsDAO->load(1);
    $smarty->assign(companyname, $companyname->companyname);
    include_once("../public/authentication.php");
    $buybillid = $_GET['buybillid'];

    $userid = $_SESSION['userid'];
    if (isset($_SESSION['parcodeTypeToPrint' . $userid])) {
        $parcodeTypeToPrint = (int) $_SESSION['parcodeTypeToPrint' . $userid];
        unset($_SESSION['parcodeTypeToPrint' . $userid]);
    } else {
        $parcodeTypeToPrint = (int) $_GET['parcodeTypeToPrint'];
    }

    $type = $_GET['type'];

    $smarty->assign("productScripts", 1);

    $allproductbuy = $buyBillDetailDAO->queryByBuybillid($buybillid);

    foreach ($allproductbuy as $allpro) {
        $productfullinfo = $productDAO->load($allpro->buybilldetailproductid);
        $catdata = $productCatDAO->load($productfullinfo->productCatId);
        $allpro->parcode = $productfullinfo->parcode;
        $allpro->productname = $productfullinfo->productName;
        if ($parcodeTypeToPrint == 1 && $allpro->sizeid < 1 && $allpro->colorid < 1) {
            $allpro->parcode = useSpecializedParcodeDigits($productfullinfo->parcode, $productfullinfo->productId, $Programsettingdata->specializedParcodeDigits);
        } elseif ($allpro->sizeid > 0 && $allpro->colorid > 0) {
            $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($allpro->buybilldetailproductid, $allpro->sizeid, $allpro->colorid);
            $allpro->parcode = $sizeColorStoreDetailData->parcode;
            $allpro->productname = $productfullinfo->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
        }

        $allpro->defultprice = $productfullinfo->productSellUnitPrice;
        $allpro->buybilldetailtotalprice = $productfullinfo->productSellHalfPrice;
        $allpro->productCatName = $catdata->productCatName;
    }
    /*
      print_r("<pre>");
      print_r($allproductbuy);
      print_r("<pre>");
     */
    //print_r($allproductbuy);
    $allproduct = $productDAO->queryByConditions(0);
    $smarty->assign("allproductbuy", $allproductbuy);
    $smarty->assign("allproduct", $allproduct);
    $smarty->assign("countall", count($allproductbuy));

    $smarty->display("productview/addproductbuybill.html");

    // $smarty->display("productview/addproductstor.html");
} elseif ($do == "showbarcodestor") {
    include_once("../public/authentication.php");

    $companyname = $ProgramsettingsDAO->load(1);
    $smarty->assign(companyname, $companyname->companyname);



    $storid = $_REQUEST['storid'];
    $userid = $_SESSION['userid'];
    $smarty->assign("userid", $userid);

    if (isset($_COOKIE['parcodeTypeToPrint' . $userid])) {
        $parcodeTypeToPrint = (int) $_COOKIE['parcodeTypeToPrint' . $userid];
    } else {
        $parcodeTypeToPrint = (int) $_REQUEST['parcodeTypeToPrint'];
    }
    $productCatId = $_REQUEST['productCatId'];
    $type = $_GET['type'];

    $smarty->assign("productScripts", 1);



    $queryString = ' ';
    if ($parcodeTypeToPrint == 2) {
        if (isset($storid) && $storid != '-1') {
            $queryString .= ' and productserial.storeid  = ' . $storid . ' ';
        }

        if (isset($productCatId) && $productCatId != '-1') {
            $queryString .= ' and product.productCatId = ' . $productCatId . ' ';
        }


        $allproductbuy = $ProductserialEX->queryByQueryString($queryString);
        foreach ($allproductbuy as $value) {
            if (isset($value->sizeName) && !empty($value->sizeName)) {
                $value->productName .= "/$value->sizeName/$value->colorName";
            }
            if (isset($value->colorName) && !empty($value->colorName)) {
                $value->productName .= "/$value->colorName";
            }
            $value->productquantity = $value->don;
            $value->parcode = $value->serialnumber;
        }
    } else {
        $unSerializedParcodesOnly = (int) $_COOKIE['unSerializedParcodesOnly' . $userid];
        $queryString = ' where ';
        if (isset($storid) && $storid != '-1') {
            //$queryString .= ' storedetail.storeid  = ' . $storid . ' AND';
            $queryString .= ' store.storeId  = ' . $storid . ' AND';
        }

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



        $arr = explode(' ', $queryString);

        if (isset($arr) && count($arr) > 0) {
            $lastWord = end($arr);
            if ($lastWord == 'AND') {
                array_pop($arr);

                $queryString = implode(' ', $arr);
            } elseif ($lastWord == 'where') {
                array_pop($arr);

                $queryString = implode(' ', $arr);
            }
        }



        if ($unSerializedParcodesOnly == 1)
            $allproductbuy = $storeDetailExt->queryProductsInInventoryExt2NoServiceWithUnionNotInProductSerial($queryString, $queryString);
        else
            $allproductbuy = $storeDetailExt->queryProductsInInventoryExt2NoServiceWithUnion($queryString, $queryString);

        if ($parcodeTypeToPrint == 1) {
            foreach ($allproductbuy as $value) {
                if ($value->sizeid > 0 && $value->colorid > 0) {
                    //same sizecolor parcode
                } else {
                    $value->parcode = useSpecializedParcodeDigits($value->parcode, $value->productid, $Programsettingdata->specializedParcodeDigits);
                }
            }
        }
    }


    //$allproduct = $productDAO->queryByConditions(0);
    $smarty->assign("allproductbuy", $allproductbuy);
    $smarty->assign("allproduct", $allproduct);
    $smarty->assign("countall", count($allproductbuy));

    $smarty->display("productview/addproductstor.html");
}

/////////////////////////////////////////barcode fro buy bill by hazem //////////////////////////////
elseif ($do == "showbarcoderetsellbill") {
    global $ProgramsettingsDAO;
    $companyname = $ProgramsettingsDAO->load(1);
    $smarty->assign(companyname, $companyname->companyname);
    include_once("../public/authentication.php");
    $returnsellbillid = $_GET['returnsellbillid'];
    $userid = $_SESSION['userid'];
    if (isset($_SESSION['parcodeTypeToPrint' . $userid])) {
        $parcodeTypeToPrint = (int) $_SESSION['parcodeTypeToPrint' . $userid];
        unset($_SESSION['parcodeTypeToPrint' . $userid]);
    } else {
        $parcodeTypeToPrint = (int) $_GET['parcodeTypeToPrint'];
    }

    //$type = $_GET['type'];

    $smarty->assign("productScripts", 1);

    $allproductbuy = $myReturnsellbilldetailRecord->queryByReturnsellbillid($returnsellbillid);

    foreach ($allproductbuy as $allpro) {
        $productfullinfo = $productDAO->load($allpro->returnsellbilldetailproductid);

        $catdata = $productCatDAO->load($productfullinfo->productCatId);
        $allpro->parcode = $productfullinfo->parcode;
        if ($parcodeTypeToPrint == 1 && $allpro->sizeid < 1 && $allpro->colorid < 1) {
            $allpro->parcode = useSpecializedParcodeDigits($productfullinfo->parcode, $productfullinfo->productId, $Programsettingdata->specializedParcodeDigits);
            $allpro->productname = $productfullinfo->productName;
        } elseif ($allpro->sizeid > 0 && $allpro->colorid > 0) {
            $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($allpro->buybilldetailproductid, $allpro->sizeid, $allpro->colorid);
            $allpro->parcode = $sizeColorStoreDetailData->parcode;
            $allpro->productname = $productfullinfo->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
        }

        $allpro->defultprice = $productfullinfo->productSellUnitPrice; //$allpro->returnsellbilldetailprice
        $allpro->buybilldetailtotalprice = $productfullinfo->productSellHalfPrice;
        $allpro->productCatName = $catdata->productCatName;
        //
        $allpro->buybilldetailquantity = $allpro->returnsellbilldetailquantity;
    }
    /*
      print_r("<pre>");
      print_r($allproductbuy);
      print_r("<pre>");
     */
    //print_r($allproductbuy);
    $allproduct = $productDAO->queryByConditions(0);
    $smarty->assign("allproductbuy", $allproductbuy);
    $smarty->assign("allproduct", $allproduct);
    $smarty->assign("countall", count($allproductbuy));

    $smarty->display("productview/addproductbuybill.html");

    // $smarty->display("productview/addproductstor.html");
} elseif ($do == "showbarcodestoremovement") {
    global $ProgramsettingsDAO;
    $companyname = $ProgramsettingsDAO->load(1);
    $smarty->assign(companyname, $companyname->companyname);
    include_once("../public/authentication.php");

    $userid = $_SESSION['userid'];
    if (isset($_SESSION['parcodeTypeToPrint' . $userid])) {
        $parcodeTypeToPrint = (int) $_SESSION['parcodeTypeToPrint' . $userid];
        unset($_SESSION['parcodeTypeToPrint' . $userid]);
    } else {
        $parcodeTypeToPrint = (int) $_GET['parcodeTypeToPrint'];
    }


    $smarty->assign("productScripts", 1);
    $operationnum = $_GET['operationnum'];

    $allproductbuy = $myStoremovementEx->queryStoremovementByoperationnumold22($operationnum, 0); //$notdeletedData
    foreach ($allproductbuy as $allpro) {
        $productfullinfo = $productDAO->load($allpro->productid);

        $catdata = $productCatDAO->load($productfullinfo->productCatId);
        $allpro->parcode = $productfullinfo->parcode;
        $allpro->productname = $productfullinfo->productName;
        if ($allpro->sizeid > 0 && $allpro->colorid > 0) {
            $sizeColorStoreDetailData = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($allpro->productid, $allpro->sizeid, $allpro->colorid);
            $allpro->parcode = $sizeColorStoreDetailData->parcode;
            $allpro->productname = $productfullinfo->productName . "/" . $sizeColorStoreDetailData->sizeName . "/" . $sizeColorStoreDetailData->colorName;
        }

        if ($parcodeTypeToPrint == 1 && $allpro->sizeid < 1 && $allpro->colorid < 1) {
            $allpro->parcode = useSpecializedParcodeDigits($productfullinfo->parcode, $productfullinfo->productId, $Programsettingdata->specializedParcodeDigits);
        }

        $allpro->defultprice = $productfullinfo->productSellUnitPrice;
        $allpro->buybilldetailtotalprice = $productfullinfo->productSellHalfPrice;
        $allpro->productCatName = $catdata->productCatName;
        //
        $allpro->buybilldetailquantity = $allpro->transferproductamount;
    }


    /*
      print_r("<pre>");
      print_r($allproductbuy);
      print_r("<pre>");
     */
    //print_r($allproductbuy);
    $allproduct = $productDAO->queryByConditions(0);
    $smarty->assign("allproductbuy", $allproductbuy);
    $smarty->assign("allproduct", $allproduct);
    $smarty->assign("countall", count($allproductbuy));

    $smarty->display("productview/addproductbuybill.html");

    // $smarty->display("productview/addproductstor.html");
} elseif ($do == "showserial") {
    include_once("../public/authentication.php");

    $smarty->assign("productScripts", 1);

    $allproduct = queryByProductserial();
    $smarty->assign("allproduct", $allproduct);


    $smarty->display("productview/addproductserial.html");
}
##
elseif ($do == "addoptic") {

    unset($_SESSION["productserialArray"]);

    $generatedParcode = generateParcode();
    $smarty->assign("generatedParcode", $generatedParcode);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

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

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

    $smarty->display("productview/addopticproduct.html");
}
##
elseif ($do == "addopticdata") {
    include_once("../public/authentication.php");
    try {
        addoptic();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
}
##
elseif ($do == "uploadexcel") {
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("productview/uploadexcel.html");
}
##
elseif ($do == "addproductexcel") {
    include_once("../public/authentication.php");
    try {
        //addProductExcel();
        addProductExcelWithColorOrSize();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
}
##
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", 1);
    $smarty->display("productview/editopticproduct.html");
}
##
elseif ($do == "addproductbytree") {
    //here the permssion check
    include_once("../public/authentication.php");
    unset($_SESSION["productserialArray"]);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

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

    $generatedParcode = generateParcode();
    $smarty->assign("generatedParcode", $generatedParcode);

    //get product categories
    $allParents = getProductCatParents();
    $smarty->assign("allParents", $allParents);

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

    // here the function that do the action
    $outputString = display_children(0, 0);  //display the tree
    $smarty->assign("treeHTML", $outputString);
    $smarty->assign("productScripts", 1);

    $smarty->assign("customProductCat", 1);

    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    //here the smarty templates
    $smarty->display("productview/addproductfromtree.html");
}
##
elseif ($do == "addCollectiveProduct") { //منتج تجميعى
    //here the permssion check
    //include_once("../public/authentication.php");
    $Programsettingdata = $ProgramsettingDAO->load(1);
    $smarty->assign("Programsettingdata", $Programsettingdata);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $generatedParcode = generateParcode();
    $smarty->assign("generatedParcode", $generatedParcode);

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

    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

    //here the smarty templates
    $smarty->display("productview/add_collective.html");
    $smarty->assign("productionRate", 1);
    $smarty->assign("productScripts", 1);
    $smarty->assign("customProductCat", 1);
}
##
elseif ($do == "addsizecolorproduct") {
    unset($_SESSION["productserialArray"]);

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

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

    $allSizeColor = $sizeColorDAO->queryByConditions(0);
    $smarty->assign("allSizeColor", $allSizeColor);

    $smarty->display("productview/addsizecolorproduct.html");
}
##
elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("productScripts", 1);
$smarty->assign("customValidation", 1);
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("footer.html");
}

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

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;
        return $randomString;
    }
}

function generateParcode()
{
    global $availableParcodeEX;
    $parcode = $availableParcodeEX->getAvailableParcodeValue();
    //    $parcode = $availableParcodeEX->getFirstRow();
    //    $parcode = $parcode->value;
    //check if this parcode already exists
    $data = checkbarcode($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 queryByProductserial()
{
    global $productDAO;
    global $productExt;

    $productsData = $productExt->queryAllproductwithserail();
    return $productsData;
}

function getProductCatsForShow()
{
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;
    $productsData = $productExt->queryAllProducts();



    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $smarty->assign("parentId" . $i, $parentId);
            $i++;
        }
        $itr = $i - 1;
        $smarty->assign("itr", $itr);
    }
    return $productsData;
}

function fetch_recursive($parentid, $categories)
{
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

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

function getProductCatParents()
{
    global $productCatExt;

    $allParents = $productCatExt->getProductCatParents();
    return $allParents;
}

function getUnits()
{
    global $unitDAO;

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

function getStores()
{
    global $storeDAO;

    $storesData = $storeDAO->queryByConditions(0);
    return $storesData;
}

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

    //كل التصنيفات التي ليست parent لأي تصنيف آخر
    $alldata = $productCatExt->queryAllnothavechildren('or productCatId = ' . $productCatId);
    //print_r($alldata);
    return $alldata;
}

//$productExt
function queryByProductCat($catid)
{
    global $productExt;

    $productsData = $productExt->queryByProductCatnotdel($catid);
    return $productsData;
}

// add in products tbl
function add()
{
    global $productCatDAO;
    global $productDAO;
    global $product;
    global $productUnitDAO;
    global $productUnit;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeReport;
    global $storeReportDAO;
    global $today;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $Programsettingdata;

    global $noOfDecimalPlaces;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $isCollective = (int) $_POST['isCollective'];
        if ($isCollective == 1) { //منتج تجميعى
            //$productCatId = $_POST['productCatId1'];
            $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));
            }
            $productItr = 1;
        } else {
            $productCatId = $_POST['productCatId'];
            $productItr = $_POST['productItr'];
        }

        $listDiscountPer = 0;
        $catData = $productCatDAO->load($productCatId);

        for ($i = 1; $i <= $productItr; $i++) {

            if (isset($_POST['productName' . $i]) && !empty($_POST['productName' . $i])) {
                $productName = $_POST['productName' . $i];
                $parcode = $_POST['parcode' . $i];
                $expireDate = $_POST['expireDate' . $i];
                $productBuyPrice = $_POST['productBuyPrice' . $i];
                $productSellAllPrice = $_POST['productSellAllPrice' . $i];
                $productSellHalfPrice = $_POST['productSellHalfPrice' . $i];
                $productSellUnitPrice = $_POST['productSellUnitPrice' . $i];
                $price4 = $_POST['price4_' . $i];
                $price5 = $_POST['price5_' . $i];
                $price6 = $_POST['price6_' . $i];
                $price7 = $_POST['price7_' . $i];
                $price8 = $_POST['price8_' . $i];

                $listPrice = $productBuyPrice;
                if ($Programsettingdata->useListPrice == 1) {
                    $listDiscountPer = $catData->buypricereal;
                    $listPrice = $productBuyPrice + (($productBuyPrice * $listDiscountPer) / 100);
                }

                $productquantity = $_POST['productquantity' . $i];
                $productDate = isset($_POST['productDate' . $i]) ? $_POST['productDate' . $i] : date('Y-m-d');
                $limitamount = (int) $_POST['limitamount' . $i];
                $productDescription = $_POST['productDescription' . $i];
                $inMenu = $_POST['inMenu' . $i];
                $type = (int) $_POST['type' . $i];
                $TypeOfBarcodeInTax = $_POST['TypeOfBarcodeInTax' . $i];
                $barcodeInTax = $_POST['barcodeInTax' . $i];

                $hasSizeAndColor = (int) $_POST['hasSizeAndColor' . $i];


                $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
                $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
                $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
                $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);
                $price4 = round($price4, $noOfDecimalPlaces);
                $price5 = round($price5, $noOfDecimalPlaces);
                $price6 = round($price6, $noOfDecimalPlaces);
                $price7 = round($price7, $noOfDecimalPlaces);
                $price8 = round($price8, $noOfDecimalPlaces);

                $productbuypricereal = $_POST['productbuypricereal' . $i];
                $buypricereal_precentage = $_POST['buypricereal_precentage' . $i];
                $buytotal_precentage = $_POST['buytotal_precentage' . $i];
                $buyhalf_precentage = $_POST['buyhalf_precentage' . $i];
                $buypart_precentage = $_POST['buypart_precentage' . $i];

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




                $isservice = (int) $_POST['isservice' . $i];
                if ($isservice == 1) {
                    $productBuyPrice = 0;
                    $productquantity = 0;
                }
                ###################################################################
                ##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 = checkbarcode($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
                }
                $productNameE = $_POST['productNameE' . $i];
                $partNumber = $_POST['partNumber' . $i];
                $vehicleType = $_POST['vehicleType' . $i];
                $company = $_POST['company' . $i];
                $weight = $_POST['weight' . $i];
                $origin = $_POST['origin' . $i];
                $hscode = $_POST['hscode' . $i];
                $power = $_POST['power' . $i];
                $ProductionDate = $_POST['ProductionDate' . $i];
                $expiry = $_POST['expiry' . $i];
                $procode = $_POST['procode' . $i];
                ###################################################################
                //insert into product tbl
                $product->lastbuyprice = $listPrice; //$productBuyPrice;
                $product->lastbuyprice_withDiscount = $listPrice; //$productBuyPrice;
                $product->meanbuyprice = $listPrice; //$productBuyPrice;
                $product->meanbuyprice_withDiscount = $listPrice; //$productBuyPrice;
                $product->lastbuyprice_withTax = $listPrice; //$productBuyPrice;
                $product->meanbuyprice_withTax = $listPrice; //$productBuyPrice;
                $product->overAllAveragePrice = $listPrice;



                $product->productbuypricereal = $productbuypricereal;
                $product->buypricereal_precentage = $buypricereal_precentage;
                $product->buytotal_precentage = $buytotal_precentage;
                $product->buyhalf_precentage = $buyhalf_precentage;
                $product->buypart_precentage = $buypart_precentage;


                $product->type = $type;
                $product->inMenu = $inMenu;
                $product->conditions = 0;
                $product->limitamount = $limitamount;
                $product->parcode = $parcode;
                $product->expireDate = $expireDate;
                $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->dailyentryId = 0;
                $product->webApiId = (int) $_POST['webApiId'];
                $product->isService = $isservice;
                $product->isOptic = 0;
                $product->hasSizeAndColor = $hasSizeAndColor;
                $product->TypeOfBarcodeInTax = $TypeOfBarcodeInTax;
                $product->barcodeInTax = $barcodeInTax;
                $product->productNameE = $productNameE;
                $product->partNumber = $partNumber;
                $product->vehicleType = $vehicleType;
                $product->company = $company;
                $product->weight = $weight;
                $product->origin = $origin;
                $product->hscode = $hscode;
                $product->power = $power;
                $product->ProductionDate = $ProductionDate;
                $product->expiry = $expiry;
                $product->procode = $procode;
                $product->price4 = $price4;
                $product->price5 = $price5;
                $product->price6 = $price6;
                $product->price7 = $price7;
                $product->price8 = $price8;

                if ($isCollective == 1) { //منتج تجميعى//save prices calculated in html
                    $productBuyPrice = (float) $_POST['productBuyPrice_h'];
                    $lastbuyprice = (float) $_POST['lastbuyprice_h'];
                    $lastbuyprice_withDiscount = (float) $_POST['lastbuyprice_withDiscount_h'];
                    $meanbuyprice = (float) $_POST['meanbuyprice_h'];
                    $meanbuyprice_withDiscount = (float) $_POST['meanbuyprice_withDiscount_h'];
                    $lastbuyprice_withTax = (float) $_POST['lastbuyprice_withTax_h'];
                    $meanbuyprice_withTax = (float) $_POST['meanbuyprice_withTax_h'];
                    $overAllAveragePrice = (float) $_POST['overAllAveragePrice_h'];

                    if (empty($lastbuyprice_withTax))
                        $lastbuyprice_withTax = $lastbuyprice_withDiscount;
                    if (empty($meanbuyprice_withTax))
                        $meanbuyprice_withTax = $meanbuyprice_withDiscount;

                    $product->productBuyPrice = $productBuyPrice;
                    $product->lastbuyprice = $lastbuyprice;
                    $product->lastbuyprice_withDiscount = $lastbuyprice_withDiscount;
                    $product->meanbuyprice = $meanbuyprice;
                    $product->meanbuyprice_withDiscount = $meanbuyprice_withDiscount;
                    $product->lastbuyprice_withTax = $lastbuyprice_withTax;
                    $product->meanbuyprice_withTax = $meanbuyprice_withTax;
                    $product->overAllAveragePrice = $overAllAveragePrice;
                }



                if (isset($productName) && $productName != "") {
                    $handle = new upload($_FILES['logo' . $i]);
                    $image = uploadImageswhioutresize($handle, '../views/default/images/product_image');
                    reduceImageSize($image);
                    $product->logo = $image;
                    $productId = $productDAO->insert($product);
                    ################################################################
                    ##this is prcode if empty
                    if (empty($parcode)) {
                        $parcode = addPreDigitsToNum($productId);

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


                    if (!empty($productId)) {
                        $unitsItr = $_POST['unitsItr' . $i];

                        //print_r($unitsItr);
                        $Unitdone = 0;
                        for ($j = 1; $j <= $unitsItr; $j++) {



                            $productunit = $_POST['productunit' . $i . $j];
                            $productnumber = $_POST['productnumber' . $i . $j];
                            $proUnitParcode = $_POST['proUnitParcode' . $i . $j];
                            $proUnitSellAllPrice = (float) $_POST['proUnitSellAllPrice' . $i . $j];
                            $proUnitSellHalfPrice = (float) $_POST['proUnitSellHalfPrice' . $i . $j];
                            $proUnitSellUnitPrice = (float) $_POST['proUnitSellUnitPrice' . $i . $j];
                            $proUnitBuyPrice = (float) $_POST['proUnitBuyPrice' . $i . $j];
                            $proUnitprice4 = (float) $_POST['proUnitprice4_' . $i . $j];
                            $proUnitprice5 = (float) $_POST['proUnitprice5_' . $i . $j];
                            $proUnitprice6 = (float) $_POST['proUnitprice6_' . $i . $j];
                            $proUnitprice7 = (float) $_POST['proUnitprice7_' . $i . $j];
                            $proUnitprice8 = (float) $_POST['proUnitprice8_' . $i . $j];

                            $unitInTax = $_POST['unitInTax' . $i . $j];
                            if (!empty($productunit) && $productunit != '-1' && !empty($productnumber)) {
                                if (empty($proUnitParcode))
                                    $proUnitParcode = addPreDigitsToNum2($productId, 5) . addPreDigitsToNum2($productunit, 2);

                                if (empty($proUnitSellAllPrice))
                                    $proUnitSellAllPrice = $product->productSellAllPrice * $productnumber;

                                if (empty($proUnitSellHalfPrice))
                                    $proUnitSellHalfPrice = $product->productSellHalfPrice * $productnumber;

                                if (empty($proUnitSellUnitPrice))
                                    $proUnitSellUnitPrice = $product->productSellUnitPrice * $productnumber;

                                if (empty($proUnitBuyPrice))
                                    $proUnitBuyPrice = $product->productBuyPrice * $productnumber;

                                if (empty($proUnitprice4))
                                    $proUnitprice4 = $product->price4 * $productnumber;
                                if (empty($proUnitprice5))
                                    $proUnitprice5 = $product->price5 * $productnumber;
                                if (empty($proUnitprice6))
                                    $proUnitprice6 = $product->price6 * $productnumber;
                                if (empty($proUnitprice7))
                                    $proUnitprice7 = $product->price7 * $productnumber;
                                if (empty($proUnitprice8))
                                    $proUnitprice8 = $product->price8 * $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;
                                $productUnit->unitInTax = $unitInTax;
                                $productUnit->proUnitPrice4 = $proUnitprice4;
                                $productUnit->proUnitPrice5 = $proUnitprice5;
                                $productUnit->proUnitPrice6 = $proUnitprice6;
                                $productUnit->proUnitPrice7 = $proUnitprice7;
                                $productUnit->proUnitPrice8 = $proUnitprice8;

                                $productUnitDAO->insert($productUnit);

                                $Unitdone = 1;
                            }
                        }
                        if ($Unitdone == 0) {

                            $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;
                            $productUnit->proUnitPrice4 = $product->price4;
                            $productUnit->proUnitPrice5 = $product->price5;
                            $productUnit->proUnitPrice6 = $product->price6;
                            $productUnit->proUnitPrice7 = $product->price7;
                            $productUnit->proUnitPrice8 = $product->price8;

                            $productUnitDAO->insert($productUnit);
                        }
                        if ($isCollective == 1) { //منتج تجميعى
                            addProductIngridients($productId);
                        }
                        if ($product->hasSizeAndColor == 1) { //منتج بمقاسات و الوان
                            addProductSizeAndColor($productId, $productBuyPrice, $productSellUnitPrice);

                            $productquantity = 0;
                            $sizeColorItr = (int) $_POST["sizeColorItr"];
                            for ($i = 1; $i <= $sizeColorItr; $i++) {
                                $quantity = (int) $_POST['quantity_detail' . $i];
                                $productquantity += $quantity;
                            }
                        } else {
                            //insert into storedetail tbl
                            $storeDetail->productid = $productId;
                            $storeDetail->productquantity = $productquantity;
                            $storeDetail->storedetaildate = $today;
                            $storeDetail->storeid = 1;
                            $storeDetail->userid = $_SESSION['userid'];

                            $storeDetailDAO->insert($storeDetail);
                        }

                        if ($product->hasSizeAndColor != 1) { //منتج بمقاسات و الوان لا تضيف له سطر عام
                            //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";
                            $storeReport->userid = $_SESSION['userid'];
                            $storeReport->productid = $productId;

                            $storeReportDAO->insert($storeReport);
                            //
                            onlineTempStoreReportFunc($storeReport);
                        }
                        onlineTempProductFunc($productId, 1);
                        onlineTempStoreDetailFunc(1, $productId, 0, 0, $productquantity, 1);
                        //////////////////////////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, 1);

                        $did = $returnedData[1];

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

                        $product->type = $rowData->type;
                        $product->inMenu = $inMenu;
                        $product->conditions = $rowData->conditions;
                        $product->limitamount = $rowData->limitamount;
                        $product->parcode = $rowData->parcode;
                        $product->expireDate = $rowData->expireDate;
                        $product->productBuyPrice = $rowData->productBuyPrice;
                        $product->productCatId = $rowData->productCatId;
                        $product->productDate = $rowData->productDate;
                        $product->productDescription = $rowData->productDescription;
                        $product->productName = $rowData->productName;
                        $product->productSellAllPrice = $rowData->productSellAllPrice;
                        $product->productSellHalfPrice = $rowData->productSellHalfPrice;
                        $product->productSellUnitPrice = $rowData->productSellUnitPrice;
                        $product->price4 = $rowData->price4;
                        $product->price5 = $rowData->price5;
                        $product->price6 = $rowData->price6;
                        $product->price7 = $rowData->price7;
                        $product->price8 = $rowData->price8;
                        $product->userId = $rowData->userId;
                        $product->dailyentryId = $did;


                        $productDAO->update($product);
                    }



                    if ($productId) {
                        $stores = R::getAll("SELECT * FROM `store` WHERE conditions = 0");
                        foreach ($stores as $store) {
                            $productstore = R::dispense('productstore');
                            $productstore->productid = $productId;
                            $productstore->storeid = $store['storeId'];
                            $productstore->productcatid = $productCatId;
                            $productstore->limitamount = $limitamount;
                            $productstore->prostorelimitamount = $limitamount;
                            $productstore->createddate = date("Y-m-d H:i:s");
                            $productstore->conditions = 0;
                            R::store($productstore);
                        }
                    }
                }
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        //echo $ex;
    }

    if ($_GET['do'] == "addOneSimpleReturn") { //only one product added and productid is needed
        return $productId;
    } else {
        return $Unitdone;
    }
    //write in the xml file
    //createXMLFile();
}

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>';
        //*******************************************************//
    }
}

function showwithsearch()
{
    global $productDAO;
    global $productExt;
    global $productCatExt;
    global $today;
    global $smarty;

    //$alldata = $productCatExt->queryAllChildren();
    $alldata = getProductCatsForShow();
    $smarty->assign("alldata", $alldata);

    $productCatId = $_REQUEST['productCatId'];

    $productsData = $productExt->queryByProductCatIdExt($productCatId);
    $smarty->assign('productsData', $productsData);
}

//show
function show()
{
    global $productDAO;
    global $productExt;
    global $productCatExt;
    global $today;
    global $smarty;

    //$alldata = $productCatExt->queryAllChildren();

    $productsData = $productExt->queryAllForShow2();
    //print_r($productsData);
    $smarty->assign('productsData', $productsData);
}

function executeOperation()
{
    global $productDAO;
    global $productExt;
    global $smarty;

    global $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $productId) {
            if ($operationType == '1') { //tempdelete
                try {
                    $note = tempdelete($productId);
                    if ($note != "success") {
                        //get product name
                        $productData = $productDAO->load($productId);
                        if (count($productData) > 0) {
                            $productName = $productData->productName;
                            $outputString .= $productName . ": " . $note . "<br/>";
                        }
                    } else {
                        $outputString = "تمت العملية بنجاح";
                    }
                } catch (Exception $e) {
                }
            } elseif ($operationType == "2") { //returndelete
                try {
                    returndelete($productId);
                    $outputString = "تمت العملية بنجاح";
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء إتمام العملية";
                }
            } elseif ($operationType == "3") { //delete "finally"
                try {

                    $isOptic = $_POST["optic_$productId"];
                    if ($isOptic == 0 || $isOptic == 1) {
                        deleteFinaly($productId);
                    } elseif ($isOptic == 2) {
                        $catId = $productId;
                        $cat = $productCatDAO->load($catId);
                        $cat->conditions = 2;
                        $productCatDAO->update($cat);
                        $products = $productDAO->queryByProductCatId($catId);
                        foreach ($products as $value) {
                            deleteFinaly($value->productId);
                        }
                    }


                    $outputString = "تمت العملية بنجاح";
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء إتمام العملية";
                }
            }
            $i++;
        }
        $smarty->assign("outputString", $outputString);
    }
}

function tempdelete($productId)
{ //إخفاء المنتج من الفواتير فقط
    global $productDAO;
    global $productExt;
    global $product;
    $note;
    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($productId)) {
            $productId = $_GET['id'];
        }

        if (!empty($productId)) {
            try {
                $productData = $productDAO->load($productId);
                if ($productData->dailyentryId > 0) {
                    $rid = reverseEntryWithItsID($productData->dailyentryId, 1);
                    $productExt->updateDailyEntry($rid[1], $productId);
                }
                $productExt->deletetemp($productId);
                onlineTempProductFunc($productId, 2);
                //write in the xml file
                //createXMLFile();

                $note = "success";
            } catch (Exception $e) {
                $note = "حدثت مشكلة أثناء إجراء العملية ... يرجى المحاولة مرة أخرى";
            }
        } else {
            $note = "حدث خطأ أثناء إتمام العملية";
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
    return $note;
}

function returndelete($productId)
{
    global $productDAO;
    global $productExt;
    //Transaction
    $mytransactions = new Transaction();
    try {
        if (empty($productId)) {
            $productId = $_GET['id'];
        }

        if (!empty($productId)) {
            $productData = $productDAO->load($productId);
            $productExt->returndelete($productId);
            onlineTempProductFunc($productId, 1);
            if ($productData->dailyentryId > 0) {
                $rid = reverseEntryWithItsID($productData->dailyentryId, 1);
                $productExt->updateDailyEntry($rid[1], $productId);
            }
            //write in the xml file
            //createXMLFile();
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function edit()
{
    global $productExt;

    $productId = $_GET['id'];

    $productsData = $productExt->loadExt($productId);
    $productsData->sumProductQuantity = (int) $productsData->sumProductQuantity;
    return $productsData;
}

function getProductUnits($productId)
{
    global $productUnitExt;

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

function update()
{
    global $productExt;
    global $productDAO;
    global $product;
    global $productUnitDAO;
    global $productUnit;
    global $productUnitExt;

    global $buyBillDetailExt;
    global $SellbilldetailEX;
    global $SellbilldetailDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $noOfDecimalPlaces;

    $storeId = 1;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $productId = $_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 = $_POST['expireDate1'];
        $productSellAllPrice = $_POST['productSellAllPrice1'];
        $productSellHalfPrice = $_POST['productSellHalfPrice1'];
        $productSellUnitPrice = $_POST['productSellUnitPrice1'];
        $productbuypricereal = $_POST['productbuypricereal1'];
        $productNameE = $_POST['productNameE1'];
        $partNumber = $_POST['partNumber1'];
        $vehicleType = $_POST['vehicleType1'];
        $company = $_POST['company1'];
        $weight = $_POST['weight1'];
        $origin = $_POST['origin1'];
        $hscode = $_POST['hscode1'];
        $power = $_POST['power1'];
        $ProductionDate = $_POST['ProductionDate1'];
        $expiry = $_POST['expiry1'];
        $procode = $_POST['procode1'];
        $treeId = $_POST['treeId'];
        $price4 = $_POST['price4_1'];
        $price5 = $_POST['price5_1'];
        $price6 = $_POST['price6_1'];
        $price7 = $_POST['price7_1'];
        $price8 = $_POST['price8_1'];


        $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
        $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
        $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
        $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);
        $productbuypricereal = round($productbuypricereal, $noOfDecimalPlaces);

        $price4 = round($price4, $noOfDecimalPlaces);
        $price5 = round($price5, $noOfDecimalPlaces);
        $price6 = round($price6, $noOfDecimalPlaces);
        $price7 = round($price7, $noOfDecimalPlaces);
        $price8 = round($price8, $noOfDecimalPlaces);


        $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, $noOfDecimalPlaces);
        $buypricereal_precentage = round($buypricereal_precentage, $noOfDecimalPlaces);
        $buytotal_precentage = round($buytotal_precentage, $noOfDecimalPlaces);
        $buyhalf_precentage = round($buyhalf_precentage, $noOfDecimalPlaces);
        $buypart_precentage = round($buypart_precentage, $noOfDecimalPlaces);



        $productDate = $_POST['productDate1'];
        $isService = (int) $_POST['isService'];
        $limitamount = (int) $_POST['limitamount1'];
        $inMenu = $_POST['inMenu1'];

        $type = (int) $_POST['type' . $i];
        $TypeOfBarcodeInTax = $_POST['TypeOfBarcodeInTax'];
        $barcodeInTax = $_POST['barcodeInTax'];

        $dailyentryid = $_POST['dailyentryid'];
        $hasSizeAndColor = (int) $_POST['hasSizeAndColor'];
        $meanbuyprice1 = $_POST['meanbuyprice1'];
        $meanbuyprice_withDiscount = $_POST['meanbuyprice_withDiscount1'];
        $lastbuyprice1 = $_POST['lastbuyprice1'];
        $lastbuyprice_withDiscount1 = $_POST['lastbuyprice_withDiscount1'];
        $meanbuyprice_withTax1 = $_POST['meanbuyprice_withTax1'];
        $lastbuyprice_withTax1 = $_POST['lastbuyprice_withTax1'];
        $overAllAveragePrice1 = $_POST['overAllAveragePrice1'];


        $rid = reverseEntryWithItsID($productData->dailyentryId, 1);
        //////////////////////////Imsert in daily entry
        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntry->entryComment = 'تعديل منتج ' . $productName;

        $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, 1);
        $did = $returnedData[1];

        ##check for barcode
        $flag = checkbarcode($parcode, $productId); //--
        if ($flag == 1) {
            //parcode is repeated get another one
            $parcode = generateParcode();
        }
        removeParcodeFromTable($parcode, $rowData->parcode);
        $product = $productDAO->load($productId);
        //update product
        $product->type = $type;
        $product->inMenu = $inMenu;
        $product->conditions = $conditions;
        $product->limitamount = $limitamount;
        $product->parcode = $parcode;
        $product->productCatId = $productCatId;
        $product->productDate = $productDate;
        $product->productDescription = $productDescription;
        $product->productName = $productName;
        $product->productSellAllPrice = $productSellAllPrice;
        $product->productSellHalfPrice = $productSellHalfPrice;
        $product->productSellUnitPrice = $productSellUnitPrice;
        $product->productbuypricereal = $productbuypricereal;
        $product->buypricereal_precentage = $buypricereal_precentage;
        $product->buytotal_precentage = $buytotal_precentage;
        $product->buyhalf_precentage = $buyhalf_precentage;
        $product->buypart_precentage = $buypart_precentage;
        $product->isService = $isService;
        $product->userId = $_SESSION['userid'];
        $product->expireDate = $expireDate;
        $product->productId = $productId;
        $product->dailyentryId = $did;
        $product->hasSizeAndColor = $hasSizeAndColor;
        $product->TypeOfBarcodeInTax = $TypeOfBarcodeInTax;
        $product->barcodeInTax = $barcodeInTax;
        $product->productNameE = $productNameE;
        $product->partNumber = $partNumber;
        $product->vehicleType = $vehicleType;
        $product->company = $company;
        $product->weight = $weight;
        $product->origin = $origin;
        $product->hscode = $hscode;
        $product->power = $power;
        $product->ProductionDate = $ProductionDate;
        $product->expiry = $expiry;
        $product->procode = $procode;
        $product->meanbuyprice = $meanbuyprice1;
        $product->meanbuyprice_withDiscount = $meanbuyprice_withDiscount;
        $product->lastbuyprice = $lastbuyprice1;
        $product->lastbuyprice_withDiscount = $lastbuyprice_withDiscount1;
        $product->meanbuyprice_withTax = $meanbuyprice_withTax1;
        $product->lastbuyprice_withTax = $lastbuyprice_withTax1;
        $product->overAllAveragePrice = $overAllAveragePrice1;
        $product->price4 = $price4;
        $product->price5 = $price5;
        $product->price6 = $price6;
        $product->price7 = $price7;
        $product->price8 = $price8;

        if (isset($_POST["rowitr"]) && (int) $_POST["rowitr"] > 0) { //if ($isCollective == 1) {//منتج تجميعى//save prices calculated in html
            $productBuyPrice = (float) $_POST['productBuyPrice_h'];
            $lastbuyprice = (float) $_POST['lastbuyprice_h'];
            $lastbuyprice_withDiscount = (float) $_POST['lastbuyprice_withDiscount_h'];
            $meanbuyprice = (float) $_POST['meanbuyprice_h'];
            $meanbuyprice_withDiscount = (float) $_POST['meanbuyprice_withDiscount_h'];
            $lastbuyprice_withTax = (float) $_POST['lastbuyprice_withTax_h'];
            $meanbuyprice_withTax = (float) $_POST['meanbuyprice_withTax_h'];


            if (empty($lastbuyprice_withTax))
                $lastbuyprice_withTax = $lastbuyprice_withDiscount;
            if (empty($meanbuyprice_withTax))
                $meanbuyprice_withTax = $meanbuyprice_withDiscount;

            if ($productBuyPrice != $product->productBuyPrice) {
                //
                $meanbuyprice = ($product->meanbuyprice + $productBuyPrice) / 2;
                $meanbuyprice_withDiscount = ($product->meanbuyprice_withDiscount + $productBuyPrice) / 2;
                //
            }


            $product->productBuyPrice = $productBuyPrice;
            $product->lastbuyprice = $lastbuyprice;
            $product->lastbuyprice_withDiscount = $lastbuyprice_withDiscount;
            $product->meanbuyprice = round($meanbuyprice, $noOfDecimalPlaces);
            $product->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, $noOfDecimalPlaces);
            $product->lastbuyprice_withTax = $lastbuyprice_withTax;
            $product->meanbuyprice_withTax = $meanbuyprice_withTax;
        } else {
            if ($productBuyPrice != $product->productBuyPrice) {
                //
                $meanbuyprice = ($product->meanbuyprice + $productBuyPrice) / 2;
                $meanbuyprice_withDiscount = ($product->meanbuyprice_withDiscount + $productBuyPrice) / 2;
                //
                $product->meanbuyprice = round($meanbuyprice, $noOfDecimalPlaces);
                //$product->meanbuyprice_withDiscount = round($meanbuyprice_withDiscount, $noOfDecimalPlaces);
                //                $product->lastbuyprice_withTax = round($lastbuyprice_withTax1, $noOfDecimalPlaces);
                //                $product->meanbuyprice_withTax = round($meanbuyprice_withTax1, $noOfDecimalPlaces);
            }
        }
        $product->productBuyPrice = $productBuyPrice;

        $handle = new upload($_FILES['logo']);
        $image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/product_image');
        reduceImageSize($image);
        $product->logo = $image;
        $productDAO->update($product);
        $productExt->updateTreeId($productId, $treeId);

        if (!empty($productId)) {
            $product = $productDAO->load($productId);
            //productunitid
            $allmyunitdata = $productUnitDAO->queryByProductid($productId);
            foreach ($allmyunitdata as $myunitdata) {
                $allbuydata = $buyBillDetailExt->queryAllbyproductunitid($myunitdata->productunitid);
                $myselldata = $SellbilldetailEX->queryAllbyproductunitid($myunitdata->productunitid);
                //if(count($allbuydata) == 0 &&  count($myselldata) == 0)
                {

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

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

            //1- delete all product unit associated with this product
            //2- insert product units again with the new ones if any
            $unitsItr = $_POST['unitsItr1'];
            $Unitdone = 0;
            for ($j = 1; $j <= $unitsItr; $j++) {
                $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];
                $unitInTax = $_POST['unitInTax1' . $j];
                $proUnitprice4 = (float) $_POST['proUnitprice4_1' . $j];
                $proUnitprice5 = (float) $_POST['proUnitprice5_1' . $j];
                $proUnitprice6 = (float) $_POST['proUnitprice6_1' . $j];
                $proUnitprice7 = (float) $_POST['proUnitprice7_1' . $j];
                $proUnitprice8 = (float) $_POST['proUnitprice8_1' . $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;

                    if (empty($proUnitprice4) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                        $proUnitprice4 = $product->price4 * $productnumber;
                    if (empty($proUnitprice5) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                        $proUnitprice5 = $product->price5 * $productnumber;
                    if (empty($proUnitprice6) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                        $proUnitprice6 = $product->price6 * $productnumber;
                    if (empty($proUnitprice7) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                        $proUnitprice7 = $product->price7 * $productnumber;
                    if (empty($proUnitprice8) || $Programsettingdata->updateProUnitPricesOnPriceUpdate == 0)
                        $proUnitprice8 = $product->price8 * $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;
                    $productUnit->proUnitPrice4 = $proUnitprice4;
                    $productUnit->proUnitPrice5 = $proUnitprice5;
                    $productUnit->proUnitPrice6 = $proUnitprice6;
                    $productUnit->proUnitPrice7 = $proUnitprice7;
                    $productUnit->proUnitPrice8 = $proUnitprice8;
                    $productUnit->unitInTax = $unitInTax;

                    if (isset($productunitid) && $productunitid > 0) {
                        $productUnit->productunitid = $productunitid;
                        $productUnitDAO->update($productUnit);

                        //echo 'insert id =  '.$productunitid.' <br>';
                    } else {
                        $productUnitDAO->insert($productUnit);
                    }

                    $Unitdone = 1;
                }
            }
            ## with $unitsItr = 0 and Unitdone  == 1 =>we wont change unit at all , we keep old unit as it is
            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1 && isset($_POST['Unitdone']) && $_POST['Unitdone'] == 1) {
                $Unitdone = 1;
            }
            if ($Unitdone == 0) {

                $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;
                $productUnit->proUnitPrice4 = $proUnitprice4;
                $productUnit->proUnitPrice5 = $proUnitprice5;
                $productUnit->proUnitPrice6 = $proUnitprice6;
                $productUnit->proUnitPrice7 = $proUnitprice7;
                $productUnit->proUnitPrice8 = $proUnitprice8;

                $productUnitDAO->insert($productUnit);
            }

            if (isset($_POST["isCollective"]) && (int) $_POST["isCollective"] == 1) { //$isCollective == 1) {//منتج تجميعى
                updateProductIngridients($productId);
            }
            if ($hasSizeAndColor == 1) { //منتج بمقاسات و الوان
                updateProductSizeAndColor($productId, $productBuyPrice, $productSellUnitPrice);
            }

            onlineTempProductFunc($productId, 1);
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
    return $Unitdone;
    //}
    //write in the xml file
    //createXMLFile();
}

// $parent is the parent of the children we want to see
// $level is increased when we go deeper into the tree,
// used to display a nice indented tree
function display_children($parent, $level)
{
    global $productCatExt;
    global $outputString;
    // retrieve all children of $parent
    $result = $productCatExt->queryByParentExt($parent);

    if (count($result) > 0) {
        // display each child
        foreach ($result as $type) {

            if ($type->isOptic != 2) {
                //check for products for this category
                $productsData = queryByProductCat($type->productCatId);

                $outputString .= '<li><a href="#" class="tree-toggle" data-toggle="branch" data-value="' . $type->productCatId . '">
                        ' . $type->productCatName . ' </a>';

                $outputString .= '<ul class="branch in">';
                if (count($productsData) > 0) {
                    foreach ($productsData as $product) {
                        $outputString .= '<li><a href="#" data-role="leaf"  data-value="' . $product->productId . '" data-isoptic="' . $type->isOptic . '"> ' . $product->productName . "/" . $type->productCatName . '</a></li>';
                    }
                }

                // call this function again to display this
                // child's children
                display_children($type->productCatId, $level + 1);

                $outputString .= '</li>';
                $outputString .= '</ul>';
            } else {
                $outputString .= '<li><a href="#" data-role="leaf"  data-value="' . $type->productCatId . '" data-isoptic="' . $type->isOptic . '" > ' . $type->productCatName . '</a></li>';
            }
        }
    }
    return $outputString;
}

//categories only
function display_children_cats($parent, $level)
{
    global $productCatExt;
    global $outputString;
    // retrieve all children of $parent
    $result = $productCatExt->queryByParentExt($parent);

    if (count($result) > 0) {
        // display each child
        foreach ($result as $type) {

            if ($type->isOptic != 2) {
                //check for products for this category

                $outputString .= '<li><a href="#" class="tree-toggle" data-toggle="branch" data-value="' . $type->productCatId . '">
                        ' . $type->productCatName . ' </a>';
                $outputString .= '<ul class="branch in">';
                // call this function again to display this
                // child's children
                display_children_cats($type->productCatId, $level + 1);

                $outputString .= '</li>';
                $outputString .= '</ul>';
            } else {
                $outputString .= '<li><a href="#" data-role="leaf"  data-value="' . $type->productCatId . '" data-isoptic="' . $type->isOptic . '" > ' . $type->productCatName . '</a></li>';
            }
        }
    }
    return $outputString;
}

//////////////////////////**************************************//////////////////////////
function showallproduct()
{
    global $productDAO;
    global $productExt;
}

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

    //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);
        onlineTempProductFunc($productId, 2);
        //
        ifCollectiveDelProductionEquation($productId);
        //
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function searchProductsWithBuyPrice()
{
    global $productDAO;
    global $productExt;
    global $productCatExt;
    global $today;
    global $smarty;

    $productCatId = $_REQUEST['productCatId'];
    if (!empty($productCatId)) {
        //select all data from product tbl by productCatId
        $productsData = $productExt->queryByProductCatIdNotdeleted($productCatId);

        if (count($productsData) > 0) {
            foreach ($productsData as $pro) {
                //إجمالي السعر
                $totalPrice += $pro->productquantity * $pro->productBuyPrice;
                //إجمالي الوحدات
                $totalQuantity += $pro->productquantity;
            }
            $smarty->assign('totalPrice', $totalPrice);
            $smarty->assign('totalQuantity', $totalQuantity);
        }
    }
    // assign your db results to the template
    $smarty->assign('productsData', $productsData);
}

//show
function showProductsWithBuyPrice()
{
    global $productDAO;
    global $productExt;
    global $productCatExt;
    global $today;
    global $smarty;

    // get the all colums number
    $productsData = $productExt->queryProductsWithBuyPrice(); //select not deleted
    SmartyPaginate::setTotal(count($allColums));

    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            //إجمالي السعر
            $totalPrice += $pro->productquantity * $pro->productBuyPrice;
            //إجمالي الوحدات
            $totalQuantity += $pro->productquantity;
        }
        $smarty->assign('totalPrice', $totalPrice);
        $smarty->assign('totalQuantity', $totalQuantity);
    }

    // assign your db results to the template
    $smarty->assign('productsData', $productsData);
}

//////////////////////////**************************************//////////////////////////
##for optic
function getProductCatParentOptic()
{
    global $productCatDAO;

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

function addoptic()
{
    $currentType = filter_input(INPUT_POST, "currentType");
    if ($currentType == 0) {
        addOpticProductWithSizeColor();
    } elseif ($currentType == 1) {
        addOpticProductWithOutSizeColor();
    }
}

function addOpticProductWithSizeColor()
{
    global $product;
    global $productDAO;

    //Productcat
    global $productCat;
    global $productCatDAO;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $today;

    global $noOfDecimalPlaces;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $parent = (int) filter_input(INPUT_POST, "opticproductcatid");
        if (empty($parent) || $parent == -1) {
            $parent = 0;
        }
        $catname = filter_input(INPUT_POST, "name");
        $description = filter_input(INPUT_POST, "description");

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

        $productCat->buytotal = 0;
        $productCat->buyhalf = 0;
        $productCat->buypart = 0;
        $productCat->buypricereal = 0;
        $productCat->opticServices = '';

        $catid = $productCatDAO->insert($productCat);
        onlineTempCategoryFunc($catid, 1);

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

        $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
        $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
        $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
        $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);

        $sizecoloritr = filter_input(INPUT_POST, "sizecoloritr");
        for ($i = 0; $i < $sizecoloritr; $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);


            $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->type = 0;
            $product->sellingtype = 0;
            $product->expireDate = 0;
            $product->isService = 0;

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

            $product->lastbuyprice = $productBuyPrice;
            $product->lastbuyprice_withDiscount = $productBuyPrice;
            $product->meanbuyprice = $productBuyPrice;
            $product->meanbuyprice_withDiscount = $productBuyPrice;
            $product->lastbuyprice_withTax = $productBuyPrice;
            $product->meanbuyprice_withTax = $productBuyPrice;
            $product->productbuypricereal = $productBuyPrice;
            $product->buypricereal_precentage = 0;
            $product->buytotal_precentage = 0;
            $product->buyhalf_precentage = 0;
            $product->buypart_precentage = 0;
            $product->logo = '.';


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

            if (isset($productName) && $productName !== "") {
                ###################################################################
                ##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 = checkbarcode($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->parcode = $parcode;
                $productId = $productDAO->insert($product);
                ################################################################
                ##this is prcode if empty
                if (empty($parcode)) {
                    $parcode = addPreDigitsToNum($productId);

                    ##check for barcode
                    $flag = checkbarcode($parcode);
                    if ($flag == 1) {
                        //parcode is repeated get another one
                        $parcode = generateParcode();
                    }
                    removeParcodeFromTable($parcode);
                    $product->parcode = $parcode;
                    $productDAO->update($product);
                }
                ##############################################################
                if (!empty($productId)) {
                    addOpticProductStoredata($productId, $productquantity);
                    onlineTempProductFunc($productId, 1);
                    //////////////////////////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, 1);

                    $did = $returnedData[1];

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

                    addOpticProductUnit($productId);
                }
            }
        }

        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function addOpticProductWithOutSizeColor()
{
    global $product;
    global $productDAO;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $today;

    global $noOfDecimalPlaces;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $opticproductcatid = filter_input(INPUT_POST, "opticproductcatid");
        $productName = filter_input(INPUT_POST, "name");
        $limitamount = filter_input(INPUT_POST, "limitamount");
        $description = filter_input(INPUT_POST, "description");
        $productBuyPrice = filter_input(INPUT_POST, "productBuyPrice");
        $productSellAllPrice = filter_input(INPUT_POST, "productSellAllPrice");
        $productSellHalfPrice = filter_input(INPUT_POST, "productSellHalfPrice");
        $productSellUnitPrice = filter_input(INPUT_POST, "productSellUnitPrice");

        $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
        $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
        $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
        $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);

        $productparcode = filter_input(INPUT_POST, "productparcode");
        $productquantity = filter_input(INPUT_POST, "productQuantity");



        $product->productName = $productName;
        $product->productDescription = $description;
        $product->productCatId = $opticproductcatid;
        $product->productBuyPrice = $productBuyPrice;
        $product->productSellAllPrice = $productSellAllPrice;
        $product->productSellHalfPrice = $productSellHalfPrice;
        $product->productSellUnitPrice = $productSellUnitPrice;
        $product->limitamount = $limitamount;

        $product->type = 0;
        $product->sellingtype = 0;
        $product->expireDate = 0;
        $product->isService = 0;

        $product->dailyentryId = 0;
        $product->isOptic = 1;


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

        $product->lastbuyprice = $productBuyPrice;
        $product->lastbuyprice_withDiscount = $productBuyPrice;
        $product->meanbuyprice = $productBuyPrice;
        $product->meanbuyprice_withDiscount = $productBuyPrice;
        $product->lastbuyprice_withTax = $productBuyPrice;
        $product->meanbuyprice_withTax = $productBuyPrice;
        $product->productbuypricereal = $productBuyPrice;
        $product->buypricereal_precentage = 0;
        $product->buytotal_precentage = 0;
        $product->buyhalf_precentage = 0;
        $product->buypart_precentage = 0;
        $product->logo = '.';
        if (isset($productName) && $productName != "") {
            ###################################################################
            ##prcode if not empty check and use it ==> as checkbarcode must be used before insert if user write his own parcode
            if (!empty($productparcode)) {
                $productparcode = addPreDigitsToNum($productparcode);
                ##check for barcode
                $flag = checkbarcode($productparcode);
                if ($flag == 1) {
                    //parcode is repeated get another one
                    $productparcode = generateParcode();
                }
                removeParcodeFromTable($productparcode);
            } else {
                //will do it after insert use parcode from pro id comming now
            }
            ###################################################################
            $product->parcode = $productparcode;
            $productId = $productDAO->insert($product);
            ################################################################
            ##this is prcode if empty
            if (empty($productparcode)) {
                $productparcode = addPreDigitsToNum($productId);

                ##check for barcode
                $flag = checkbarcode($productparcode);
                if ($flag == 1) {
                    //parcode is repeated get another one
                    $productparcode = generateParcode();
                }
                removeParcodeFromTable($productparcode);
                $product->parcode = $parcode;
                $productDAO->update($product);
            }
            ##############################################################
            if (!empty($productId)) {
                addOpticProductStoredata($productId, $productquantity);
                onlineTempProductFunc($productId, 1);
                //////////////////////////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, 1);

                $did = $returnedData[1];

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

                addOpticProductUnit($productId);
            }
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }
}

function addOpticProductUnit($productId)
{
    //Opticproductunit
    global $productUnit;
    global $productUnitDAO;
    global $today;

    $Unitdone = 0;
    $unitsitr = filter_input(INPUT_POST, "unitsitr");
    for ($i = 0; $i < $unitsitr; $i++) {
        $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'];
            $productUnitDAO->insert($productUnit);

            $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);
    onlineTempStoreDetailFunc(1, $productId, 0, 0, $productquantity, 1);

    //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);
    onlineTempStoreReportFunc($storeReport);
}

function addExcelProductStoredata($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);
    onlineTempStoreDetailFunc(1, $productId, 0, 0, $productquantity, 1);

    //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/uploadexcel";
    $storeReport->userid = $_SESSION['userid'];
    $storeReport->productid = $productId;

    $storeReportDAO->insert($storeReport);
    onlineTempStoreReportFunc($storeReport);
}

/////////////////////////////////////////////////////////////////
##for show new way of multi parents
function getCategoryChilds($parentid = 0)
{
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

function getAllSubCat($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;
                getAllSubCat($data->productCatId, $mode);
            } elseif ($mode == 2) {
                $childData = $productCatExt->queryByParentExt2($data->productCatId);
                if (count($childData) > 0) {
                    getAllSubCat($data->productCatId, $mode);
                } else {
                    if (!empty($data->productCatId)) {
                        array_push($lastLevelCatIDS, $data->productCatId);
                    }
                }
            }
        }
    } else {
        //        if ($mode == 2) {
        //            $childData = $productCatExt->queryByParentExt2($data->productCatId);
        //            if (count($childData) > 0) {
        //                getAllSubCat($data->productCatId, $mode);
        //            } else {
        //                if (!empty($data->productCatId)) {
        //                    array_push($lastLevelCatIDS, $data->productCatId);
        //                }
        //            }
        //        }
    }
}

/////////////////////////////////////////////////////////////////
##for excel uploads
function addProductExcel()
{
    global $productCat;
    global $productCatDAO;
    global $product;
    global $productDAO;
    global $productUnit;
    global $productUnitDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;
    $storeId = 1;
    ## upload file
    $handle = new upload($_FILES['productssheet']);
    $excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;
    //  Read your Excel workbook
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        //$objReader->setUTFEncoder('iconv');
        //$objReader::setOutputEncoding('UTF-8');
        $objPHPExcel = $objReader->load($inputFileName);



        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //echo $highestRow . "*" . $highestColumn . "<br/>";
        //$data = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(0, 1)->getValue();
        //  Loop through each row of the worksheet in turn
        for ($row = 5; $row <= $highestRow; $row++) {
            //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $rowData = $rowData[0];
            if (isset($rowData[0], $rowData[1]) && $rowData[0] != "" && !empty($rowData[1])) {
                $product = new product();
                ##recieve data
                $productName = $rowData[0];
                $CatName = $rowData[1];
                $parcode = $rowData[2];
                $productBuyPrice = (float) $rowData[3];
                $productSellAllPrice = (float) $rowData[4];
                $productSellHalfPrice = (float) $rowData[5];
                $productSellUnitPrice = (float) $rowData[6];
                $productquantity = (int) $rowData[7];
                $limitamount = (int) $rowData[8];
                $type = (int) $rowData[9];
                $description = $rowData[10];

                if (!isset($productBuyPrice) || empty($productBuyPrice)) {
                    $productBuyPrice = 0;
                }
                if (!isset($productSellAllPrice) || empty($productSellAllPrice)) {
                    $productSellAllPrice = 0;
                }
                if (!isset($productSellHalfPrice) || empty($productSellHalfPrice)) {
                    $productSellHalfPrice = 0;
                }
                if (!isset($productSellUnitPrice) || empty($productSellUnitPrice)) {
                    $productSellUnitPrice = 0;
                }
                if (!isset($productquantity) || empty($productquantity)) {
                    $productquantity = 0;
                }
                if (!isset($limitamount) || empty($limitamount)) {
                    $limitamount = 0;
                }
                if (!isset($type) || empty($type) || $type != 1) {
                    $type = 0;
                }


                ###################################################
                ##1-check if product exist
                $isProductHere = $productDAO->queryByProductName($productName);
                if (count($isProductHere) < 1) {
                    ##2-handle cat
                    $catData = $productCatDAO->queryByProductCatName($CatName);
                    if (count($catData) > 0) {
                        $product->productCatId = $catData[0]->productCatId;
                    } else {
                        $productCat->productCatName = $CatName;
                        $productCat->productCatDescription = "";
                        $productCat->productCatParent = 0;
                        $productCat->selldiscount = 0;
                        $productCat->buydiscount = 0;
                        $productCat->discounttype = 0;
                        $productCat->isOptic = 0;
                        $productCat->userId = $_SESSION['userid'];
                        $productCat->conditions = 0;
                        $productCat->productCatDate = date("Y-m-d");
                        $productCat->inMenu = 0;
                        $productCat->buytotal = 0;
                        $productCat->buyhalf = 0;
                        $productCat->buypart = 0;
                        $productCat->buypricereal = 0;
                        $productCat->opticServices = '';

                        $catid = $productCatDAO->insert($productCat);
                        onlineTempCategoryFunc($catid, 1);
                        $product->productCatId = $catid;
                    }
                    ###################################################################
                    ##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 = checkbarcode($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
                    }
                    ###################################################################
                    //                    $okParcode == FALSE;
                    //                    if (isset($parcode) && !empty($parcode)) {
                    //                        $flag = checkbarcode($parcode);
                    //                        if ($flag == 2) {
                    //                            $okParcode = TRUE;
                    //                        }
                    //                    }
                    //                    if ($okParcode == FALSE) {
                    //                        $parcode = generateParcode();
                    //                    }
                    ###########################
                    ##4-insert product
                    $product->productName = $productName;
                    $product->productDescription = '';
                    if ($type == 1) {
                        $productBuyPrice = 0;
                        $productquantity = 0;
                    }
                    $product->productBuyPrice = $productBuyPrice;
                    $product->productSellAllPrice = $productSellAllPrice;
                    $product->productSellHalfPrice = $productSellHalfPrice;
                    $product->productSellUnitPrice = $productSellUnitPrice;
                    $product->productDate = date("Y-m-d");
                    $product->conditions = 0;
                    $product->userId = $_SESSION['userid'];
                    $product->limitamount = $limitamount;
                    $product->parcode = $parcode;
                    $product->type = 0;
                    $product->dailyentryId = 0;
                    $product->isService = $type;
                    $product->isOptic = 0;
                    $product->inMenu = $inMenu;

                    $product->lastbuyprice = $productBuyPrice;
                    $product->lastbuyprice_withDiscount = $productBuyPrice;
                    $product->meanbuyprice = $productBuyPrice;
                    $product->meanbuyprice_withDiscount = $productBuyPrice;
                    $product->lastbuyprice_withTax = $productBuyPrice;
                    $product->meanbuyprice_withTax = $productBuyPrice;
                    $product->productbuypricereal = $productBuyPrice;
                    $product->buypricereal_precentage = 0;
                    $product->buytotal_precentage = 0;
                    $product->buyhalf_precentage = 0;
                    $product->buypart_precentage = 0;
                    $product->logo = 0;
                    $product->productDescription = $description;

                    $productid = $productDAO->insert($product);
                    onlineTempProductFunc($productid, 1);
                    ################################################################
                    ##this is prcode if empty
                    if (empty($parcode)) {
                        $parcode = addPreDigitsToNum($productid);

                        ##3-check parcode
                        $flag = checkbarcode($parcode);
                        if ($flag == 1 || empty($parcode)) {
                            //parcode is repeated get another one
                            $parcode = generateParcode();
                        }
                        removeParcodeFromTable($parcode);
                        $product->parcode = $parcode;
                        $productDAO->update($product);
                    }
                    ##############################################################
                    ##
                    $productUnit->conditions = 0;
                    $productUnit->productid = $productid;
                    $productUnit->productnumber = 1;
                    $productUnit->productunitdate = $today;
                    $productUnit->unitid = 1;
                    $productUnit->userid = $_SESSION['userid'];

                    $productUnitDAO->insert($productUnit);
                    ##5-affectstore
                    addExcelProductStoredata($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];

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

        unlink($inputFileName);
    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}

function addProductExcelWithColorOrSize()
{
    global $productCat;
    global $productCatDAO;
    global $product;
    global $productDAO;
    global $productExt;
    global $productUnit;
    global $productUnitDAO;

    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $noOfDecimalPlaces;
    $storeId = 1;
    ## upload file
    $handle = new upload($_FILES['productssheet']);
    $excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;
    //  Read your Excel workbook
    //Transaction
    $mytransactions = new Transaction();
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        //$objReader->setUTFEncoder('iconv');
        //$objReader::setOutputEncoding('UTF-8');
        $objPHPExcel = $objReader->load($inputFileName);



        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //echo $highestRow . "*" . $highestColumn . "<br/>";
        //$data = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(0, 1)->getValue();
        //  Loop through each row of the worksheet in turn
        //        $rowData = $sheet->rangeToArray('A4:' . $highestColumn . "4", NULL, TRUE, FALSE);
        //        $rowData = $rowData[0];
        //
        //        $initialNoOfCats = 0;
        //        for ($i = 0; $i < count($rowData); $i++) {
        //            if (strpos($rowData[$i], 'تصنيف') !== false) {
        //                $initialNoOfCats++;
        //            }
        //        }
        //        if (empty($initialNoOfCats)) {
        //            $initialNoOfCats = 1;
        //        }
        $initialNoOfCats = 4;
        $eachCatLastId = array();
        $eachCatLastId[0] = 0;
        $eachCatLastId[1] = 0;
        $eachCatLastId[2] = 0;
        $eachCatLastId[3] = 0;
        $eachCatLastId[4] = 0;
        for ($row = 5; $row <= $highestRow; $row++) {
            $noOfCats = $initialNoOfCats;
            //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $rowData = $rowData[0];

            ##getdata
            $col = $noOfCats;
            $productName = $rowData[$col];
            $col++;
            $color_size = $rowData[$col];
            $col++;
            if ((isset($productName) && $productName !== "") || (isset($color_size) && $color_size !== "")) {
                $isOptic = 0;
                if (isset($color_size) && !empty($color_size)) {
                    //يعنى لو فيه لون او مقاس يبقى اسم المنتجهو كمان تصنيف واللون هو اللى منتج
                    $noOfCats = $noOfCats + 1;
                    $isOptic = 2;
                    $productName = $color_size;
                }
                $theparent = 0; //as start
                for ($i = 0; $i < $noOfCats; $i++) {
                    $catName = $rowData[$i];
                    if (isset($catName) && !empty($catName)) {
                        if ($i == ($noOfCats - 1)) {
                            $theparent = handleCats($catName, $theparent, $isOptic);
                        } else {
                            $theparent = handleCats($catName, $theparent, 0);
                        }
                        $eachCatLastId[$i] = $theparent;
                    } else {
                        if (!empty($eachCatLastId[$i])) {
                            $theparent = $eachCatLastId[$i];
                        }
                    }
                }
                $lastCatid = $theparent;
                $parcode = $rowData[$col];
                $col++;
                $productBuyPrice = (float) $rowData[$col];
                $col++;
                $productSellAllPrice = (float) $rowData[$col];
                $col++;
                $productSellHalfPrice = (float) $rowData[$col];
                $col++;
                $productSellUnitPrice = (float) $rowData[$col];
                $col++;
                $productquantity = (int) $rowData[$col];
                $col++;
                $weightedDiscount = (float) $rowData[$col];
                $col++;
                $limitamount = (int) $rowData[$col];
                $col++;
                $type = (int) $rowData[$col];
                $col++;
                $description = $rowData[$col];
                //!empty $lastCatid checks that is it is not empty and it is not 0;
                if (isset($lastCatid, $productName) && !empty($lastCatid) && $productName !== "") {
                    $product = new product();
                    ##check data
                    if (!isset($productBuyPrice) || empty($productBuyPrice)) {
                        $productBuyPrice = 0;
                    }
                    if (!isset($productSellAllPrice) || empty($productSellAllPrice)) {
                        $productSellAllPrice = 0;
                    }
                    if (!isset($productSellHalfPrice) || empty($productSellHalfPrice)) {
                        $productSellHalfPrice = 0;
                    }
                    if (!isset($productSellUnitPrice) || empty($productSellUnitPrice)) {
                        $productSellUnitPrice = 0;
                    }
                    if (!isset($productquantity) || empty($productquantity)) {
                        $productquantity = 0;
                    }
                    if (!isset($limitamount) || empty($limitamount)) {
                        $limitamount = 0;
                    }
                    if (!isset($type) || empty($type) || $type != 1) {
                        $type = 0;
                    }

                    ###################################################
                    ##1-check if product exist
                    if ($isOptic == 2) {
                        $isProductHere = $productExt->queryByProductNameEX($productName, $lastCatid);
                    } else {
                        $isProductHere = $productDAO->queryByProductName($productName);
                    }

                    if (count($isProductHere) < 1) {
                        ##2-handle cat##done above
                        ###################################################################
                        ##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 = checkbarcode($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
                        }
                        ###################################################################
                        //                        $okParcode == FALSE;
                        //                        if (isset($parcode) && !empty($parcode)) {
                        //                            $flag = checkbarcode($parcode);
                        //                            if ($flag == 2) {
                        //                                $okParcode = TRUE;
                        //                            }
                        //                        }
                        //                        if ($okParcode == FALSE) {
                        //                            $parcode = generateParcode();
                        //                        }
                        ##4-insert product
                        $product->productCatId = $lastCatid;
                        $product->productName = $productName;
                        $product->productDescription = '';
                        if ($type == 1) {
                            $productBuyPrice = 0;
                            $productquantity = 0;
                        }
                        $productBuyPriceWithDiscount = $productBuyPrice;
                        if ($weightedDiscount > 0) {
                            $discountVal = (100 - $weightedDiscount) / 100;
                            $productBuyPriceWithDiscount = round(($productBuyPrice * $discountVal), $noOfDecimalPlaces);
                        }
                        $product->productBuyPrice = $productBuyPrice;
                        $product->productSellAllPrice = $productSellAllPrice;
                        $product->productSellHalfPrice = $productSellHalfPrice;
                        $product->productSellUnitPrice = $productSellUnitPrice;
                        $product->productDate = date("Y-m-d");
                        $product->conditions = 0;
                        $product->userId = $_SESSION['userid'];
                        $product->limitamount = $limitamount;
                        $product->weightedDiscount = $weightedDiscount;
                        $product->parcode = $parcode;
                        $product->type = 0;
                        $product->dailyentryId = 0;
                        $product->isService = $type;
                        $product->isOptic = $isOptic;
                        $product->inMenu = 0;
                        $product->lastbuyprice = $productBuyPrice;
                        $product->lastbuyprice_withDiscount = $productBuyPriceWithDiscount;
                        $product->meanbuyprice = $productBuyPrice;
                        $product->meanbuyprice_withDiscount = $productBuyPriceWithDiscount;
                        $product->lastbuyprice_withTax = $productBuyPrice;
                        $product->meanbuyprice_withTax = $productBuyPrice;
                        $product->expireDate = 0;
                        $product->productDescription = $description;
                        $product->price4 = $productSellUnitPrice;
                        $product->price5 = $productSellUnitPrice;
                        $product->price6 = $productSellUnitPrice;
                        $product->price7 = $productSellUnitPrice;
                        $product->price8 = $productSellUnitPrice;
                        $productid = $productDAO->insert($product);
                        onlineTempProductFunc($productid, 1);
                        ################################################################
                        ##this is prcode if empty
                        if (empty($parcode)) {
                            $parcode = addPreDigitsToNum($productid);

                            ##check for barcode
                            $flag = checkbarcode($parcode);
                            if ($flag == 1) {
                                //parcode is repeated get another one
                                $parcode = generateParcode();
                            }
                            removeParcodeFromTable($parcode);
                            $product->parcode = $parcode;
                            $productDAO->update($product);
                        }
                        ##############################################################
                        ##
                        $noOfUnitsAdded = 0;
                        for ($i = 1; $i <= 3; $i++) {
                            $col++;
                            $unitId = (int) $rowData[$col];
                            $col++;
                            $productnumber = (float) $rowData[$col];
                            if ($unitId > 0 && $productnumber > 0) {
                                $productUnit->conditions = 0;
                                $productUnit->productid = $productid;
                                $productUnit->productnumber = $productnumber; //1;
                                $productUnit->productunitdate = $today;
                                $productUnit->unitid = $unitId; //1;
                                $productUnit->userid = $_SESSION['userid'];
                                $productUnit->proUnitParcode = addPreDigitsToNum2($productid, 5) . addPreDigitsToNum2($unitId, 2);
                                $productUnit->proUnitSellAllPrice = $product->productSellAllPrice * $productnumber;
                                $productUnit->proUnitSellHalfPrice = $product->productSellHalfPrice * $productnumber;
                                $productUnit->proUnitSellUnitPrice = $product->productSellUnitPrice * $productnumber;
                                $productUnit->proUnitBuyPrice = $product->productBuyPrice;
                                $productUnit->proUnitPrice4 = $product->productSellUnitPrice * $productnumber;
                                $productUnit->proUnitPrice5 = $product->productSellUnitPrice * $productnumber;
                                $productUnit->proUnitPrice6 = $product->productSellUnitPrice * $productnumber;
                                $productUnit->proUnitPrice7 = $product->productSellUnitPrice * $productnumber;
                                $productUnit->proUnitPrice8 = $product->productSellUnitPrice * $productnumber;
                                $productUnitDAO->insert($productUnit);
                                $noOfUnitsAdded++;
                            }
                        }
                        if ($noOfUnitsAdded == 0) {
                            $productUnit->conditions = 0;
                            $productUnit->productid = $productid;
                            $productUnit->productnumber = 1;
                            $productUnit->productunitdate = $today;
                            $productUnit->unitid = 1;
                            $productUnit->userid = $_SESSION['userid'];

                            $productUnitDAO->insert($productUnit);
                        }
                        ##5-affectstore
                        addExcelProductStoredata($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, 1);
                        $did = $returnedData[1];

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

        unlink($inputFileName);
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}

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

    return $flag;
}

function checkbarcode($parcode, $productId = 0)
{
    global $productDAO;
    global $productExt;
    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 ($parcode <= $biggestParcode) {
            $parcodeResult = $availableParcodeDAO->queryByValue($parcode);
            if (isset($parcodeResult) && count($parcodeResult) > 0) {
                //if value in the table it is not repeated
                $flag = 2;
                return $flag;
            }
        }
    }

    //check if this parcode already exists in db
    $query = '';
    if ($productId > 0) {
        $query = " and productId != $productId ";
    }
    $data = $productExt->isParcodeRepated($parcode, $query);
    //$data = $productDAO->queryByParcode($parcode);
    $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 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 handleCats($CatName, $CatParent, $isOptic)
{
    global $productCatDAO;
    global $productCatExt;

    if ($CatParent == 0) {
        $catData = $productCatExt->queryByProductCatName($CatName);
    } else {
        $catData = $productCatExt->queryByProductCatNameEX($CatName, $CatParent);
    }

    if (count($catData) > 0) {
        $lastCatid = $catData[0]->productCatId;
    } else {
        $productCat->productCatName = $CatName;
        $productCat->productCatDescription = "";
        $productCat->productCatParent = $CatParent;
        $productCat->selldiscount = 0;
        $productCat->buydiscount = 0;
        $productCat->discounttype = 0;
        $productCat->isOptic = $isOptic;
        $productCat->userId = $_SESSION['userid'];
        $productCat->conditions = 0;
        $productCat->productCatDate = date("Y-m-d");
        $productCat->inMenu = 0;
        $productCat->buytotal = 0;
        $productCat->buyhalf = 0;
        $productCat->buypart = 0;
        $productCat->buypricereal = 0;
        $productCat->opticServices = '';
        $productCat->stopNegativeSale = 0;

        $lastCatid = $productCatDAO->insert($productCat);
        onlineTempCategoryFunc($lastCatid, 1);
    }
    return $lastCatid;
}

function addproductIngridients($proId)
{
    global $productIngredients;
    global $productIngredientsDAO;
    global $productIngredientsEX;

    $rowitr = $_POST["rowitr"];
    for ($i = 1; $i <= $rowitr; $i++) {

        if (isset($_POST["product" . $i]) && $_POST["product" . $i] != -1) {
            if (isset($_POST["unitId" . $i]) && !empty($_POST["unitId" . $i])) {
                $productIngredients->productId = $proId;
                $productIngredients->ingridientId = $_POST["product" . $i . ""];

                if (isset($_POST["inputt" . $i]) && !empty($_POST["inputt" . $i])) {
                    $productIngredients->quantity = $_POST["inputt" . $i];
                } else {
                    $productIngredients->quantity = 0;
                }
                $productIngredients->unitId = $_POST["unitId" . $i];
                $productIngredients->thedate = date("Y-m-d");
                $productIngredients->conditions = 0;
                $productIngredients->userId = $_SESSION['userid'];

                $productionRateProductId = $_POST["productionRateProductId" . $i];
                if (isset($productionRateProductId) && $productionRateProductId > 0) {
                    $productIngredients->id = $productionRateProductId;
                    $productIngredientsEX->insertwithid($productIngredients);
                } else {
                    $productIngredientsDAO->insert($productIngredients);
                }
            }
        }
    }
}

function ifCollectiveGetData($productId)
{
    global $productIngredients;
    global $productIngredientsDAO;
    global $productIngredientsEX;
    global $productUnitExt;
    global $productDAO;
    global $productExt;
    global $productCatDAO;
    global $smarty;
    //to edit collective pro get ingridients
    $ingridients = $productIngredientsEX->queryAllProductIngridientsEX($productId); //final name is product id that is collective
    if (count($ingridients) > 0) {
        $isCollective = 1;

        //Productunit
        $i = 1;
        foreach ($ingridients as $p) {
            $productUnitData = $productUnitExt->queryWithProductId($p->ingridientId);
            $smarty->assign("productUnitData" . $i, $productUnitData);
            $i++;
        }

        $product = $productDAO->load($productId);
        $productCat = $productCatDAO->load($product->productCatId);

        $smarty->assign("oldfinalproduct", ""); //$productionrate->finalName);
        $smarty->assign("oldfinalproductname", ""); //$product->productName . '/ ' . $productCat->productCatName);
        $rows = $productExt->GetRawMaterials();
        $smarty->assign("rows", $rows);

        $smarty->assign("noOfRows", count($ingridients));

        $smarty->assign("productionrate", "");
        $smarty->assign("Productionrateproduct", $ingridients);
    } else {
        $isCollective = 0;
    }
    $smarty->assign('isCollective', $isCollective);
}

function updateProductIngridients($proId)
{
    global $productIngredients;
    global $productIngredientsDAO;
    global $productIngredientsEX;

    //delete old ones in data base
    $productIngredientsDAO->deleteByProductId($proId);

    //insert
    addproductIngridients($proId);
}

function ifCollectiveDelProductionEquation($proId)
{
    global $productIngredientsDAO;
    //delete old ones in data base
    $productIngredientsDAO->deleteByProductId($proId);
}

//this gets length of parcode from program setting
function addPreDigitsToNum($num, $length = 7)
{
    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;
}

//this we pass length we need
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;
}

/////////////////////////////////////////////////////////////////
##for product and size color
function addProductSizeAndColor($productId, $buyprice, $sellunitprice)
{
    global $sizeColorStoreDetail;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $storeReportDAO;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $Programsettingdata;

    $sizeColorItr = (int) $_POST["sizeColorItr"];
    for ($i = 1; $i <= $sizeColorItr; $i++) {
        $size = (int) $_POST['size_detail' . $i];
        $color = (int) $_POST['color_detail' . $i];
        $parcode = $_POST['parcode_detail' . $i];
        $quantity = (int) $_POST['quantity_detail' . $i];

        if (!empty($size) && !empty($color)) {
            $parcodeToUse = addPreDigitsToNum($productId) . addPreDigitsToNum2($size, $Programsettingdata->sizecolorDigits) . addPreDigitsToNum2($color, $Programsettingdata->sizecolorDigits);
            if (!empty($parcode)) {
                $noOfRepeats = (int) $sizeColorStoreDetailEX->checkParcode($parcode);
                if ($noOfRepeats == 0) {
                    $parcodeToUse = $parcode;
                }
            }
            $sizeColorStoreDetail->storeid = 1;
            $sizeColorStoreDetail->productid = $productId;
            $sizeColorStoreDetail->sizeid = $size;
            $sizeColorStoreDetail->colorid = $color;
            $sizeColorStoreDetail->buyprice = $buyprice;
            $sizeColorStoreDetail->sellunitprice = $sellunitprice;
            $sizeColorStoreDetail->quantity = $quantity;
            $sizeColorStoreDetail->parcode = $parcodeToUse;
            $sizeColorStoreDetail->userid = $_SESSION['userid'];
            $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

            $id = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);

            //insert into storereport tbl
            $storeReport->processname = "إضافة منتج بمقاسات و الوان";
            $storeReport->productafter = $quantity;
            $storeReport->productbefore = 0;
            $storeReport->productquantity = $quantity;
            $storeReport->storeid = 1;
            $storeReport->storereportdate = date("Y-m-d");
            $storeReport->storereportmodelid = $productId;
            $storeReport->storereporttype = 0;
            $storeReport->tablename = "productController.php";
            $storeReport->userid = $_SESSION['userid'];
            $storeReport->productid = $productId;
            $storeReport->sizeid = $size;
            $storeReport->colorid = $color;

            $storeReportDAO->insert($storeReport);
        }
    }

    $storeid = 1;
    $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $storeid, 0);
    if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
        //insert into storedetail tbl
        $storeDetail->productid = $productId;
        $storeDetail->productquantity = 0;
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->storeid = $storeid;
        $storeDetail->userid = $_SESSION['userid'];

        $storeDetailData->storedetailid = $storeDetailDAO->insert($storeDetail);
    }
    $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productId);
}

function updateProductSizeAndColor($productId, $buyprice, $sellunitprice)
{
    global $sizeColorStoreDetail;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $storeReportDAO;
    global $Programsettingdata;

    $sizeColorItr = (int) $_POST["sizeColorItr"];

    //gather all ids of size color exist
    $sizeColorExist = '0,';
    for ($i = 1; $i <= $sizeColorItr; $i++) {

        $size = (int) $_POST['size_detail' . $i];
        $color = (int) $_POST['color_detail' . $i];
        $parcode = $_POST['parcode_detail' . $i];
        //        $id = (int) $_POST['sizecolorstoredetail_id' . $i];
        $sizeColorStoreDetail = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEXList($productId, $size, $color);
        if (count($sizeColorStoreDetail) > 0) {
            //data already exist no thing is available to change so do nothing.
            $oneId = 0;
            foreach ($sizeColorStoreDetail as $value) {
                $oneId = $value->id;
                $sizeColorExist .= $value->id . ',';
            }

            //updateParcode
            $parcodeToUse = addPreDigitsToNum($productId) . addPreDigitsToNum2($size, $Programsettingdata->sizecolorDigits) . addPreDigitsToNum2($color, $Programsettingdata->sizecolorDigits);
            if (!empty($parcode)) {
                $noOfRepeats = (int) $sizeColorStoreDetailEX->checkParcode($parcode, " and id != " . $oneId);
                if ($noOfRepeats == 0) {
                    $parcodeToUse = $parcode;
                }
            }
            $sizeColorStoreDetailEX->updateSizeColorParcodeInAllStores($parcodeToUse, $productId, $size, $color);
        } else {
            if (!empty($size) && !empty($color)) {
                $quantity = 0; //(int) $_POST['quantity_detail' . $i];
                $parcodeToUse = addPreDigitsToNum($productId) . addPreDigitsToNum2($size, $Programsettingdata->sizecolorDigits) . addPreDigitsToNum2($color, $Programsettingdata->sizecolorDigits);
                if (!empty($parcode)) {
                    $noOfRepeats = (int) $sizeColorStoreDetailEX->checkParcode($parcode);
                    if ($noOfRepeats == 0) {
                        $parcodeToUse = $parcode;
                    }
                }
                $sizeColorStoreDetail = new stdClass();
                $sizeColorStoreDetail->storeid = 1;
                $sizeColorStoreDetail->productid = $productId;
                $sizeColorStoreDetail->sizeid = $size;
                $sizeColorStoreDetail->colorid = $color;
                $sizeColorStoreDetail->buyprice = $buyprice;
                $sizeColorStoreDetail->sellunitprice = $sellunitprice;
                $sizeColorStoreDetail->quantity = $quantity;
                $sizeColorStoreDetail->parcode = $parcodeToUse;
                $sizeColorStoreDetail->userid = $_SESSION['userid'];
                $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");
                $id = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
                $sizeColorExist .= $id . ',';

                //insert into storereport tbl
                $storeReport->processname = "إضافة منتج بمقاسات و الوان";
                $storeReport->productafter = $quantity;
                $storeReport->productbefore = 0;
                $storeReport->productquantity = $quantity;
                $storeReport->storeid = 1;
                $storeReport->storereportdate = date("Y-m-d");
                $storeReport->storereportmodelid = $productId;
                $storeReport->storereporttype = 0;
                $storeReport->tablename = "productController.php";
                $storeReport->userid = $_SESSION['userid'];
                $storeReport->productid = $productId;
                $storeReport->sizeid = $size;
                $storeReport->colorid = $color;

                $storeReportDAO->insert($storeReport);
            }
        }
    }
    //to delete old size color not exist in new data
    $sizeColorExist = trim($sizeColorExist, ',');
    $sizeColorStoreDetailEX->deleteProductSizeColorWhereIdNotIn($productId, $sizeColorExist);
}

function ifHasSizeANDColorGetData($productsData)
{
    global $sizeColorStoreDetailEX;
    global $sizeColorDAO;
    global $smarty;

    $sizeColorStoreDetail = $sizeColorStoreDetailEX->queryByProductidEX($productsData->productId, " and storeid = 1 ");
    $smarty->assign('sizeColorStoreDetail', $sizeColorStoreDetail);

    $allSizeColor = $sizeColorDAO->queryByConditions(0);
    $smarty->assign("allSizeColor", $allSizeColor);
}

function avalableParcodes()
{
    global $Programsettingdata;
    global $availableParcodeEX;

    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }

    //check if it has rows
    $result = $availableParcodeEX->getFirstRow();
    //if no rows create parcodes
    if (!isset($result) || empty($result)) {
        ##write all parcodes possibilities
        $availableParcodeEX->createGenerateParcodesSP();
        $availableParcodeEX->callGenerateParcodesSP($Programsettingdata->parcodeDigits);
        ##remove used parcodes from possibilities ##edit line is also like this
        $availableParcodeEX->deleteUsedParcodesInproductTable();
    }
}

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

function addParcodeToImage($hiddenFileName, $oldHiddenFileName, $targetDir, $parcode)
{
    global $hosturl_f;

    $statusMsg = '';
    // Allow certain file formats//needed for image copy function
    $allowTypes = array('jpg', 'png', 'jpeg');
    if (!empty($_FILES[$hiddenFileName]["name"])) {
        // Path configuration
        //        $targetDir;//this is comming from user
        //        $watermarkImagePath
        //$parcodeImageURL = $hosturl_f . "/library/barcode2/barcode.php?text=$parcode&codetype=code128&size=30&print=true&sizefactor=1.1";
        $parcodeImageURL = "../library/barcode2/barcode.php?text=$parcode&codetype=code128&size=30&print=true&sizefactor=1.1";
        $parcodeImageName = $targetDir . md5(uniqid(mt_rand(), true)) . '.png';
        file_put_contents($parcodeImageName, file_get_contents($parcodeImageURL));
        $watermarkImagePath = $parcodeImageName;
        /////$image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/product_image');
        // File upload path
        $fileName = basename($_FILES[$hiddenFileName]["name"]);
        $targetFilePath = $targetDir . $fileName;
        $targetFilePathNewName = $targetDir . md5(uniqid(mt_rand(), true)) . '.png'; //create random name with png extention
        $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
        // Allow certain file formats
        if (in_array($fileType, $allowTypes)) {
            // Upload file to the server
            if (move_uploaded_file($_FILES[$hiddenFileName]["tmp_name"], $targetFilePathNewName)) {
                // Load the stamp and the photo to apply the watermark to
                $watermarkImg = imagecreatefrompng($watermarkImagePath);
                switch ($fileType) {
                    case 'jpg':
                        $im = imagecreatefromjpeg($targetFilePathNewName);
                        break;
                    case 'jpeg':
                        $im = imagecreatefromjpeg($targetFilePathNewName);
                        break;
                    case 'png':
                        $im = imagecreatefrompng($targetFilePathNewName);
                        break;
                    default:
                        $im = imagecreatefromjpeg($targetFilePathNewName);
                }

                // Set the margins for the watermark
                $marge_right = 0;
                $marge_bottom = 0;

                // Get the height/width of the watermark image
                $sx = imagesx($watermarkImg);
                $sy = imagesy($watermarkImg);

                // Copy the watermark image onto our photo using the margin offsets and
                // the photo width to calculate the positioning of the watermark.
                imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg));

                // Save image and free memory
                imagepng($im, $targetFilePathNewName);
                imagedestroy($im);
                if (file_exists($parcodeImageName)) {
                    unlink($parcodeImageName);
                }


                if ($oldHiddenFileName != '' && $oldHiddenFileName != '.' && $oldHiddenFileName != 'no image') {
                    $image = $targetDir . $oldHiddenFileName;
                    //                    file_put_contents($image, file_get_contents($hosturl_f . '/' . substr($targetFilePathNewName, 3)));
                    file_put_contents($image, file_get_contents('../' . substr($targetFilePathNewName, 3)));
                    if (file_exists($targetFilePathNewName)) {
                        unlink($targetFilePathNewName);
                    }
                    $targetFilePathNewName = $image;
                }


                if (file_exists($targetFilePathNewName)) {
                    $statusMsg = "The image with watermark has been uploaded successfully.";
                } else {
                    $statusMsg = "Image upload failed, please try again.";
                }
            } else {
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        } else {
            $statusMsg = 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.';
        }
    }
    return array($statusMsg, $targetFilePathNewName);
}

//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";
        $theImageURL = "../views/default/images/product_image/$imageName";
        $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 getTreeAccounts($parent, $selectedId)
{
    global $accountsTreeOrdered;
    global $smarty;

    $accountsTreeOrdered = array();
    orderAsTree($parent, 0);
    $myhtml = '<option value="0"> لا يوجد</option>';
    foreach ($accountsTreeOrdered as $element) {
        //draw level as dashes
        $preString = '';
        for ($index = 0; $index < $element->notes; $index++) {
            $preString .= '_';
        }

        $selectedAttr = '';
        if ($element->id == $selectedId) {
            $selectedAttr = 'selected';
        }
        $myhtml .= '<option value="' . $element->id . '"  ' . $selectedAttr . '>' . $preString . $element->layingOrder . ' ' . $element->name . '</option>';
    }
    $smarty->assign("myhtml", $myhtml);
}

function orderAsTree($parent, $level)
{
    global $accountsTreeDAO;
    global $accountsTreeEX;
    global $accountsTreeOrdered;
    //global $outputString;
    // retrieve all children of $parent
    $result = $accountsTreeEX->queryByParentExt($parent);
    if (count($result) > 0) {
        // display each child

        foreach ($result as $type) {
            $type->notes = $level;
            array_push($accountsTreeOrdered, $type);
            orderAsTree($type->id, $level + 1);
        }
    }
}
