<?php

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

//global varable
global $showoutside;

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

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

//Breadcrumb
require_once("../library/breadcrumb.php");

include_once("dailyentryfun.php");

//get the do the action

$do = $_GET['do'];

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

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

  Controller Name :-storeCTRL

  OPERTATION in Controller

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

//here the global templates
if ($do != "print") {
    $smarty->display("header.html");
}


//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();


//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

// insurancecompanies
$insuranceCompanies = new Insurancecompanie();
$insuranceCompaniesDAO = new InsurancecompaniesMySqlDAO();


//paymentnetworks
$paymentNetworks = new Paymentnetwork();
$paymentNetworksDAO = new PaymentnetworksMySqlDAO();

//Store
$myStoreRecord = new StoreMySqlDAO();

//doctorkashf
$doctorKashf = new Doctorkashf();
$doctorKashfDAO = new DoctorkashfMySqlDAO();
$doctorKashfEX = new DoctorkashfMySqlExtDAO();


$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailEX = new StoredetailMySqlExtDAO();

$mySave = new Save();
$mySaveDAO = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();



//Dailyentry
$dailyEntry = new Dailyentry();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();

$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();

//bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();

//billsproducts
$billsReturnProducts = new Billsreturnproduct();
$billsReturnProductsDAO = new BillsreturnproductsMySqlDAO();
$billsReturnProductsEX = new BillsreturnproductsMySqlExtDAO();

$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
$myClientdebtchangeEx = new ClientdebtchangeMySqlExtDAO();



$userdata = $userDAO->load($_SESSION['userid']);
$smarty->assign("userdata", $userdata);


//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
//$transactions = new Transaction();
//Breadcrumb
$breadcrumbObject = new Breadcrumb();

//create object from user
## dispaly  add form
if (!isset($_GET['do']) || $_GET['do'] == "empty") {
    include_once("../public/authentication.php");

    ## stores
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);


    $smarty->display("billsreturnview/add.html"); //the template page
}

#######
elseif ($_GET['do'] == "add") {
    include_once("../public/authentication.php");
//    add();
    try {
        add();
        //$transactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //$transactions->rollback();
        header("location:?do=error");
    }
}

#######
elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

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

    $clientData = getClientData();
    $smarty->assign('clientData', $clientData);

    $billsNo = $billsEX->getAllBillNoDistinct();
    $smarty->assign('billsNo', $billsNo);


    $smarty->display("billsreturnview/show.html");
}


## delete bill
elseif ($_GET['do'] == "delete") {
    include_once("../public/authentication.php");

    $billsReturnId = filter_input(INPUT_GET, "id");
    $billsReturn = $billsReturnDAO->load($billsReturnId);


    $billsReturn->deleted = 1;
    try {
        $billsReturnDAO->update($billsReturn);
        reverseEntryWithItsID($billsReturn->dailyentryid);
        $billsReturnProducts = $billsReturnProductsEX->queryByReturnbillidAndDeleted($billsReturn->id, 0);
        $storeId = $userdata->userstoreid;
        foreach ($billsReturnProducts as $productR) {
            $productNum = $productR->productno;
            $storeDetail = $storeDetailEX->getProductQuantity($productR->productid, $storeId);
            $productbefore = $storeDetail->productquantity;
            $productafter = $productbefore - $productNum;
            $storeDetail->productquantity = $productafter;
            $storeDetailDAO->update($storeDetail);
            insertStorereportupdate($productR->productid, $storeId, $productNum, $productbefore, $productafter, 1, $billsReturnId, "حذف مرتجع فاتورة مبيعات", "billsreturn.php", date('Y-m-d'));
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}

#######
elseif ($_GET['do'] == "edit") {
    include_once("../public/authentication.php");
    $billsReturnId = filter_input(INPUT_GET, "id");

    $billsReturn = $billsReturnDAO->load($billsReturnId);
    $smarty->assign('billsReturn', $billsReturn);

    $otherBillReturn = $billsReturnEX->returnedpriceSumExcept($billsReturnId, $billsReturn->billid);

    ## stores
    $storeData = loadStore();
    $smarty->assign("storeData", $storeData);

    getBillDetails($billsReturn->billid, $billsReturnId, $otherBillReturn->returnedprice, $billsReturn->returnedprice);



    $smarty->display("billsreturnview/edit.html"); //the template page
}

#######
elseif ($_GET['do'] == "update") {
    include_once("../public/authentication.php");
//    update();
    try {
        update();
        //$transactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //$transactions->rollback();
        header("location:?do=error");
    }
}

## show bill details
elseif ($_GET['do'] == "details") {
    include_once("../public/authentication.php");

    $billsReturnId = filter_input(INPUT_GET, "id");
    $billsReturn = $billsReturnDAO->load($billsReturnId);
    $smarty->assign('billsReturn', $billsReturn);
    $otherBillReturn = $billsReturnEX->returnedpriceSumExcept($billsReturnId, $billsReturn->billid);
    getBillDetails($billsReturn->billid, $billsReturnId, $otherBillReturn->returnedprice, $billsReturn->returnedprice);
    $smarty->display("billsreturnview/bdetails.html"); //the template page
}


##
elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
}

##
elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}


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

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

function getBillDetails($billId, $billsReturnId, $otherReturnedPrice, $currentReturnedPrice) {
    global $smarty;
    global $clientDAO;
    global $billsDAO;
    global $doctorKashfDAO;
    global $billsReturnProductsEX;

    #
    #
    ## bill data
    $bill = $billsDAO->load($billId);

    ## client name
    $client = $clientDAO->load($bill->clientid);
    $bill->clientname = $client->clientname;

    ## bill kashf
    $kashf = $doctorKashfDAO->load($bill->kashfid);
    $smarty->assign("kashf", $kashf);

    ## bill products
    getBillProducts($bill->id, $billsReturnId);

    $billRetNoObj = $billsReturnProductsEX->getNoOfReturnedProductsWithbillsReturnId($billId, 0, $billsReturnId);  ##عدد القطع المرتجعة   لهذا ال مرتجع فقط
    $billRetNo = $billRetNoObj->productno;
    $smarty->assign("billRetNo", $billRetNo);


    $bill->finalnetbillvalue = $bill->finalnetbillvalue - $otherReturnedPrice;     ##اجمالى الفاتورة
    $bill->netbillvalue = $bill->finalnetbillvalue - $currentReturnedPrice;                     ##الصافى
    ## bill
    $smarty->assign("bill", $bill);
}

function getBillProducts($billId, $billsReturnId) {
    global $productDAO;
    global $productCatDAO;
    global $billsProductsEX;
    global $billsReturnProductsEX;
    global $smarty;

    $billProducts = $billsProductsEX->queryByBillIdAndDeleted($billId, 0);
    $i = 1;
    $categories;
    if (count($billProducts) > 0) {
        foreach ($billProducts as $pro) {
            $product = $productDAO->load($pro->productid);
            $parentId = $product->productCatId;
            $pathArr = getProductPath_recursive($parentId, $categories);
            $pro->productName = $product->productName . '/' . $pathArr;

            $productReturnedExcept = $billsReturnProductsEX->queryByBillIdAndProductidAndDeletedExcept($billId, $pro->id, $pro->productid, 0, $billsReturnId);
            $productReturnedWith = $billsReturnProductsEX->queryByBillIdAndProductidAndDeletedAndbillsReturnId($billId, $pro->id, $pro->productid, 0, $billsReturnId);

            $pro->netproductno = 0;     ##         العدد الصافى
            $pro->retproductno = 0;     ##    عدد المرتجع سابقا
            if ($productReturnedWith->productno) {
                $pro->retno = $productReturnedWith->productno;
                $pro->retprice = $productReturnedWith->productno * $productReturnedWith->productprice;
            } else {
                $pro->retno = 0;
                $pro->retprice = 0;
            }

            if (count($productReturnedExcept) > 0) {
                foreach ($productReturnedExcept as $retPro) {
                    $pro->retproductno = $pro->retproductno + $retPro->productno;
                }
            }
            $pro->netproductno = $pro->productno - $pro->retproductno;
            $pro->producttotalprice = $pro->netproductno * $pro->productprice;
        }
    }

    $smarty->assign("billProducts", $billProducts);
    $smarty->assign("billProductsCount", count($billProducts));
}

function getClientData() {
    global $clientExt;

    $alldata = $clientExt->queryAllsup();
    return $alldata;
}

function loadStore() {
    global $myStoreRecord;

    // select all data from Storetbl
    $storeData = $myStoreRecord->queryByConditions(0);
    return $storeData;
}

function add() {
    $billsReturnId = saveBillDetails();
    saveBillProducts($billsReturnId);
    saveDailyEntry($billsReturnId);
}

function saveBillDetails() {
    global $billsReturn;
    global $billsReturnDAO;
    global $client;
    global $clientDAO;
    global $bills;
    global $billsDAO;
    global $mySaveDAO;

    $billId = filter_input(INPUT_POST, "billId");
    $discValue = filter_input(INPUT_POST, "discValue");
    $clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue");

    $bills = $billsDAO->load($billId);

    $billsReturn->billid = $billId;
    $billsReturn->returnedprice = $discValue;
    $billsReturn->clientreceivevalue = $clientReceiveValue;
    $billsReturn->date = date("Y-m-d H:i:s");
    $billsReturn->deleted = 0;
    $billsReturn->userid = $_SESSION['userid'];
    $billsReturn->branchid = $_SESSION['branchId'];
    $billsReturnId = $billsReturnDAO->insert($billsReturn);
    return $billsReturnId;
}

function saveBillProducts($billsReturnId) {
    global $billsProductsDAO;
    global $billsReturnProducts;
    global $billsReturnProductsDAO;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailEX;

    $itr = filter_input(INPUT_POST, "hidden_itr");
    for ($i = 1; $i <= $itr; $i++) {
        $billProductId = filter_input(INPUT_POST, 'product' . $i);
        $productNum = filter_input(INPUT_POST, 'retnum' . $i);
        $storeId = filter_input(INPUT_POST, 'storeid');
        $productPrice = filter_input(INPUT_POST, 'proprice' . $i);
        $totalProductPrice = filter_input(INPUT_POST, 'totalRetPrice' . $i);

        $billsProducts = $billsProductsDAO->load($billProductId);

        if ($billProductId && $billProductId != -1 && $productNum > 0) {

            $billsReturnProducts->returnbillid = $billsReturnId;
            $billsReturnProducts->productid = $billsProducts->productid;
            $billsReturnProducts->productno = $productNum;
            $billsReturnProducts->productprice = $productPrice;
            $billsReturnProducts->producttotalprice = $totalProductPrice;
            $billsReturnProducts->billproductid = $billProductId;
            $billsReturnProducts->deleted = 0;
            $detailId = $billsReturnProductsDAO->insert($billsReturnProducts);
            lastAndMeanBuyPrice_RetOptic($detailId, $billsProducts->productid);

            $storeDetail = $storeDetailEX->getProductQuantity($billsProducts->productid, $storeId);
            $productbefore = $storeDetail->productquantity;
            $productafter = $productbefore + $productNum;
            $storeDetail->productquantity = $productafter;
            $storeDetailDAO->update($storeDetail);
            insertStorereportupdate($billsProducts->productid, $storeId, $productNum, $productbefore, $productafter, 0, $billsReturnId, "مرتجع فاتورة مبيعات", "billsreturn.php", date('Y-m-d'));
        }
    }
}

function updateClientDebt($clientid, $clientdebtAfter) {
    //to use the variable out side the funcion
    global $client;
    global $clientExt;

    //update clientdebt in client tbl
    $client->userid = $_SESSION['userid'];
    $client->clientdebt = $clientdebtAfter;
    $client->clientid = $clientid;

    $clientExt->updateClientdebt($client);
}

// insert data into Clientdebtchange tbl
function insertClientdebtchangeupdate($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost, $mydate) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = $mydate; //date("Y-m-d");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->userid = $_SESSION['userid'];
    $myClientdebtchange->totalOperationCost = $totalOperationCost;
    $myClientdebtchange->dailyentryid = 0;

    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

//add in Storemovement tbl
function insertStorereportupdate($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $mydate) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = $mydate;
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

function saveDailyEntry($billsReturnId) {
    global $dailyEntry;      ## Dailyentry
    global $accountsTreeDAO;
    global $mySave;
    global $mySaveDAO;
    global $billsReturn;
    global $billsReturnDAO;
    global $bills;
    global $billsDAO;
    global $client;
    global $clientDAO;

    $mytransactions = new Transaction();
    $billsReturn = $billsReturnDAO->load($billsReturnId);
    $bills = $billsDAO->load($billsReturn->billid);

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

    $dailyEntry->dDateTime = date('Y-m-d h:i:s');
    $dailyEntry->entryComment = 'مرتجع فاتورة ';
    $dailyEntry->fromFlag = 2;
    $dailyEntry->reverseofid = -9;

//#########################################################################################

    $discValue = filter_input(INPUT_POST, "discValue");                         ## total returned price
    $clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue");       ## value received by client in cash
    $clientDeptChangeValue = $discValue - $clientReceiveValue;                  ## value removed  from client dept
    //#################################### deptors #####################################################
    $dailyEntryDebtor->value = $discValue;
    $dailyEntryDebtor->accountstreeid = 16;
    $dailyEntryDebtor->pluginControllerName = "billsreturn.php";
    $dailyEntryDebtor->pluginComment = "أضافة مرتجع كشف بصاريات";

    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

    //#################################### creditors #####################################################
    if ($clientReceiveValue > 0) {
        $saveId = $_SESSION['saveid'];
        $mySave = $mySaveDAO->load($saveId);

        if ($mySave->treeId > 0) {
            $treeId2 = $mySave->treeId;
        } else {
            $treeId2 = addTreeElement($mySave->savename, 20, 3, 0, 1, '', 0, 0);
        }

        $dailyEntryCreditor->value = $clientReceiveValue;
        $dailyEntryCreditor->accountstreeid = $treeId2;
        $dailyEntryCreditor->pluginControllerName = "billsreturn.php";
        $dailyEntryCreditor->pluginComment = "أضافة مرتجع كشف بصاريات";
        $dailyEntryCreditor->pluginid = $billsReturnId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
    }

    if ($clientDeptChangeValue > 0) {
        $clientId = $bills->clientid;
        $client = $clientDAO->load($clientId);

        if ($client->treeId > 0) {
            $treeId1 = $client->treeId;
        } else {
            $treeId1 = addTreeElement($client->clientname, 23, 3, 0, 1, '', 0, 0);
        }

        $dailyEntryCreditor2->value = $clientDeptChangeValue;
        $dailyEntryCreditor2->accountstreeid = $treeId1;
        $dailyEntryCreditor2->pluginControllerName = "billsreturn.php";
        $dailyEntryCreditor2->pluginComment = "أضافة مرتجع كشف بصاريات";
        $dailyEntryCreditor2->pluginid = $billsReturn->billid;

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor2);
    }
//#########################################################################################

    try {
        $data = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $dailyEntryId = $data[1];

        $billsReturn->dailyentryid = $dailyEntryId;
        $billsReturnDAO->update($billsReturn);
        $mytransactions->commit();

        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }
}

function getProductPath_recursive($parentid, $categories) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

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

        return getProductPath_recursive($newParentId, $categories);
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

##########################################################################################################

function updateBillProducts($billsReturnId) {
    global $billsProductsDAO;
    global $billsReturnProducts;
    global $billsReturnProductsDAO;
    global $billsReturnProductsEX;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailEX;

    $itr = filter_input(INPUT_POST, "hidden_itr");
    for ($i = 1; $i <= $itr; $i++) {
        $billProductId = filter_input(INPUT_POST, 'product' . $i);
        $productNum = filter_input(INPUT_POST, 'retnum' . $i);
        $storeId = filter_input(INPUT_POST, 'storeid');
        $productPrice = filter_input(INPUT_POST, 'proprice' . $i);
        $totalProductPrice = filter_input(INPUT_POST, 'totalRetPrice' . $i);

        $productNoBefore = 0;

        $billsProducts = $billsProductsDAO->load($billProductId);

        if ($billProductId && $billProductId != -1 && $productNum >= 0) {

            $billsReturnProducts = $billsReturnProductsEX->queryByProductidAndDeletedAndbillsReturnIdAndbillsproductId($billsProducts->productid, 0, $billsReturnId, $billProductId);
            $productNoBefore = $billsReturnProducts->productno;
            #######################
            $billsReturnProducts->returnbillid = $billsReturnId;
            $billsReturnProducts->productid = $billsProducts->productid;
            $billsReturnProducts->productno = $productNum;
            $billsReturnProducts->productprice = $productPrice;
            $billsReturnProducts->producttotalprice = $totalProductPrice;
            $billsReturnProducts->billproductid = $billProductId;
            $billsReturnProducts->deleted = 0;
            $billsReturnProductsDAO->update($billsReturnProducts);


            $storeDetail = $storeDetailEX->getProductQuantity($billsProducts->productid, $storeId);
            $productbefore = $storeDetail->productquantity;
            $productafter = $productbefore + $productNum - $productNoBefore;
            $productChangeAmount = $productNum - $productNoBefore;
            $storeDetail->productquantity = $productafter;
            $storeDetailDAO->update($storeDetail);
            insertStorereportupdate($billsProducts->productid, $storeId, $productChangeAmount, $productbefore, $productafter, 0, $billsReturnId, "مرتجع فاتورة مبيعات", "billsreturn.php", date('Y-m-d'));
        }
    }
}

function updateBillDetails() {
    global $billsReturn;
    global $billsReturnDAO;

    $billsReturnId = filter_input(INPUT_POST, "billsReturnId");
    $discValue = filter_input(INPUT_POST, "discValue");
    $clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue");

    $billsReturn = $billsReturnDAO->load($billsReturnId);
    $billsReturn->returnedprice = $discValue;
    $billsReturn->clientreceivevalue = $clientReceiveValue;
    $billsReturn->date = date('Y-m-d');
    $billsReturn->deleted = 0;
    $billsReturn->userid = $_SESSION['userid'];
    $billsReturn->branchid = $_SESSION['branchId'];
    $billsReturnDAO->update($billsReturn);

    return $billsReturnId;
}

function update() {
    global $billsReturn;
    global $billsReturnDAO;

    $billsReturnId = updateBillDetails();
    updateBillProducts($billsReturnId);

    $billsReturn = $billsReturnDAO->load($billsReturnId);
    reverseEntryWithItsID($billsReturn->dailyentryid);
    saveDailyEntry($billsReturnId);
}

function lastAndMeanBuyPrice_RetOptic($detailId, $productId) {

    global $productDAO;
    global $billsReturnProductsEX;

    ##the differance
    ## use $buyProduct->lastbuyprice and $buyProduct->meanbuyprice and put them in sell table
    $buyProduct = new Product();

    ##1- get mean
    $buyProduct = $productDAO->load($productId);
    if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
        $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
    }
    if ($buyProduct->lastbuyprice == NULL || $buyProduct->lastbuyprice == 0) {
        $buyProduct->lastbuyprice = $buyProduct->productBuyPrice;
    }

    if (isset($detailId) && !empty($detailId)) {
        $billsReturnProductsEX->updatePrices_f_optic($buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $detailId);
    }
}

?>