HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/buyBillControllerAjax.php
<?php

//the global file operation
session_start();
ob_start();
//global varable
global $showoutside;

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

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

//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');
//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');
//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');
//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');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.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');
//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');
//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');
//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');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.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');
//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');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.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');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.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');
//get the do the action
$do = isset($_GET['do']) ? $_GET['do'] : '';

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

  Controller Name :- buyBillController

  OPERTATION in Controller

  1- add buy bill
  2-  تقرير لمورد معين

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

//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();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Supplier
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//Programsetting
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Productunit
$productUnitExt = new ProductunitMySqlExtDAO();
$productUnit = new Productunit();
$productUnitDAO = new ProductunitMySqlDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Billsetting
$billSettingExt = new BillsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport();
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();

//Productserial
$Productserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();


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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();

//User
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();
//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Billname
$billNameDAO = new BillnameMySqlDAO();
$billNameEX = new BillnameMySqlExtDAO();
//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();

$serialArray = array();


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

$do = isset($_GET['do']) ? $_GET['do'] : '';
$billnameid = isset($_GET['billnameid']) ? $_GET['billnameid'] : '';
$supplierId = isset($_GET['supplierid']) ? $_GET['supplierid'] : '';
$productId = isset($_GET['productid']) ? $_GET['productid'] : '';
$itr = isset($_GET['itrs']) ? $_GET['itrs'] : '';
$tabindex = isset($_GET['tabindex']) ? $_GET['tabindex'] : '';
$return = isset($_GET['return']) ? $_GET['return'] : '';

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

if (empty($do)) {
    if (!empty($supplierId) && $supplierId != "-1") {
        try {
            $rawmaterialssupplierdebt = getSupplierDebt();
            echo $rawmaterialssupplierdebt;
        } catch (Exception $e) {

        }
    } elseif (!empty($productId) && $productId != "-1" && $productId != "0" && (!empty($return) || $return == 0)) {
        try {
            $productPriceData = getBuyPrice();
            $itr = $productPriceData[0];
            $tabindex = $productPriceData[1];
            $productprice = $productPriceData[2];
            if ($return == 0) {
                echo '<input name="proprice' . $itr . '" id="proprice' . $itr . '"  value="0" class="getprototal  txt-nonraduis  numberclic enteraction numberinput" type="text"  tabindex="' . $tabindex . '"/>';
            } else {
                echo '<input name="proprice_re' . $itr . '" id="proprice_re' . $itr . '"  value="0" class="getprototal  txt-nonraduis  numberclic enteraction numberinput" type="text"  tabindex="' . $tabindex . '" />';
            }
        } catch (Exception $e) {

        }
    }
} elseif ($do == "units") {
    getProductUnits();
} elseif ($do == "unitPrice") {
    calculateUnitBuyPrice();
} elseif ($do == "parcode") {
    getProductByParcode();
} elseif ($do == "addplnew") {
    $detailid = $_REQUEST['detailid'];
    $buybilldetailpl = R::dispense('buybilldetailpl');
    $buybilldetailpl->buybilldetailid = $detailid;
    $buybilldetailpl->text1 = '';
    $buybilldetailpl->text2 = 0;
    $buybilldetailpl->text3 = '';
    $id = R::store($buybilldetailpl);
    $smarty->assign('id', $id);
    $smarty->assign('detailid', $detailid);
    $smarty->display("buyBillview/addplr.html");
} elseif ($do == "autosave") {
    $name = filter_input(INPUT_POST, 'name');
    $detailid = filter_input(INPUT_POST, 'detailid');
    $id = filter_input(INPUT_POST, 'id');
    $values = filter_input(INPUT_POST, 'values');
    R::exec("UPDATE `buybilldetailpl` SET $name = '$values', buybilldetailid = $detailid WHERE id = '" . $id . "' ");
} elseif ($do == "removepl") {
    $detailid = filter_input(INPUT_POST, 'detailid');
    $id = filter_input(INPUT_POST, 'id');
    R::exec("DELETE FROM `buybilldetailpl` WHERE id = '" . $id . "' ");
} elseif ($do == "printaddpl") {

    $buyBill_Id = $_GET['id'];


    $buybill = R::getRow("SELECT * FROM buybill where buybillid = ? ", [$buyBill_Id]);
    $supplier = R::getRow("SELECT * FROM supplier where supplierid = ? ", [$buybill['buybillsupplierid']]);
    $store = R::getRow("SELECT * FROM store where storeId = ? ", [$buybill['buybillstoreid']]);

    $buybilldetails = R::getAll("SELECT * FROM buybilldetail where buybillid = ? ", [$buyBill_Id]);


    $allitem = array();
    foreach ($buybilldetails as $buybilldetail) {
        $product = R::getRow("SELECT * FROM product where productId = ? ", [$buybilldetail['buybilldetailproductid']]);
        $unit = R::getRow("SELECT * FROM unit where unitId = ? ", [$buybilldetail['productunitid']]);
        $buybilldetailpls = R::getAll("SELECT * FROM buybilldetailpl where buybilldetailid = ? ", [$buybilldetail['buybilldetailid']]);
        $stayquantity = R::getcell("SELECT sum(text2) FROM buybilldetailpl where buybilldetailid = ? ", [$buybilldetail['buybilldetailid']]);
        $item = array(
            'buybilldetailid' => $buybilldetail['buybilldetailid'],
            'unitName' => $unit['unitName'],
            'buybilldetailquantity' => $buybilldetail['buybilldetailquantity'],
            'stayquantity' => $stayquantity,
            'productName' => $product['productName'],
            'weight' => $product['weight'],
            'origin' => $product['origin'],
            'hscode' => $product['hscode'],
            'buybilldetailpls' => $buybilldetailpls
        );
        array_push($allitem, $item);
    }


    $smarty->assign('buybill', $buybill);
    $smarty->assign('supplier', $supplier);
    $smarty->assign('store', $store);
    $smarty->assign('buybilldetails', $allitem);


    $smarty->display("buyBillview/printaddpl.html");
} elseif ($do == "temp") {
    if (!isset($_POST["erpDB"]) || empty($_POST["erpDB"])) {
        $billSettingsData = loadBillProperties($billnameid);
        $smarty->assign("billSettingsData", $billSettingsData);
    }

    try {
        insertTempProduct();
    } catch (Exception $e) {

    }
} elseif ($do == "editProduct") {
    editProduct();
} elseif ($do == "updateProduct") {
    $billSettingsData = loadBillProperties($billnameid);
    $smarty->assign("billSettingsData", $billSettingsData);

    try {
        updateProduct();
    } catch (Exception $e) {

    }
} elseif ($do == "getProducts") {
    $productsData = getProducts(); //undeleted products
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsnoservice") { //products that is not collective products"has no ingridients"
    $productsData = getProductsnoservice(); //undeleted products
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsnotcollective") { //products that is not collective products"has no ingridients"
    $productsData = getProductsnotcollective(); //undeleted products
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsQueryString") {
    $productsData = getProductsQueryString(); //undeleted products
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getProductsQueryStringnoservice") {
    $productsData = getProductsQueryStringnoservice(); //undeleted products
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getserail") {

    $generatedParcode = getserail();
    echo $generatedParcode;
} elseif ($do == "productAddModal") {
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

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

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

    $today = date("Y-m-d");
    $smarty->assign("today", $today);

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

    //
    $allSizeColor = $sizeColorDAO->queryAll();
    $smarty->assign("allSizeColor", $allSizeColor);

    $smarty->display("buyBillview/addProduct.html");
} elseif ($do == "productData") {
    getProductData();
} elseif ($do == "getProPriceUpdateModalData") {
    $productId = $_GET['id'];
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }
    $_GET['id'] = $productId;
    $newBuyPrice = (float) $_GET['newBuyPrice'];
    $smarty->assign("newBuyPrice", $newBuyPrice);


    $productsData = $productExt->loadExt($productId);
    $productsData->sumProductQuantity = (int) $productsData->sumProductQuantity;
    $smarty->assign("productsData", $productsData);

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

    //get units
    $unitsData = $unitDAO->queryByCondition(0);
    $smarty->assign("unitsData", $unitsData);

    $smarty->display("buyBillview/updateProPrices.html");
} elseif ($do == "updateProPriceOnlyFromModal") {
    $productId = (int) $_POST['productIdForPrices'];
    $productBuyPrice = $_POST['productBuyPrice1'];
    $productSellAllPrice = $_POST['productSellAllPrice1'];
    $productSellHalfPrice = $_POST['productSellHalfPrice1'];
    $productSellUnitPrice = $_POST['productSellUnitPrice1'];
    $productbuypricereal = $_POST['productbuypricereal1'];

    $productBuyPrice = round($productBuyPrice, $noOfDecimalPlaces);
    $productSellAllPrice = round($productSellAllPrice, $noOfDecimalPlaces);
    $productSellHalfPrice = round($productSellHalfPrice, $noOfDecimalPlaces);
    $productSellUnitPrice = round($productSellUnitPrice, $noOfDecimalPlaces);
    $productbuypricereal = round($productbuypricereal, $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);

    if (!empty($productId)) {
        $product = $productDAO->load($productId);
        //update product
        $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->userId = $_SESSION['userid'];
        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_withTax, $noOfDecimalPlaces);
            //            $product->meanbuyprice_withTax = round($meanbuyprice_withTax, $noOfDecimalPlaces);
        }

        #############
        $unitsItr = $_POST['unitsItr1'];
        for ($j = 1; $j <= $unitsItr; $j++) {
            $productunit = $_POST['productunit1' . $j];
            $productnumber = $_POST['productnumber1' . $j];
            $productunitid = (int) $_POST['productunitid' . $j];
            $proUnitParcode = $_POST['proUnitParcode1' . $j];
            $proUnitSellAllPrice = (float) $_POST['proUnitSellAllPrice1' . $j];
            $proUnitSellHalfPrice = (float) $_POST['proUnitSellHalfPrice1' . $j];
            $proUnitSellUnitPrice = (float) $_POST['proUnitSellUnitPrice1' . $j];
            $proUnitBuyPrice = (float) $_POST['proUnitBuyPrice1' . $j];

            if (!empty($productunitid)) {
                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;

                //insert into productunit tbl
                $productUnit = $productUnitDAO->load($productunitid);
                $productUnit->userid = $_SESSION['userid'];
                $productUnit->proUnitSellAllPrice = $proUnitSellAllPrice;
                $productUnit->proUnitSellHalfPrice = $proUnitSellHalfPrice;
                $productUnit->proUnitSellUnitPrice = $proUnitSellUnitPrice;
                $productUnit->proUnitBuyPrice = $proUnitBuyPrice;
                $productUnitDAO->update($productUnit);
            }
        }


        $product->productBuyPrice = $productBuyPrice;
        $productDAO->update($product);
    }
} elseif ($do == "getProductsHasSizeAndColor") { //products that is not collective products"has no ingridients"
    $productsData = getProductsHasSizeAndColor(); //undeleted products
    $smarty->assign("productsData", $productsData);
}

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

function generateParcode_old($length = 5) {
    global $productDAO;

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

    return $randomString;
}

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

function checkbarcode($parcode) {
    global $productDAO;
    global $Programsettingdata;
    global $availableParcodeDAO;
    $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
    $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 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 loadBillProperties($billnameid) {
    global $billSettingExt;

    // select all data from Billname
    $billSettingsData = $billSettingExt->queryWithBillnameId($billnameid);

    return $billSettingsData;
}

// get supplierdebt from supplier tbl
function getSupplierDebt() {
    global $supplierDAO;

    $supplierId = $_GET['supplierid'];

    // get supplierdebt by supplierid
    $supplierData = $supplierDAO->load($supplierId);
    if ($supplierData->sullpierCurrencyid == 1) {
        $supplierdebt = $supplierData->suppliercurrentDebt;
    } else {
        $supplierdebt = $supplierData->suppliercurrentDebtInCurrency;
    }

    return $supplierdebt;
}

// get productprice from product tbl
function getBuyPrice() {
    global $productDAO;
    global $productExt;
    global $productCatDAO;
    global $sizeColorStoreDetailEX;
    global $Programsettingdata;

    $productId = $_GET['productid'];
    $productunitid = (int) $_GET['productunitid'];
    $itr = $_GET['itrs'];
    $tabindex = $_GET['tabindex'];

    //for product hassizecolor
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
        }
    }

    if ($productunitid > 0) {
        $productprice = getBuyPriceFromUnitExt($productId, $productunitid);
    } else {
        $productprice = getBuyPriceExt($productId);
    }


    $price = $productprice;
    if ($Programsettingdata->useListPrice == 1) {
        $pData = $productExt->loadByProductId($productId);
        $listPercentage = $pData->buypricereal;
        $price = $price + (($price * $listPercentage) / 100);
        $productprice = $price;
    }
    return array($itr, $tabindex, $productprice);
}

function getBuyPriceExt($productId) {
    global $productDAO;
    global $productExt;
    global $productCatDAO;
    global $sizeColorStoreDetailEX;

    $productId = $_GET['productid'];

    //for product hassizecolor
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
        }
    }

    $productprice;
    //$buydiscount;
    //$discounttype;
    // get productprice by productid
    //$productData = $productDAO->load($productId);
    $productprice = $productExt->getProductBuyPriceById($productId);
    //		if(count($productData) > 0)
    //		{
    //			$productprice = $productData->productBuyPrice;
    //			$productCatId = $productData->productCatId;
    //
    //			/*** حساب خصم التصنيف من سعر المنتج ***/
    //			//get productCat data to get buydiscount and discounttype
    //			$catData = $productCatDAO->load($productCatId);
    //			if(count($catData) > 0)
    //			{
    //				$buydiscount = $catData->buydiscount;
    //				$discounttype = $catData->discounttype;
    //
    //				//
    //				if($discounttype == 0)//خصم مباشر
    //				{
    //					$productprice = $productprice - $buydiscount;
    //				}
    //				else //خصم نسبة
    //				{
    //					$productprice = $productprice - (($buydiscount / 100) * $productprice);
    //				}
    //			}
    /*     * *********************************** */
    //		}
    return $productprice;
}

function getBuyPriceFromUnitExt($productId, $productunitid) {
    global $productUnitDAO;
    global $productDAO;
    global $productExt;
    global $productCatDAO;
    global $sizeColorStoreDetailEX;

    $productId = $_GET['productid'];

    //for product hassizecolor
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
        }
    }

    //$productprice = $productExt->getProductBuyPriceById($productId);
    $productUnit = $productUnitDAO->load($productunitid);
    $productprice = $productUnit->proUnitBuyPrice;
    return $productprice;
}

function getProductUnits() {
    global $productUnitExt;
    global $unitString;
    global $priceString;
    global $tabindex;
    global $productDAO;
    global $sizeColorStoreDetailEX;
    global $billNameDAO;
    global $Programsettingdata;

    $productId = $_GET['productid'];
    $itr = $_GET['itrs'];
    $return = $_GET['return'];
    $supplier_id = (int) $_GET['supplier']; // this cast is needed as supplier now may not exist
    $billnameid = $_GET['billnameid'];
    $comingproserial = (int) $_GET['comingproserial']; //means user selct product by serial  from "productserial" table and we need parcode as it is
    $parcode = $_GET['parcode'];

    //for product hassizecolor
    $sizeColor;
    if (!empty($productId)) {
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColor = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeId, $colorId);
        }
    }


    if (!empty($productId) && !empty($itr) && empty($return)) {
        $productUnitData = $productUnitExt->queryWithProductIdAndCondition($productId);

        $unitString .= '<select name="unitId' . $itr . '" id="unitId' . $itr . '" onchange="getUnitPrice(' . $itr . ');"  data-placeholder="اختر" class="select2_unit' . $itr . ' aw_m1" >';
        $i = 0;
        foreach ($productUnitData as $unit) {
            $unitString .= '<option value="' . $unit->productunitid . '">' . $unit->unitName . '</option>';
            if ($i == 0) { //get buy price for the first unit only
                //buy price
                try {
                    // $buybilldetailData = getProductPriceFromBuyBill($productId, $supplier_id, $unit->productunitid);
                    // if (count($buybilldetailData[0]) > 0) {
                    //     $priceAfterUnit = $buybilldetailData[1];
                    //     //$priceString = '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $buybilldetailData[1] . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                    //     $priceString = '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                    //     $priceString .= '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                    // } else {

                    $productQty = getProductUnitQuantity($unit->productunitid);
                    $productPriceData = getBuyPrice();
                    $buyPriceBeforeUnit = $productPriceData[2];

                    $priceAfterUnit = $productQty * $buyPriceBeforeUnit; //عدد المنتجات في وحدة القياس * سعر شراء المنتج الواحد

                    $priceString = '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                    $priceString .= '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                    // }
                } catch (Exception $e) {
                    $priceString .= '<input name="proprice' . $itr . '" id="proprice' . $itr . '"  value="0" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"  tabindex="' . $tabindex . '"/>
                            <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                }
            }
            $i++;
        }
        $unitString .= ' </select>';
    } elseif (!empty($productId) && !empty($itr) && !empty($return)) {
        $productUnitData = $productUnitExt->queryWithProductIdAndCondition($productId);

        $unitString .= '<select name="unitId_re' . $itr . '" id="unitId_re' . $itr . '" onchange="return_getUnitPrice(' . $itr . ');"  data-placeholder="اختر" class="select2_unit_re' . $itr . ' aw_m1" >';
        $i = 0;
        foreach ($productUnitData as $unit) {
            $unitString .= '<option value="' . $unit->productunitid . '">' . $unit->unitName . '</option>';
            if ($i == 0) { //get buy price for the first unit only
                //buy price
                try {
                    $buybilldetailData = getProductPriceFromBuyBill($productId, $supplier_id, $unit->productunitid);
                    if (count($buybilldetailData[0]) > 0) {
                        $priceAfterUnit = $buybilldetailData[1];
                        //$priceString = '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $buybilldetailData[1] . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                        $priceString = '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                        $priceString .= '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                    } else {
                        $productQty = getProductUnitQuantity($unit->productunitid);

                        $productPriceData = getBuyPrice();
                        $buyPriceBeforeUnit = $productPriceData[2];

                        $priceAfterUnit = $productQty * $buyPriceBeforeUnit; //عدد المنتجات في وحدة القياس * سعر شراء المنتج الواحد
                    }
                    if ($return == 1) {
                        //$buybilldetailData = getProductPriceFromBuyBill($productId, $supplier_id, $unit->productunitid);
                        $priceString = '<input name="proprice_re' . $itr . '" id="proprice_re' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"   tabindex="' . $tabindex . '"/>';
                        //                        if (count($buybilldetailData[0]) > 0) {
                        //                            $priceString .= '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                        //                        } else {
                        $priceString .= '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                        //                        }
                    }
                } catch (Exception $e) {
                    $priceString .= '<input name="proprice_re' . $itr . '" id="proprice_re' . $itr . '"   value="0" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"  tabindex="' . $tabindex . '"/>
                             <input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                }
            }
            $i++;
        }
        $unitString .= ' </select>';
    }

    $productData = $productDAO->load($productId);
    $buypricereal_precentage = $productData->buypricereal_precentage;
    if ($comingproserial == 1) {
        $parcodeString = $parcode;
    } else {
        if (!is_null($sizeColor->id) && !empty($sizeColor->id)) {
            $parcodeString = $sizeColor->parcode;
        } else {
            $billnameData = $billNameDAO->load($billnameid);
            if ($billnameData->billnameid > 0 && (int) $billnameData->parcodeType == 1) {
                $parcodeString = useSpecializedParcodeDigits($productData->parcode, $productData->productId, $Programsettingdata->specializedParcodeDigits);
            } else {
                $parcodeString = $productData->parcode;
            }
        }
    }

    ////******************************************************///
    //get buy price

    $data = array('unitString' => $unitString, 'priceString' => $priceString, 'buypricereal_precentage' => $buypricereal_precentage, 'parcodeString' => $parcodeString);

    echo json_encode($data);
}

function calculateUnitBuyPrice() {
    $productunitid = $_GET['productunitid'];
    $productId = $_GET['productid'];
    $itr = $_GET['itrs'];
    $tabindex = $_GET['tabindex'];
    $return = $_GET['return'];
    $supplier_id = $_GET['supplier'];

    //print($productunitid."<br/>");

    if ($productunitid != '-1' && !empty($productunitid)) {
        try {

            if (empty($return)) {
                $buybilldetailData = getProductPriceFromBuyBill($productId, $supplier_id, $productunitid);

                if (count($buybilldetailData[0]) > 0) {
                    $priceAfterUnit = $buybilldetailData[1];
                    echo '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "1" size = "7" readonly />';
                } else {
                    $productQty = getProductUnitQuantity($productunitid);

                    $productPriceData = getBuyPrice();
                    $buyPriceBeforeUnit = $productPriceData[2];

                    //$priceAfterUnit = $productQty * $buyPriceBeforeUnit; //عدد المنتجات في وحدة القياس * سعر شراء المنتج الواحد
                    $priceAfterUnit = $buyPriceBeforeUnit; //it is now prounitbuyprice  "price in each unit no need to do *$productQty "
                    echo '<input name = "productpricetype' . $itr . '" id = "productpricetype' . $itr . '" type = "hidden" value = "0" size = "7" readonly />';
                }

                echo '<input name="proprice' . $itr . '" id="proprice' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text"  tabindex="' . $tabindex . '"/>';
            } elseif ($return == 1) {

                $productQty = getProductUnitQuantity($productunitid);

                $productPriceData = getBuyPrice();
                $buyPriceBeforeUnit = $productPriceData[2];

                //$priceAfterUnit = $productQty * $buyPriceBeforeUnit; //عدد المنتجات في وحدة القياس * سعر شراء المنتج الواحد
                $priceAfterUnit = $buyPriceBeforeUnit; //it is now prounitbuyprice  "price in each unit no need to do *$productQty "

                echo '<input name="proprice_re' . $itr . '" id="proprice_re' . $itr . '"   value="' . $priceAfterUnit . '" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text" tabindex="' . $tabindex . '" />';
            }
        } catch (Exception $e) {
            if (empty($return)) {
                echo '<input name="proprice' . $itr . '" id="proprice' . $itr . '"  value="0" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text" tabindex="' . $tabindex . '"/>';
            } elseif ($return == 1) {
                echo '<input name="proprice_re' . $itr . '" id="proprice_re' . $itr . '"   value="0" class="getprototal form-control txt-nonraduis  numberclic enteraction numberinput" type="text" tabindex="' . $tabindex . '"/>';
            }
        }
    }
}

function getProductUnitQuantity($productunitid) {
    global $productUnitDAO;
    $productQty = 1;
    if ($productunitid != '-1' && !empty($productunitid)) {
        $pUnitData = $productUnitDAO->load($productunitid);
        $productQty = $pUnitData->productnumber;
    }
    return $productQty;
}

function getProductByParcode() {
    global $productDAO;
    global $productExt;
    global $productCatDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailEX;
    global $ProductserialDAO;
    global $ProductserialEX;
    global $storeReportExt;
    global $Programsettingdata;
    $arr = array();
    $number = $_GET['parcode']; //It could be serial or parcode
    $storeid = (int) $_GET['store']; //It could be serial or parcode

    $productId = 0;

    // get productprice by productid
    //$productData = $productExt->queryWithSerialnumber($number);
    //print_r($productData);
    //if(count($productData) == 0)
    //{
    if ($number[0] == 'i' && $Programsettingdata->usedParcode == 1) { //usedParcode == 1 it is id coming after i
        $number = str_replace("i", "", $number);
        $productData = $productExt->loadProduct((int) $number);
    } else {
        $productData = $productExt->queryWithParcode($number);
    }
    //print_r($productData);
    if (count($productData) > 0 && $productData->hasSizeAndColor == 0) {
        $productId = $productData->productId;
        //pass variables as something that select2 can understand
        $arr['id'] = $productData->productId;
        $arr['text'] = $productData->productCatName . "/" . $productData->productName;
        if ($storeid > 0) {
            $storedetails = $storeDetailExt->getProductQuantity($productData->productId, $storeid);
            $arr['quantity'] = $storedetails->productquantity;
            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($productData->productId, $storeid, '');
            $arr['lastInventoryDate'] = $lastDate;
        }
    } else { //There is no products for this parcode
        //so check if it is producthassizecolor
        $sizeColor = $sizeColorStoreDetailEX->queryByParcodeEX($number);
        if ($sizeColor->id > 0) {
            $arr['id'] = "hasSizeColor" . $sizeColor->productid . "-" . $sizeColor->sizeid . "-" . $sizeColor->colorid;
            $arr['text'] = $sizeColor->productName . "/" . $sizeColor->productCatName . "/" . $sizeColor->sizeName . "/" . $sizeColor->colorName;
            if ($storeid > 0) {
                $storedetails = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2($sizeColor->productid, $storeid, $sizeColor->sizeid, $sizeColor->colorid);
                $arr['quantity'] = $storedetails->quantity;
                ///////////تاريخ آخر عملية إعادة جرد
                $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($sizeColor->productid, $storeid, " AND sizeid = $sizeColor->sizeid And colorid = $sizeColor->colorid ");
                $arr['lastInventoryDate'] = $lastDate;
            }
        } else {
            $productData = $productExt->queryWithProUnitParcode($_GET['parcode']);
            if (count($productData) > 0) {
                $productId = $productData->productId;
                //pass variables as something that select2 can understand
                $arr['id'] = $productData->productId;
                $arr['text'] = $productData->productCatName . "/" . $productData->productName;
                $arr['isProUnitParcode'] = 1; //parcode is ProUnitParcode
                $arr['productunitid'] = $productData->productunitid;
                $arr['unitid'] = $productData->unitid;
                $arr['proUnitBuyPrice'] = $productData->proUnitBuyPrice;
            } else {
                $productData = $productExt->queryWithSerialnumberEvenIfNotAvailable($_GET['parcode']); //Ex->queryLastWithProductIdAndSerial($sizeColor->productid,$parcode," and sizeid=$sizeColor->sizeid and colorid= $sizeColor->colorid ");
                if (count($productData) > 0 && $productData->hasSizeAndColor == 0) {
                    $productId = $productData->productId;
                    //pass variables as something that select2 can understand
                    $arr['id'] = $productData->productId;
                    $arr['text'] = $productData->productCatName . "/" . $productData->productName;
                } else {
                    $productData = $productExt->queryWithParcodeExcel($_GET['parcode']);
                    if (count($productData) > 0 && $productData->hasSizeAndColor == 0) {
                        $productId = $productData->productId;
                        //pass variables as something that select2 can understand
                        $arr['id'] = $productData->productId;
                        $arr['text'] = $productData->productCatName . "/" . $productData->productName;
                    } else {
                        $arr['id'] = 0;
                        $arr['text'] = 0;
                    }
                }
            }
        }
    }
    //}
    //		else
    //		{
    //				$productId = $productData->productId;
    //				//pass variables as something that select2 can understand
    //				$arr['id'] = $productData->productId;
    //				$arr['text'] = $productData->productName;
    //		}

    echo json_encode($arr);
}

function insertTempProduct() {
    global $product;
    global $productDAO;
    global $productExt;
    global $productUnit;
    global $productUnitDAO;
    global $productUnitExt;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeReport;
    global $storeReportDAO;
    global $productCatDAO;
    global $UsergroupDAO;
    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $sizeColorStoreDetailEX;
    global $billSettingExt;


    global $smarty;

    global $Programsettingdata;
    global $noOfDecimalPlaces;

    try {
        $itr = $_GET['itr'];
        $level = (int) $_POST['level'];
        $cat_id = $_POST['new_cat_id'];

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

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

                if (count($catData) > 0) {
                    $cat_id = $catData[0]->productCatId;
                } else {
                    $cat_id = addCatByNameOnly($catName);
                }
            }
        }
        #################################
        $hasSizeAndColor = (int) $_POST['hasSizeAndColor' . $i];


        $parcode = $_POST['new_parcode'];
        $productBuyPrice = $_POST['new_productBuyPrice'];
        $productSellAllPrice = $_POST['new_productSellAllPrice'];
        $productSellHalfPrice = $_POST['new_productSellHalfPrice'];
        $productSellUnitPrice = $_POST['new_productSellUnitPrice'];

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

        $productquantity = $_POST['new_productquantity'];
        $productDate = $_POST['new_productDate'];
        $tabIndex = $_GET['tabIndex'];
        $type1 = $_REQUEST["type1"];
        $expireDate = $_REQUEST["expireDate"];

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

        $productbuypricereal = $_POST['new_productbuypricereal'];
        $buypricereal_precentage = $_POST['new_buypricereal_precentage1'];
        $buytotal_precentage = $_POST['new_buytotal_precentage1'];
        $buyhalf_precentage = $_POST['new_buyhalf_precentage1'];
        $buypart_precentage = $_POST['new_buypart_precentage1'];
        $isservice = $_POST['new_isservice1'];

        $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);
        ###################################################################
        ##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
        }
        ###################################################################
        //echo "cat_id: ".$cat_id." productName: ".$productName;
        //insert into producttemp tbl
        $product->productbuypricereal = $productbuypricereal;
        $product->buypricereal_precentage = $buypricereal_precentage;
        $product->buytotal_precentage = $buytotal_precentage;
        $product->buyhalf_precentage = $buyhalf_precentage;
        $product->buypart_precentage = $buypart_precentage;
        $product->conditions = 0;
        $product->expireDate = $expireDate;
        $product->parcode = $parcode;
        $product->productBuyPrice = $productBuyPrice;
        $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->productCatId = $cat_id;
        $product->productDate = $productDate;
        $product->productName = $productName;
        $product->productSellAllPrice = $productSellAllPrice;
        $product->productSellHalfPrice = $productSellHalfPrice;
        $product->productSellUnitPrice = $productSellUnitPrice;
        $product->userId = $_SESSION['userid'];
        $product->limitamount = 1;
        $product->productDescription = '';
        $product->type = $type1;
        $product->dailyentryId = 0;
        $product->isService = $isservice;
        $product->isOptic = 0;
        $product->inMenu = 0;
        $product->obygyDetectionId = $detection_id;
        $product->obygyInvestigationId = $investigation_id;
        $product->hasSizeAndColor = $hasSizeAndColor;

        $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);
        }
        ##############################################################
        //echo "<br>";
        if (!empty($productId)) {
            $unitsItr = $_POST['unitsItr'];
            $Unitdone = 0;
            for ($i = 1; $i <= $unitsItr; $i++) {
                $productunit = $_POST['productunit' . $i];
                $productnumber = $_POST['productnumber' . $i];
                $proUnitParcode = $_POST['proUnitParcode' . $i];
                $proUnitSellAllPrice = (float) $_POST['proUnitSellAllPrice' . $i];
                $proUnitSellHalfPrice = (float) $_POST['proUnitSellHalfPrice' . $i];
                $proUnitSellUnitPrice = (float) $_POST['proUnitSellUnitPrice' . $i];
                $proUnitBuyPrice = (float) $_POST['proUnitBuyPrice' . $i];
                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;

                    //insert into producttempunit tbl
                    $productUnit->conditions = 0;
                    $productUnit->productnumber = $productnumber;
                    $productUnit->productid = $productId;
                    $productUnit->productunitdate = date("Y-m-d");
                    $productUnit->unitid = $productunit;
                    $productUnit->userid = $_SESSION['userid'];
                    $productUnit->proUnitParcode = $proUnitParcode;
                    $productUnit->proUnitSellAllPrice = $proUnitSellAllPrice;
                    $productUnit->proUnitSellHalfPrice = $proUnitSellHalfPrice;
                    $productUnit->proUnitSellUnitPrice = $proUnitSellUnitPrice;
                    $productUnit->proUnitBuyPrice = $proUnitBuyPrice;

                    $productUnitDAO->insert($productUnit);
                    $Unitdone = 1;
                }
            }

            if ($Unitdone == 0) {


                //insert into producttempunit tbl
                $productUnit->conditions = 0;
                $productUnit->productnumber = 1;
                $productUnit->productid = $productId;
                $productUnit->productunitdate = date("Y-m-d");
                $productUnit->unitid = 1;
                $productUnit->userid = $_SESSION['userid'];
                $productUnit->proUnitParcode = addPreDigitsToNum2($productId, 5) . addPreDigitsToNum2($productUnit->unitid, 2);
                $productUnit->proUnitSellAllPrice = $product->productSellAllPrice;
                $productUnit->proUnitSellHalfPrice = $product->productSellHalfPrice;
                $productUnit->proUnitSellUnitPrice = $product->productSellUnitPrice;
                $productUnit->proUnitBuyPrice = $product->productBuyPrice;

                $productUnitDAO->insert($productUnit);
            }

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

            $storeDetailDAO->insert($storeDetail);

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

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

//            $productsData = $productExt->queryAllExt();
//            $smarty->assign("productsData", $productsData);

            if ($product->hasSizeAndColor == 1) { //منتج بمقاسات و الوان
                addProductSizeAndColor($productId, $productBuyPrice, $productSellUnitPrice);
            }

            //get units associated with this producttempid
            $unitsData = $productUnitExt->queryWithProductIdAndCondition($productId);
            $smarty->assign("unitsData", $unitsData);

            //get Buy price
            $productprice = getBuyPriceExt($productId);
        }

        if ($product->hasSizeAndColor == 1) { //منتج بمقاسات و الوان
            //change data to get first size color
            $sizeColor = $sizeColorStoreDetailEX->queryByProductidEX($productId);
            if (count($sizeColor) > 0) {
                $productId = "hasSizeColor" . $sizeColor[0]->productid . "-" . $sizeColor[0]->sizeid . "-" . $sizeColor[0]->colorid;
                $parcode = $sizeColor[0]->parcode;
                if (!is_null($sizeColor[0]->sizeName) && !empty($pro->sizeName)) {
                    $productName .= '/' . $sizeColor[0]->sizeName;
                }
                if (!is_null($sizeColor[0]->colorName) && !empty($pro->colorName)) {
                    $productName .= '/' . $sizeColor[0]->colorName;
                }
            }
        }


        //write in the xml file
        //createXMLFile();

        $usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
        $smarty->assign("usergroup", $usergroup);

        $billnameid = (int) $_GET['billnameid'];
        $billsettingsData = $billSettingExt->queryWithBillnameId($billnameid);
        $smarty->assign("billsettingsData", $billsettingsData);

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

        $smarty->assign("productId", $productId);
        $smarty->assign("parcode", $parcode);
        $smarty->assign("productBuyPrice", $productprice);
        $smarty->assign("productName", $productName);
        $smarty->assign("cat_id", $cat_id);
        $smarty->assign("itr", $itr);
        $smarty->assign("tabIndex", $tabIndex);
        $smarty->assign("proprice", $productBuyPrice);
        $smarty->assign("hasSizeColor", $product->hasSizeAndColor);

        if (!isset($_POST["erpDB"]) || empty($_POST["erpDB"])) {
            $smarty->display("buyBillview/product.html");
        }
    } catch (Exception $e) {
        echo $e;
        echo "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);

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

    //go back to your db
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $sessionDBName;
        unset($_SESSION['userid']); //tempppppppppppppppp
    }
}

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 editProduct() {
    global $product;
    global $productDAO;
    global $productExt;
    global $productUnit;
    global $productUnitDAO;
    global $productUnitExt;
    global $smarty;
    $productprice;

    $productId = $_GET['id'];
    $itr = $_GET['itr'];
    $tabIndex = $_GET['tabIndex'];

    if (!empty($productId) && $productId != '-1') {
        $productData = $productExt->loadProductExt($productId);
        if (count($productData) > 0) {
            $smarty->assign("productData", $productData);

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

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

            //get product units
            $productUnitsData = getProductUnitsById($productId);
            $smarty->assign("productUnitsData", $productUnitsData);
            $unitsItr = count($productUnitsData);

            $smarty->assign("itr", $itr);
            $smarty->assign("tabIndex", $tabIndex);
            $smarty->assign("unitsItr", $unitsItr);

            $smarty->display("buyBillview/editProduct.html");
        } else {
            echo "1"; //ERROR: البرنامج لم يستطع الوصول لبيانات المنتج ... الرجاء المحاولة مرة أخرى
        }
        //print_r($productData);
    }
    //print_r($productData);
}

function updateProduct() {
    global $product;
    global $productDAO;
    global $productExt;
    global $productUnit;
    global $productUnitDAO;
    global $productUnitExt;
    global $smarty;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $storeReport;
    global $storeReportDAO;

    try {
        $itr = $_GET['itr'];
        $productId = $_POST['productId'];
        $cat_id = $_POST['new_cat_id'];
        $productName = $_POST['new_productName'];
        $parcode = $_POST['new_parcode'];
        $productBuyPrice = $_POST['new_productBuyPrice'];
        $productSellAllPrice = $_POST['new_productSellAllPrice'];
        $productSellHalfPrice = $_POST['new_productSellHalfPrice'];
        $productSellUnitPrice = $_POST['new_productSellUnitPrice'];
        $productquantity = $_POST['new_productquantity'];
        $productDate = $_POST['new_productDate'];
        $tabIndex = $_GET['tabIndex'];
        $storedetailid = $_POST['storedetailid'];
        $product_qty_before = $_POST['product_qty_before'];
        $storeid = $_POST['storeid'];

        $product = $productDAO->load($productId);
        ##check for barcode
        $flag = checkbarcode($parcode);
        if ($flag == 1) {
            //parcode is repeated get another one
            $parcode = generateParcode();
        }
        removeParcodeFromTable($parcode, $product->parcode);
        //echo "cat_id: ".$cat_id." productName: ".$productName;
        //insert into producttemp tbl
        $product->conditions = 0;
        $product->parcode = $parcode;
        $product->productBuyPrice = $productBuyPrice;
        $product->productCatId = $cat_id;
        $product->productDate = $productDate;
        $product->productName = $productName;
        $product->productSellAllPrice = $productSellAllPrice;
        $product->productSellHalfPrice = $productSellHalfPrice;
        $product->productSellUnitPrice = $productSellUnitPrice;
        $product->userId = $_SESSION['userid'];
        $product->limitamount = 1;
        $product->productDescription = '';
        $product->productId = $productId;
        //$product->productquantity = $productquantity;
        $product->inMenu = 0;
        $productDAO->update($product);

        if (!empty($productId)) {
            //delete product units
            $productUnitDAO->deleteByProductid($productId);

            $unitsItr = $_POST['unitsItr'];
            for ($i = 1; $i <= $unitsItr; $i++) {
                $productunit = $_POST['productunit' . $i];
                $productnumber = $_POST['productnumber' . $i];
                if (!empty($productunit) && $productunit != '-1' && !empty($productnumber)) {
                    //insert into producttempunit tbl
                    $productUnit->conditions = 0;
                    $productUnit->productnumber = $productnumber;
                    $productUnit->productid = $productId;
                    $productUnit->productunitdate = date("Y-m-d");
                    $productUnit->unitid = $productunit;
                    $productUnit->userid = $_SESSION['userid'];

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

            //update quantity in storedetail tbl
            $storeDetail->productquantity = $productquantity;
            $storeDetail->userid = $_SESSION['userid'];
            $storeDetail->storedetailid = $storedetailid;
            $storeDetail->storedetaildate = date("Y-m-d");

            $storeDetailExt->updateProductquantity($storeDetail);

            //insert into storereport tbl
            if ($product_qty_before > $productquantity) {
                $storeReport->storereporttype = 1; //minus
                $storeReport->productquantity = $product_qty_before - $productquantity;
            } else {
                $storeReport->storereporttype = 0; //plus
                $storeReport->productquantity = $productquantity - $product_qty_before;
            }
            $storeReport->processname = "تعدبل منتج في فاتورة الشراء";
            $storeReport->productafter = $productquantity;
            $storeReport->productbefore = $product_qty_before;
            $storeReport->productid = $productId;

            $storeReport->storeid = $storeid;
            $storeReport->storereportdate = date("Y-m-d");
            $storeReport->storereportmodelid = $productId;
            $storeReport->tablename = "productController.php";
            $storeReport->userid = $_SESSION['userid'];

            $storeReportDAO->insert($storeReport);

            $productsData = $productExt->queryAllExt();
            $smarty->assign("productsData", $productsData);

            //get units associated with this producttempid
            $unitsData = $productUnitExt->queryWithProductIdAndCondition($productId);
            $smarty->assign("unitsData", $unitsData);

            //get Buy price
            $productprice = getBuyPriceExt($productId);
        }
        $smarty->assign("productId", $productId);
        $smarty->assign("parcode", $parcode);
        $smarty->assign("productBuyPrice", $productprice);
        $smarty->assign("productName", $productName);
        $smarty->assign("cat_id", $cat_id);
        $smarty->assign("itr", $itr);
        $smarty->assign("tabIndex", $tabIndex);

        $smarty->display("buyBillview/product.html");
    } catch (Exception $e) {
        echo "1"; //Error
    }
}

function getProductCatParents() {
    global $productCatExt;
    global $productExt;

    $allParents = $productExt->queryAllCategories();
    return $allParents;
}

function getUnits() {
    global $unitDAO;

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

function getProductUnitsById($productId) {
    global $productUnitDAO;
    global $productUnitExt;
    global $unitDAO;

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

function getProducts() {
    global $productExt;
    global $productCatDAO;
    global $productDAO;
    global $smarty;
    global $Programsettingdata;

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

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }

    /* 		if (file_exists('productXML.xml')) {
      $xml = simplexml_load_file('productXML.xml');
      ////			print("<pre>");
      ////			print_r($xml);
      ////			print("</pre>");
      $product = $xml->product;
      for($i=0; $i <= count($xml); $i++)
      {
      $productPath = $product[$i]->path;
      if(strpos($productPath, $name) !== false)
      {
      //send product id and product name as something that select2 expects.
      $row_array['id'] = (string)$product[$i]->id;
      $row_array['text'] = (string)$product[$i]->path;

      array_push($return_arr,$row_array);
      }
      }

      }
     */

    $productsData = $productExt->queryByNameExtWithoutLimit($name, '', 1, ' limit ' . $limit);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

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

            array_push($return_arr, $row_array);
        }
    }

    //		print("<pre>");
    //		print_r($return_arr);
    //		print("</pre>");
    echo json_encode($return_arr);
}

function getProductsnoservice() { //products that is not collective products"has no ingridients"
    global $productExt;
    global $productCatDAO;
    global $productDAO;
    global $userDAO;
    global $Programsettingdata;
    global $smarty;

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

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }
    $controlNameSearch = (int) $_REQUEST["searchWithCatAndProductNameOnly"]; //0 search catname,proname only //1 search sizename,colorname too

    /* 		if (file_exists('productXML.xml')) {
      $xml = simplexml_load_file('productXML.xml');
      ////			print("<pre>");
      ////			print_r($xml);
      ////			print("</pre>");
      $product = $xml->product;
      for($i=0; $i <= count($xml); $i++)
      {
      $productPath = $product[$i]->path;
      if(strpos($productPath, $name) !== false)
      {
      //send product id and product name as something that select2 expects.
      $row_array['id'] = (string)$product[$i]->id;
      $row_array['text'] = (string)$product[$i]->path;

      array_push($return_arr,$row_array);
      }
      }

      }
     */
    $storeid = $_GET['storeid'];

    $storeidQSJoin = '';
    if (((int) $storeid) > 0)
        $storeidQSJoin = ' and storedetail.storeid= ' . ((int) $storeid);
    $stopStoreSearch = (int) $_GET['stopStoreSearch'];
    if ($stopStoreSearch == 0) {
        if (!isset($storeid) || empty($storeid)) {
            $userData = $userDAO->load($_SESSION['userid']);
            $storeid = $userData->userstoreid;
        }

        $storeidQS = '';
        if (!empty($storeid)) {
            $storeidQS = " and storedetail.storeid=" . $storeid . " ";
        }
    } else {
        $storeidQS = ''; //search in all stores
    }
    //$productsData = $productExt->queryByNameExtWithoutLimitNoService($name, $storeidQS);
    //products without production rate,means no collective products
    $productsData = $productExt->queryByNameExtWithoutLimitNoServiceNotCollective($name, $storeidQS, $storeidQSJoin, $controlNameSearch, ' limit ' . $limit);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            $price = $pro->productBuyPrice;
            if ($Programsettingdata->useListPrice == 1) {
                $listPercentage = $pro->buypricereal;
                $price = $price + (($price * $listPercentage) / 100);
            }

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }
            $row_array['price'] = $price; //$pro->productBuyPrice;
            $row_array['productquantity'] = (float) $pro->productquantity;

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            array_push($return_arr, $row_array);
        }
    }

    //		print("<pre>");
    //		print_r($return_arr);
    //		print("</pre>");
    echo json_encode($return_arr);
}

function getProductsnotcollective() { //products that is not collective products"has no ingridients"
    global $productExt;
    global $productCatDAO;
    global $productDAO;
    global $userDAO;
    global $Programsettingdata;
    global $smarty;

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

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }
    $controlNameSearch = (int) $_REQUEST["searchWithCatAndProductNameOnly"]; //0 search catname,proname only //1 search sizename,colorname too


    $storeid = $_GET['storeid'];

    $storeidQSJoin = '';
    if (((int) $storeid) > 0)
        $storeidQSJoin = ' and storedetail.storeid= ' . ((int) $storeid);
    $stopStoreSearch = (int) $_GET['stopStoreSearch'];
    if ($stopStoreSearch == 0) {
        if (!isset($storeid) || empty($storeid)) {
            $userData = $userDAO->load($_SESSION['userid']);
            $storeid = $userData->userstoreid;
        }

        $storeidQS = '';
        if (!empty($storeid)) {
            $storeidQS = " and storedetail.storeid=" . $storeid . " ";
        }
    } else {
        $storeidQS = ''; //search in all stores
    }
    //$productsData = $productExt->queryByNameExtWithoutLimitNoService($name, $storeidQS);
    //products without production rate,means no collective products
    $productsData = $productExt->queryByNameExtWithoutLimitNotCollective($name, $storeidQS, $storeidQSJoin, $controlNameSearch, ' limit ' . $limit);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            $price = $pro->productBuyPrice;
            if ($Programsettingdata->useListPrice == 1) {
                $listPercentage = $pro->buypricereal;
                $price = $price + (($price * $listPercentage) / 100);
            }

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }
            $row_array['price'] = $price; //$pro->productBuyPrice;
            $row_array['productquantity'] = (float) $pro->productquantity;
            $row_array['buydiscountpercent'] = (float) $pro->buydiscountpercent;

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;
            if ($_GET['searchColorSize'] == 1 && $pro->hasSizeAndColor == 0) {
                continue;
            }
            array_push($return_arr, $row_array);
        }
    }

    //		print("<pre>");
    //		print_r($return_arr);
    //		print("</pre>");
    echo json_encode($return_arr);
}

function getProductsQueryString() {
    global $storeDetailExt;
    global $productExt;
    global $productCatDAO;
    global $productDAO;
    global $smarty;
    global $Programsettingdata;

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

    $storeId = $_GET['storeid'];
    $productId = $_GET['productid'];
    $catId = $_GET['catid'];

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }

    $queryString = ' WHERE';

    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' storedetail.storeId = ' . $storeId . ' AND';
    }
    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        $queryString .= ' productcat.productCatId = ' . $catId . ' AND';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        //get product by id
        $queryString .= ' storedetail.productid = ' . $productId . ' AND';
    }

    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>".$queryString."<br>");
    }



    $productsData = $storeDetailExt->queryProductsInInventoryExt2($queryString, ' limit ' . $limit);

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

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

            array_push($return_arr, $row_array);
        }
    }


    echo json_encode($return_arr);
}

function getProductsQueryStringnoservice() {
    global $storeDetailExt;
    global $productExt;
    global $productCatDAO;
    global $productDAO;
    global $smarty;
    global $Programsettingdata;

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

    $storeId = $_GET['storeid'];
    $productId = $_GET['productid'];
    $catId = $_GET['catid'];

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }

    $queryString = ' WHERE';

    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' storedetail.storeId = ' . $storeId . ' AND';
    }
    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        // or statment is for optic product that has size or color
        $queryString .= ' (productcat.productCatId = ' . $catId . ' || productcat.productCatId in (select productCatId from productcat where productCatParent = ' . $catId . ')) AND';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        //get product by id
        $queryString .= ' storedetail.productid = ' . $productId . ' AND';
    }
    if (isset($name) && !empty($name)) {
        //get product by id
        $queryString .= ' CONCAT(product.productName, "/",  productcat.productCatName) LIKE "%' . $name . '%" AND';
    }

    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>".$queryString."<br>");
    }



    $productsData = $storeDetailExt->queryProductsInInventoryExt2NoService($queryString, ' limit ' . $limit);

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

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) { //has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productid . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else { //without size and color
                $row_array['id'] = $pro->productid;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            array_push($return_arr, $row_array);
        }
    }


    echo json_encode($return_arr);
}

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

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

function getProductData() {
    global $productDAO;
    global $sizeColorStoreDetailEX;
    $row_array = array();
    $id = $_GET['id'];

    if (!empty($id) && $id != '-1') {
        $sizeColor;
        if (strpos($id, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $id));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizeColor = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorEX($productId, $sizeId, $colorId);

            $productData = $productDAO->load($productId);
        } else {
            $productData = $productDAO->load($id);
        }
        ##fatma
        $parentId = $productData->productCatId;
        //names of product's parents
        $pathString = fetch_recursive($parentId, $categories);
        ##
        $row_array['id'] = $id;
        $row_array['text'] = $pathString . '/' . $productData->productName;
        if (!is_null($sizeColor->sizeName) && !empty($sizeColor->sizeName)) {
            $row_array['text'] .= '/' . $sizeColor->sizeName;
        }
        if (!is_null($sizeColor->colorName) && !empty($sizeColor->colorName)) {
            $row_array['text'] .= '/' . $sizeColor->colorName;
        }
    }
    echo json_encode($row_array);
}

function getserail($length = 6) {
    global $Productserial;
    global $ProductserialEX;
    global $ProductserialDAO;

    //global $serialArray;

    $serialArray = $_SESSION["serialarray"];

    //print_r($serialArray);

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

    //print_r('randomString'.$randomString."<br>");
    //check if this parcode already exists
    $data = $ProductserialEX->queryAllbyserialandproductid($randomString, $productid);
    if (count($data) > 0) {

        //print_r('in if <br>');
        getserail();
    } elseif (in_array($randomString, $serialArray)) {
        //print_r('in elseif <br>');
        getserail();
    }

    /* if(in_array($randomString, $_SESSION["serialarray"]))
      {
      generateParcode();
      } */

    $serialArray[] = $randomString;
    $_SESSION["serialarray"] = $serialArray;

    return $randomString;
}

function getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

function getProductPriceFromBuyBill($ProductId, $supplier_id, $productunitid) {
    //to use the variable out side the funcion
    global $buyBillDetailExt;
    global $buyAndReturnBillDetailExt;

    $sellbilldetailPrice;
    $detailData = array();

    // get rawmaterialprice by rawmaterialid
    $sellbilldetailData = $buyBillDetailExt->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $supplier_id, $productunitid);

    $sellandruternbilldetailData = $buyAndReturnBillDetailExt->queryPriceWithProductIdAndClientIdAndUnit($ProductId, $supplier_id, $productunitid, 0);

    if (count($sellbilldetailData) > 0 && count($sellandruternbilldetailData) > 0) {
        //number of days
        $dayNum = round(abs(strtotime($sellbilldetailData->buybilldate) - strtotime($sellandruternbilldetailData->buybilldate)));

        if ($dayNum >= 0) {
            $sellbilldetailPrice = $sellbilldetailData->buybilldetailprice;
            $detailData = $sellbilldetailData;
        } else {
            $sellbilldetailPrice = $sellandruternbilldetailData->buybilldetailprice;
            $detailData = $sellandruternbilldetailData;
        }
    } elseif (count($sellbilldetailData) > 0 && count($sellandruternbilldetailData) <= 0) {
        $detailData = $sellbilldetailData;
        $sellbilldetailPrice = $sellbilldetailData->buybilldetailprice;
    } elseif (count($sellbilldetailData) <= 0 && count($sellandruternbilldetailData) > 0) {
        $detailData = $sellandruternbilldetailData;

        $sellbilldetailPrice = $sellandruternbilldetailData->buybilldetailprice;
    } else {
        $detailData = array();
    }




    return array($detailData, $sellbilldetailPrice);
}

function addCatByNameOnly($catName) {
    global $productCatDAO;
    global $productCat;
    global $catUnit;
    global $catUnitDAO;
    $today = date('Y-m-d');
    $productCat->productCatName = $catName;
    $productCat->productCatDate = $today;
    $productCat->productCatDescription = '';
    $productCat->productCatParent = 0;
    $productCat->userId = $_SESSION['userid'];
    $productCat->conditions = 0;
    $productCat->selldiscount = 0;
    $productCat->buydiscount = 0;
    $productCat->discounttype = -1;
    $productCat->isOptic = 0;
    $productCat->inMenu = 0;
    $productCat->buytotal = 0;
    $productCat->buyhalf = 0;
    $productCat->buypart = 0;
    $productCat->buypricereal = 0;
    $productCat->opticServices = '';
    $productCat->logo = '';
    $productCatId = $productCatDAO->insert($productCat);
    onlineTempCategoryFunc($productCatId, 1);

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

function addPreDigitsToNum($num) {
    global $Programsettingdata;

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


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

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

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

        if (!empty($size) && !empty($color)) {
            $sizeColorStoreDetail->storeid = 1;
            $sizeColorStoreDetail->productid = $productId;
            $sizeColorStoreDetail->sizeid = $size;
            $sizeColorStoreDetail->colorid = $color;
            $sizeColorStoreDetail->buyprice = $buyprice;
            $sizeColorStoreDetail->sellunitprice = $sellunitprice;
            $sizeColorStoreDetail->quantity = $quantity;
            $sizeColorStoreDetail->parcode = addPreDigitsToNum($productId) . addPreDigitsToNum($size) . addPreDigitsToNum($color);
            $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;

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

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

################################################################################
//this 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;
}

function getProductsHasSizeAndColor() { //products that is not collective products"has no ingridients"
    global $productExt;
    global $Programsettingdata;

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

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //(int)$_GET['page_limit'];
    if (empty($limit)) {
        $limit = 30;
    }
    $productsData = $productExt->queryByNameExtHasColorAndSize($name, ' limit ' . $limit);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            array_push($return_arr, $row_array);
        }
    }
    echo json_encode($return_arr);
}