<?php

session_start();
ob_start();
//the global file operation
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("add2SimpleReturn");

include("initiateStaticSessionCommingWithCurl.php");
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    array_push($ajaxDoArr, $do);
}


if (!in_array($do, $ajaxDoArr)) {
    //the global file operation
    include("../public/impOpreation.php");
}

include("reportfunctions.php");

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.php");
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Productcatunit
require_once('../models/dao/ProductcatunitDAO.class.php');
require_once('../models/dto/Productcatunit.class.php');
require_once('../models/mysql/ProductcatunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatunitMySqlExtDAO.class.php');
//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');

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

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');




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

$langs = $_SESSION['erp_lang'];

include_once("../views/languages/$langs/productCat/productCat.php");
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

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

  Controller Name :- productCatController

  OPERTATION in Controller

  1-display add form
  2- add in productCat tble
  4-display sucess or error
  5-display show and delete
  6-delete from productCat tbl
  7-display edit
  8- update productCat tbl
  ======================== */

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("header.html");
    }
}

//here goes the instances and general variables
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Product
$productDAO = new ProductMySqlDAO();
$ProductEX = new ProductMySqlExtDAO();


//Productcatunit
$catUnit = new Productcatunit();
$catUnitDAO = new ProductcatunitMySqlDAO();
$catUnitExt = new ProductcatunitMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();

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

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

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

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

//print_r($Programsettingdata);
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check


    $allParents = getProductCatParents();
    //    $smarty->assign("allParents", $allParents);
    ##التصنيفات
    //$catDataReport = getCategoryChilds();
    //$smarty->assign("catDataReport", $catDataReport[1]);
    //    $allCat = $productCatDAO->queryAll();
    //
    //    $smarty->assign("catDataReport", $allCat);
    $smarty->assign("categories", $allParents);



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


    $smarty->assign("customProductCat", 1);
    $smarty->display("productCatview/add.html");
} elseif ($do == "add") {

    $flag = $_GET['flag'];
    try {
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            if (!empty($flag) && $flag == "addproduct") {
                header("location:productController.php");
            } else {
                header("location:?do=sucess");
            }
        }
    } catch (Exception $e) {
        //echo $e;
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "add2") {

    $flag = $_GET['flag'];
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "add2SimpleReturn") {
    try {
        $id = add();
        echo $id;
    } catch (Exception $e) {
        echo -1;
        //header("location:?do=error");
    }
} elseif ($do == "addCat") {

    //from add product page
    try {
        addCat();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {


    //$allData = $productCatDAO->queryByCondition(0); //not deleted
    $allData = $productCatExt->queryByConditionEX(0);
    $smarty->assign("allData", $allData);
    $catId = $_REQUEST['catId'];
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    if (isset($catId) && !empty($catId) && $catId != '-1') {
        showByCatId($catId);
    } else {
        show();
    }
    $smarty->display("productCatview/show.html");
    $smarty->assign('customUsergroup', 1);

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

        $smarty->assign("customCheck", 1);
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "returndelete") { //returndelete
    try {
        returndelete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") { //tempdelete
    try {
        $note = tempdelete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
                echo 1;
            } else {
                header("location:?do=sucess");
            }
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deleteFinaly") { //tempdelete
    try {
        $productCatid = (int) $_GET['id'];
        deleteFinaly($productCatid);

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "editprint") { //edit  productCat
    $allParents = getProductCatParents();
    $smarty->assign("allParents", $allParents);

    $productCatData = edit();
    $smarty->assign("productCatData", $productCatData);

    if (count($productCatData) > 0) {
        $catUnitsData = getProductCatUnits($productCatData->productCatId);
        $smarty->assign("catUnitsData", $catUnitsData);
        $smarty->assign("countcatUnits", count($catUnitsData));
    }
    //get units
    $unitsData = getUnits();
    $smarty->assign("unitsData", $unitsData);
    $smarty->display("productCatview/editprint.html");
} elseif ($do == "edit") { //edit  productCat
    $productCatid = $_GET['id'];
    $allParents = getProductCatParents($productCatid);
    $smarty->assign("allParents", $allParents);
    $parentid = $_GET['parentid'];
    if ($parentid) {
        $productCatparent = $productCatDAO->load($parentid);
        $smarty->assign("productCatparent", $productCatparent);
    }
    $smarty->assign("parentid", $parentid);
    //    $allCat = $productCatDAO->queryAll();
    //    $categories = array();
    //    foreach ($allCat as $Cat) {
    //        $productCatParent = R::count('productcat', 'productCatParent = ? and conditions = 0 ', [$Cat->productCatId]);
    //        $product = R::count('product', 'productCatId = ? and conditions = 0', [$Cat->productCatId]);
    //        if (($productCatParent + $product) == 0 && $Cat->conditions == 0) {
    //            array_push($categories, $Cat);
    //        }
    //    }
    //    $smarty->assign("catDataReport", $allCat);
    //    $smarty->assign("categories", $categories);
    $smarty->assign("categories", $allParents);

    $productCatData = edit();
    $smarty->assign("productCatData", $productCatData);

    if (count($productCatData) > 0) {
        $catUnitsData = getProductCatUnits($productCatData->productCatId);
        $smarty->assign("catUnitsData", $catUnitsData);
        $smarty->assign("countcatUnits", count($catUnitsData));
    }
    //get units
    $unitsData = getUnits();
    $smarty->assign("unitsData", $unitsData);

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

    $smarty->display("productCatview/edit.html");
} elseif ($do == "update") { //edit update
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}


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

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

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

function getUnits() {
    global $unitDAO;

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

function getProductCatUnits($productCatId) {
    global $catUnitExt;

    $productCatUnitData = $catUnitExt->queryByProductCatidExt($productCatId);
    return $productCatUnitData;
}

function getProductCatParents($productCatid = 0) {
    global $productCatDAO;
    global $productCatExt;

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

// add in productCat tbl
function add() {
    global $productCatDAO;
    global $productCat;
    global $catUnit;
    global $catUnitDAO;
    global $today;

    $productCatName = $_POST['productCatName'];
    $inMenu = (int) $_POST['inMenu'];
    $stopNegativeSale = (int) $_POST['stopNegativeSale'];
    $productCatDescription = $_POST['productCatDescription'];
    $parent = (int) $_POST['parent'];

    $discounttype = (int) $_POST['discounttype'];
    $selldiscount = (float) $_POST['selldiscount'];
    $buydiscount = (float) $_POST['buydiscount'];
    $buytotal = (int) $_POST['buytotal'];
    $buyhalf = (int) $_POST['buyhalf'];
    $buypart = (int) $_POST['buypart'];
    $buypricereal = (int) $_POST['buypricereal'];
    $opticServices = $_POST["opticServices"];
    $obygyInvestigationCatId = (int) $_POST["obygyInvestigationCatId"];
    $price4 = (int) $_POST['price4'];
    $price5 = (int) $_POST['price5'];
    $price6 = (int) $_POST['price6'];
    $price7 = (int) $_POST['price7'];
    $price8 = (int) $_POST['price8'];
    $price9 = (int) $_POST['price9'];
    $price10 = (int) $_POST['price10'];
    $price11 = (int) $_POST['price11'];
    $price12 = (int) $_POST['price12'];
    $price13 = (int) $_POST['price13'];


    //choose erpDB user has choosen in obygy_app
    $erpDB = $_POST["erpDB"];
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = 1; //tempppppppppppppppp
        //get parent
        $catData = $productCatDAO->queryByProductCatName('Investigations'); //'obygy Investigations'
        if (count($catData) > 0) {
            $parent = $catData[0]->productCatId;
        } else {
            $parent = addCatByNameOnly('Investigations'); ////'obygy Investigations'
        }
    }
    #################################



    if (empty($parent) || $parent == -1) {
        $parent = 0;
    }
    if (empty($selldiscount)) {
        $selldiscount = 0;
    }
    if (empty($buydiscount)) {
        $buydiscount = 0;
    }
    if (empty($discounttype)) {
        $discounttype = 0;
    }
    $productCat->discounttype = $discounttype;
    $productCat->selldiscount = $selldiscount;
    $productCat->buydiscount = $buydiscount;

    $productCat->conditions = 0;
    $productCat->isOptic = 0;
    $productCat->productCatDate = $today;
    $productCat->productCatDescription = $productCatDescription;
    $productCat->productCatName = $productCatName;
    $productCat->inMenu = $inMenu;
    $productCat->stopNegativeSale = $stopNegativeSale;
    $productCat->productCatParent = $parent;
    $productCat->obygyInvestigationCatId = $obygyInvestigationCatId;
    $productCat->userId = $_SESSION['userid'];

    $productCat->buytotal = $buytotal;
    $productCat->buyhalf = $buyhalf;
    $productCat->buypart = $buypart;
    $productCat->buypricereal = $buypricereal;
    $productCat->price4 = $price4;
    $productCat->price5 = $price5;
    $productCat->price6 = $price6;
    $productCat->price7 = $price7;
    $productCat->price8 = $price8;
    $productCat->price9 = $price9;
    $productCat->price10 = $price10;
    $productCat->price11 = $price11;
    $productCat->price12 = $price12;
    $productCat->price13 = $price13;

    $choosedServices = '';
    foreach ($opticServices as $value) {
        $choosedServices .= $value . ",";
    }
    $choosedServices = rtrim($choosedServices, ",");
    $productCat->opticServices = $choosedServices;
    $productCat->webApiId = (int) $_POST['webApiId'];


    $handle = new upload($_FILES['logo']);
    $image = uploadImages2($handle, '../views/default/images/cat_image');
    $productCat->logo = $image;
    //print_r($productCat);
    $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;
}

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

    $productCatData = $productCatExt->queryAllForShow();
    $smarty->assign('productCatData', $productCatData);
}

function showByCatId($catId) {
    global $productCatDAO;
    global $productCatExt;
    global $today;
    global $smarty;

    $productCatData = $productCatExt->loadExt($catId);
    $smarty->assign('productCatData', $productCatData);
}

function executeOperation() {
    global $productDAO;
    global $productCatDAO;
    global $productCatExt;
    global $productCat;
    global $smarty;

    global $outputString;

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

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $productCatId) {
            //get product category name
            $productCatData = $productCatDAO->load($productCatId);

            $productCatName = $productCatData->productCatName;

            if ($operationType == '1') { //tempdelete
                try {
                    $note = tempdelete($productCatId);
                    if ($note != "success") {
                        $outputString .= $productCatName . ": " . $note . "<br/>";
                    } else {
                        $outputString .= $productCatName . ": تمت العملية بنجاح<br/>";
                    }
                } catch (Exception $e) {

                }
            } elseif ($operationType == "2") {
                try {
                    returndelete($productCatId);

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

function tempdelete($productCatid) {
    global $productDAO;
    global $ProductEX;
    global $productCatDAO;
    global $productCatExt;
    global $productCat;
    global $smarty;

    //choose erpDB user has choosen in obygy_app
    $erpDB = $_POST["erpDB"];
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = 1; //tempppppppppppppppp
    }
    #################################

    if (empty($productCatid)) {
        $productCatid = $_GET['id'];
    }

    if (!empty($productCatid)) {

        //1- check if there are any products associated with this category
        $productsData = $ProductEX->queryByProductCatIdExt($productCatid);
        //2- check if there are any child category for this parent category
        $childCategories = $productCatDAO->queryByProductCatParent($productCatid);
        //if(count($productsData) > 0 || count($childCategories) > 0)
        if (count($productsData) > 0 || count($childCategories) > 0) {
            $note = "لا يمكن حذف هذا التصنيف لارتباطه ببيانات أخرى";
        } else {
            try {
                $productCat->productCatId = $productCatid;
                $productCat->productCatDate = date("Y-m-d");
                $productCat->userId = $userID;
                $productCat->conditions = 1;
                $productCatExt->updateConditions($productCat);
                onlineTempCategoryFunc($productCatid, 2);
                $note = "success";
                //header("location:?do=sucess");
            } catch (Exception $e) {
                $note = "حدثت مشكلة أثناء إجراء العملية ... يرجى المحاولة مرة أخرى";
            }
        }
    }
    return $note;
}

function returndelete($productCatid) {
    global $productCatExt;

    if ($productCatid == "") {
        $productCatid = $_GET['id'];
    }

    //return delete from productCat tbl
    $productCatExt->returndelete($productCatid);
    onlineTempCategoryFunc($productCatid, 1);
}

function edit() {
    global $productCatDAO;

    $productCatid = $_GET['id'];
    $productCatData = $productCatDAO->load($productCatid);
    //to make strpos of smarty works fine
    //as occurance at index zero makes it like not fount to it
    $productCatData->opticServices = "," . $productCatData->opticServices;
    return $productCatData;
}

function update() {
    global $productCat;
    global $productCatExt;
    global $productCatDAO;
    global $catUnit;
    global $catUnitDAO;
    global $today;

    $productCatId = $_POST['productCatId'];
    $productCat = $productCatDAO->load($productCatId);
    $conditions = $_POST['conditions'];
    $productCatName = $_POST['productCatName'];
    $inMenu = (int) $_POST['inMenu'];
    $stopNegativeSale = (int) $_POST['stopNegativeSale'];
    $productCatDescription = $_POST['productCatDescription'];
    $parent = $_POST['parent'];

    $discounttype = (int) $_POST['discounttype'];
    $selldiscount = (float) $_POST['selldiscount'];
    $buydiscount = (float) $_POST['buydiscount'];

    $buytotal = (int) $_POST['buytotal'];
    $buyhalf = (int) $_POST['buyhalf'];
    $buypart = (int) $_POST['buypart'];
    $buypricereal = (int) $_POST['buypricereal'];
    $opticServices = $_POST["opticServices"];

    $price4 = (int) $_POST['price4'];
    $price5 = (int) $_POST['price5'];
    $price6 = (int) $_POST['price6'];
    $price7 = (int) $_POST['price7'];
    $price8 = (int) $_POST['price8'];
    $price9 = (int) $_POST['price9'];
    $price10 = (int) $_POST['price10'];
    $price11 = (int) $_POST['price11'];
    $price12 = (int) $_POST['price12'];
    $price13 = (int) $_POST['price13'];


    //choose erpDB user has choosen in obygy_app
    $erpDB = $_POST["erpDB"];
    if (isset($erpDB) && !empty($erpDB)) {
        $_SESSION['dbname'] = $erpDB;
        $_SESSION['userid'] = 1; //tempppppppppppppppp
        //get conditions
        $conditions = $productCat->conditions;
        //get parent
        $catData = $productCatDAO->queryByProductCatName('Investigations'); //'obygy Investigations'
        if (count($catData) > 0) {
            $parent = $catData[0]->productCatId;
        } else {
            $parent = addCatByNameOnly('Investigations'); //'obygy Investigations'
        }
    }
    #################################


    if (empty($parent) || $parent == -1) {
        $parent = 0;
    }

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


    $productCat->productCatDate = $today;
    $productCat->productCatDescription = $productCatDescription;
    $productCat->productCatName = $productCatName;
    $productCat->inMenu = $inMenu;
    $productCat->stopNegativeSale = $stopNegativeSale;
    $productCat->productCatParent = $parent;
    $productCat->userId = $_SESSION['userid'];
    $productCat->productCatId = $productCatId;
    $productCat->conditions = $conditions;

    $productCat->buytotal = $buytotal;
    $productCat->buyhalf = $buyhalf;
    $productCat->buypart = $buypart;
    $productCat->buypricereal = $buypricereal;

    $productCat->price4 = $price4;
    $productCat->price5 = $price5;
    $productCat->price6 = $price6;
    $productCat->price7 = $price7;
    $productCat->price8 = $price8;
    $productCat->price9 = $price9;
    $productCat->price10 = $price10;
    $productCat->price11 = $price11;
    $productCat->price12 = $price12;
    $productCat->price13 = $price13;

    $choosedServices = '';
    foreach ($opticServices as $value) {
        $choosedServices .= $value . ",";
    }
    $choosedServices = rtrim($choosedServices, ",");
    $productCat->opticServices = $choosedServices;

    $handle = new upload($_FILES['logo']);
    $image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/cat_image');
    $productCat->logo = $image;
    $productCatDAO->update($productCat);
    onlineTempCategoryFunc($productCatId, 1);
    if (!empty($productCatId)) {
        //1- delete all product unit associated with this product
        $catUnitDAO->deleteByProductcatid($productCatId);

        //2- insert product units again with the new ones if any
        $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);
            }
        }
    }
}

function deleteFinaly($productCatid) {
    global $productCatDAO;
    global $productCatExt;
    global $productDAO;
    global $productEX;



    $prodactcatdata = $productCatExt->queryByParentExt($productCatid);

    if (count($prodactcatdata) > 0) {
        foreach ($prodactcatdata as $myprodactcatdata) {

            deleteFinaly($myprodactcatdata->productCatId);
        }

        $deldata = $productDAO->deleteByProductCatId($productCatid);
        $delcatdata = $productCatDAO->delete($productCatid);
        onlineTempCategoryFunc($productCatid, 2);

        //print_r('deldata'.$deldata.'<br>');
        //print_r('delcatdata'.$delcatdata.'<br>');
    } else {

        $deldata = $productDAO->deleteByProductCatId($productCatid);
        $delcatdata = $productCatDAO->delete($productCatid);
        onlineTempCategoryFunc($productCatid, 2);

        //print_r('deldata'.$deldata.'<br>');
        //print_r('delcatdata'.$delcatdata.'<br>');
    }




    /* print_r('<pre>');
      print_r($prodactcat);
      print_r('<pre>'); */
}

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 = '';

    $productCat->price4 = 0;
    $productCat->price5 = 0;
    $productCat->price6 = 0;
    $productCat->price7 = 0;
    $productCat->price8 = 0;
    $productCat->price9 = 0;
    $productCat->price10 = 0;
    $productCat->price11 = 0;
    $productCat->price12 = 0;
    $productCat->price13 = 0;

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

    return $productCatId;
}
