<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.php");
//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.class.php');
//Buyandruternbillcurr
require_once('../models/dao/BuyandruternbillcurrDAO.class.php');
require_once('../models/dto/Buyandruternbillcurr.class.php');
require_once('../models/mysql/BuyandruternbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillcurrMySqlExtDAO.class.php');
//Buybillcurr
require_once('../models/dao/BuybillcurrDAO.class.php');
require_once('../models/dto/Buybillcurr.class.php');
require_once('../models/mysql/BuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillcurrMySqlExtDAO.class.php');
//Returnbuybillcurr
require_once('../models/dao/ReturnbuybillcurrDAO.class.php');
require_once('../models/dto/Returnbuybillcurr.class.php');
require_once('../models/mysql/ReturnbuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillcurrMySqlExtDAO.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');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.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');
//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');
//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');
//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');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.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');

require_once('../models/dao/CostcenterDAO.class.php');
require_once('../models/dto/Costcenter.class.php');
require_once('../models/mysql/CostcenterMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterMySqlExtDAO.class.php');

require_once('../models/dao/CostcenterdetailDAO.class.php');
require_once('../models/dto/Costcenterdetail.class.php');
require_once('../models/mysql/CostcenterdetailMySqlDAO.class.php');
require_once('../models/mysql/ext/CostcenterdetailMySqlExtDAO.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');

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

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');
//Buyandruternbillcurr
require_once('../models/dao/BuyandruternbillcurrDAO.class.php');
require_once('../models/dto/Buyandruternbillcurr.class.php');
require_once('../models/mysql/BuyandruternbillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillcurrMySqlExtDAO.class.php');
//Buybillcurr
require_once('../models/dao/BuybillcurrDAO.class.php');
require_once('../models/dto/Buybillcurr.class.php');
require_once('../models/mysql/BuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillcurrMySqlExtDAO.class.php');
//Returnbuybillcurr
require_once('../models/dao/ReturnbuybillcurrDAO.class.php');
require_once('../models/dto/Returnbuybillcurr.class.php');
require_once('../models/mysql/ReturnbuybillcurrMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillcurrMySqlExtDAO.class.php');

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

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

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

  Controller Name :- returnBuyBillController

  OPERTATION in Controller

  1- show return buy bill details
  2- show return buy bills
  3- delete return buy bill

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

//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables

$Costcenterdetail = new Costcenterdetail();
$CostcenterdetailDAO = new CostcenterdetailMySqlDAO();
$CostcenterdetailEX = new CostcenterdetailMySqlExtDAO();

//Costcenter
$Costcenter = new Costcenter();
$CostcenterDAO = new CostcenterMySqlDAO();
$CostcenterEX = new CostcenterMySqlExtDAO();



//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();


//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();
//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Buyandruternbillcurr
$buyAndRuternBillCurr = new Buyandruternbillcurr();
$buyAndRuternBillCurrDAO = new BuyandruternbillcurrMySqlDAO();
$buyAndRuternBillCurrEX = new BuyandruternbillcurrMySqlExtDAO();
//Buybillcurr
$buyBillCurr = new Buybillcurr();
$buyBillCurrDAO = new BuybillcurrMySqlDAO();
$buyBillCurrEX = new BuybillcurrMySqlExtDAO();
//Returnbuybillcurr
$returnBuyBllCurr = new Returnbuybillcurr();
$returnBuyBllCurrDAO = new ReturnbuybillcurrMySqlDAO();
$returnBuyBllCurrEX = new ReturnbuybillcurrMySqlExtDAO();
//Product
$product = new Product();
$productDAO = $myProductRecord = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDebtChange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//Programsetting
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Billname
$billNameDAO = new BillnameMySqlDAO();
$billNameExt = new BillnameMySqlExtDAO();
//Billsetting
$billSettingExt = new BillsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport;
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();

//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();

//
$sizeColor = new Sizecolor();
$sizeColorDAO = new SizecolorMySqlDAO();
$sizeColorEX = new SizecolorMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();

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

//Productserial
$Productserial = $myProductserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = $myProductserialEx = new ProductserialMySqlExtDAO();
//Buyandruternbillcurr
$buyAndRuternBillCurr = new Buyandruternbillcurr();
$buyAndRuternBillCurrDAO = new BuyandruternbillcurrMySqlDAO();
$buyAndRuternBillCurrEX = new BuyandruternbillcurrMySqlExtDAO();
//Buybillcurr
$buyBillCurr = new Buybillcurr();
$buyBillCurrDAO = new BuybillcurrMySqlDAO();
$buyBillCurrEX = new BuybillcurrMySqlExtDAO();
//Returnbuybillcurr
$returnBuyBllCurr = new Returnbuybillcurr();
$returnBuyBllCurrDAO = new ReturnbuybillcurrMySqlDAO();
$returnBuyBllCurrEX = new ReturnbuybillcurrMySqlExtDAO();

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

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

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

//check and use the condition that suite this action
if ($do == "editprint") {
    include_once("../public/authentication.php");

    $returnbuybillId = $_GET['id'];
    $billnameid = $_REQUEST['billnameid'];

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);


    $detailsData = showBillDetails($returnbuybillId);
    $returnbuybillData = $detailsData[0];
    if (count($returnbuybillData) > 0) {
        $returnbuybilldetailData = $detailsData[1];

        //getalldiscount
        $buybilldiscount = $detailsData[0]->returnbuybilldiscount;
        $buybilldiscountrype = $detailsData[0]->returnbuybilldiscountrype; //0 مباشر
        $buybilltotalbill = $detailsData[0]->returnbuybilltotalbill;
        $buybillaftertotalbill = $detailsData[0]->returnbuybillaftertotalbill;
        $tax = $detailsData[0]->payedtax;


        if ($buybilldiscountrype == 0) {
            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ((abs($buybilldiscount) * -1)));
            $discountvalue = $buybilldiscount;
        } else {
            //discount
            $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;
            //tax
            $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ((abs($discountvalue) * -1)));
        }

        $smarty->assign('discountvalue', $discountvalue);
        $smarty->assign('taxvalue', $taxvalue);

        //get count
        if (count($returnbuybilldetailData) > 0) {
            foreach ($returnbuybilldetailData as $detail) {
                $countBillDetails += $detail->returnbuybilldetailquantity;
            }
        }

        $smarty->assign('returnbuybillData', $returnbuybillData);
        $smarty->assign('returnbuybilldetailData', $returnbuybilldetailData);
        $smarty->assign('countBillDetails', $countBillDetails);
        //# $billSettingsData = loadBillProperties($detailsData[0]->returnbuybillid);
        $billSettingsData = loadBillProperties($detailsData[0]->billnameid);


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


        $smarty->assign("billnameid", $detailsData[0]->returnbuybillid);

        $billnameAddData = $billNameDAO->load($returnbuybillData->billnameid);
        $smarty->assign("billnameAddData", $billnameAddData);


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

        //here the smarty templates
        $smarty->assign("customPrint", 1);
        $smarty->assign("customBuyBill", 1);
        $smarty->assign("buyBillNewProductScript", 1);
    }
    $smarty->display("returnbuybillview/editprint.html");
} elseif ($do == "details") {

    include_once("../public/authentication.php");
    $countBillDetails = 0;
    $returnbuybillId = $_GET['id'];

    $allCostcenter = $CostcenterDAO->queryAll();
    $smarty->assign("allCostcenter", $allCostcenter);


    $detailsData = showBillDetails($returnbuybillId);
    $returnbuybillData = $detailsData[0];
    $returnbuybilldetailData = $detailsData[1];

    //getalldiscount
    $buybilldiscount = $detailsData[0]->returnbuybilldiscount;
    $buybilldiscountrype = $detailsData[0]->returnbuybilldiscountrype; //0 مباشر
    $buybilltotalbill = $detailsData[0]->returnbuybilltotalbill;
    $buybillaftertotalbill = $detailsData[0]->returnbuybillaftertotalbill;
    $tax = $detailsData[0]->payedtax;


    if ($buybilldiscountrype == 0) {
        //tax
        $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ((abs($buybilldiscount) * -1)));
        $discountvalue = $buybilldiscount;
    } else {
        //discount
        $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;
        //tax
        $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ((abs($discountvalue) * -1)));
    }

    $smarty->assign('discountvalue', $discountvalue);
    $smarty->assign('taxvalue', $taxvalue);


    //get count
    if (count($returnbuybilldetailData) > 0) {
        foreach ($returnbuybilldetailData as $detail) {
            $countBillDetails += $detail->returnbuybilldetailquantity;
        }
    }

    $smarty->assign('returnbuybillData', $returnbuybillData);
    $smarty->assign('returnbuybilldetailData', $returnbuybilldetailData);
    $smarty->assign('countBillDetails', $countBillDetails);

    $billSettingsData = loadBillProperties($detailsData[0]->billnameid);
    $smarty->assign("billSettingsData", $billSettingsData);
    $smarty->assign("billnameid", $detailsData[0]->billnameid);

    $billnameAddData = $billNameDAO->load($returnbuybillData->billnameid);
    $smarty->assign("billnameAddData", $billnameAddData);

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

    //here the smarty templates
    $smarty->assign("customBuyBill", 1);
    $smarty->assign("buyBillNewProductScript", 1);

    $smarty->display("returnbuybillview/details.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");

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

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

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

    //    $suppliersData = getSuppliers(); //undeleted suppliers
    //    $smarty->assign("suppliersData", $suppliersData);

    $returnbuybillSerialData = showReturnBuyBills();
    $smarty->assign("returnbuybillSerialData", $returnbuybillSerialData);

    $supplierId = (int) $_REQUEST['supplier'];
    $serial = $_REQUEST['serial'];
    $buybillid = $_REQUEST['buybillid'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    $hideDel = (int) $_REQUEST['hideDel'];
    $delString = '';
    if (isset($hideDel) && $hideDel == 1) {
        //$message .= "<br> اخفاء المحذوف ";
        $delString .= ' AND returnbuybill.conditions = 0 ';
    }

    //display the converted time ##reportsPlusHours
    $Programsetting = $ProgramsettingDAO->load(1);

    if (!empty($supplierId) && $supplierId > 0 && (empty($serial) || $serial == "-1")) {
        showBySupplier($supplierId, $delString);

        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);
    } elseif (!empty($serial) && $serial != "-1" && (empty($supplierId) || $supplierId == "-1")) {
        showByBillSerial($serial, $delString);

        $message = "رقم الفاتورة: " . $serial;
        $smarty->assign("message", $message);
    } elseif (!empty($buybillid) && $buybillid != "-1" && (empty($serial) || $serial == "-1") && (empty($supplierId) || $supplierId == "-1")) {
        showBybuybillid($buybillid, $delString);

        $message = "الرقم المتسلسل: " . $buybillid;
        $smarty->assign("message", $message);
    } else if (!empty($from) && !empty($to)) {
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
        } else {
            $endDatePrepared = $endDate . ' 23:59:59';
            $from = $from . " 00:00:00";
        }
        showByDate($from, $to, $delString);

        $message = "التاريخ من: " . $from . " إلى: " . $to;
        $smarty->assign("message", $message);
    } else { //show today's bills
        //display the converted time ##reportsPlusHours
        ################
        $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $from = $startYesterday;
            $to = $endYesterday;
        } else {
            $from = $startToday;
            $to = $endToday;
        }
        ##############
        showByDate($from, $to, $delString);
        //showAll();
    }
    $smarty->assign("customCheck", 1);
    $smarty->display("returnbuybillview/show.html");
} elseif ($do == "delete") {
    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        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");
}
//here the global templates
$smarty->display("footer.html");

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

function getSuppliers() {
    global $supplierDAO;
    $suppliersData = $supplierDAO->queryByCondition(0);
    return $suppliersData;
}

function showBillDetails($returnbuybillId) {
    global $returnBuyBillExt;
    global $returnBuyBillDetailExt;
    global $returnBuyBllCurrEX;

    $returnbuybillData = $returnBuyBillExt->loadExt($returnbuybillId);
    $billCurrData = $returnBuyBllCurrEX->queryOneByBuybillid($returnbuybillId);
    $returnbuybilldetailData = $returnBuyBillDetailExt->queryByBuyReturnbuybillIdExt($returnbuybillId);

    ##use currency values
    if (isset($billCurrData) && $_GET['do'] == "editprint") {
        $returnbuybillData->returnbuybilldiscount = $billCurrData->returnbuybilldiscountC;
        $returnbuybillData->returnbuybilltotalbill = $billCurrData->returnbuybilltotalbillC;
        $returnbuybillData->returnbuybillaftertotalbill = $billCurrData->returnbuybillaftertotalbillC;
        $returnbuybillData->returnbuybilltotalpayed = $billCurrData->returnbuybilltotalpayedC;
        $returnbuybillData->returnbuybillfinalbill = $billCurrData->returnbuybillfinalbillC;
        $returnbuybillData->returnbuybilldirectpayment = $billCurrData->returnbuybilldirectpaymentC;
        $returnbuybillData->payedtax = $billCurrData->payedtaxC;
        ##
        $returnbuybillData->returnbuybilltotaldeptbefor = $returnbuybillData->returnbuybilltotaldeptbefor * $billCurrData->conversionFactor;
        $returnbuybillData->returnbuybilltotaldeptafter = $returnbuybillData->returnbuybilltotaldeptafter * $billCurrData->conversionFactor;
        foreach ($returnbuybilldetailData as $value) {
            $value->returnbuybilldetailprice = $value->returnbuybilldetailpriceC;
            $value->returnbuybilldetailtotalprice = $value->returnbuybilldetailtotalpriceC;
            $value->discountvalue = $value->discountvalueC;
        }
    }

    return array($returnbuybillData, $returnbuybilldetailData);
}

function showReturnBuyBills() {
    global $returnBuyBillExt;
    $returnbuybills = $returnBuyBillExt->queryAllSerialsNotDeleted();
    return $returnbuybills;
}

function loadBillProperties($billnameid) {
    global $billSettingExt;

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

function showAll() {
    global $returnBuyBillExt;
    global $smarty;

    $returnbuybillData = $returnBuyBillExt->queryByConditionExt(0);
    $totalBills = 0;
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }
    $smarty->assign('totalBills', $totalBills);
    $smarty->assign('returnbuybillData', $returnbuybillData);
}

function showByDate($from, $to, $delString) {
    global $returnBuyBillExt;
    global $smarty;

    $returnbuybillData = $returnBuyBillExt->queryByDateExt($from, $to, $delString);
    $totalBills = 0;
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }
    $smarty->assign('totalBills', $totalBills);

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

function showBySupplier($supplierId, $delString) {
    global $returnBuyBillExt;
    global $smarty;

    $returnbuybillData = $returnBuyBillExt->queryBySupplierId($supplierId, $delString);
    $totalBills = 0;
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }
    $smarty->assign('totalBills', $totalBills);

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

function showByBillSerial($serial, $delString) {
    global $returnBuyBillExt;
    global $smarty;

    $returnbuybillData = $returnBuyBillExt->queryBySerial($serial, $delString);
    $totalBills = 0;
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }
    $smarty->assign('totalBills', $totalBills);

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

function showBybuybillid($buybillid, $delString) {
    global $returnBuyBillExt;
    global $smarty;

    $returnbuybillData = $returnBuyBillExt->loadExt2($buybillid, $delString);
    $totalBills = 0;
    if (count($returnbuybillData) > 0) {

        foreach ($returnbuybillData as $bill) {
            if ($bill->conditions == 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }
    $smarty->assign('totalBills', $totalBills);

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

function delete() {
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillExt;
    global $returnBuyBillDetail;
    global $returnBuyBillDetailDAO;
    global $returnBuyBillDetailExt;
    //
    global $returnBuyBllCurr;
    global $returnBuyBllCurrDAO;
    global $returnBuyBllCurrEX;

    global $CostcenterdetailDAO;
    global $Costcenterdetail;
    global $CostcenterdetailEX;

    global $sizeColorStoreDetailEX;
    global $myProductserialEx;
    global $smarty;

    global $today;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $dailyentryid = $_GET['action'];
        $returnbuybillId_one = $_GET['id'];
        if (isset($returnbuybillId_one)) {
            $returnbuybillId = $returnbuybillId_one;
            if (isset($returnbuybillId)) {
                $returnbuybillData = $returnBuyBillDAO->load($returnbuybillId);
                $billCurrData = $returnBuyBllCurrEX->queryOneByBuybillid($returnbuybillId);
                if (count($returnbuybillData) > 0 && $returnbuybillData->conditions == 0) {
                    foreach (explode(',', $dailyentryid) as $entryid) {
                        reverseEntryWithItsID($entryid, 1);
                    }
                    $deleteOrNot = $returnbuybillData->conditions;
                    if (isset($deleteOrNot) && $deleteOrNot != 1) {
                        $CostcenterdetailEX->updatedellbytypeandmodelid(4, $returnbuybillId, 1);

                        $totaldeptafter = $returnbuybillData->returnbuybilltotaldeptafter;
                        $totaldeptbefore = $returnbuybillData->returnbuybilltotaldeptbefor;
                        $totalpayed = $returnbuybillData->returnbuybilltotalpayed;
                        $finalbill = $returnbuybillData->returnbuybillfinalbill;
                        $buybillfinalbillC = $billCurrData->returnbuybillfinalbillC;
                        $storeId = $returnbuybillData->returnbuybillstoreid;
                        $supplierId = $returnbuybillData->returnbuybillsupplierid;
                        $saveId = $returnbuybillData->returnbuybillsaveid;
                        $currencyId = $returnbuybillData->currencyId;

                        $returnBuyBill->conditions = 1;
                        $returnBuyBill->returnbuybillsysdate = date("Y-m-d H:i:s");
                        ;
                        //$returnBuyBill->userid = $_SESSION['userid'];
                        $returnBuyBill->userid = $returnbuybillData->userid;
                        $returnBuyBill->delbyuserid = $_SESSION['userid'];
                        $returnBuyBill->returnbuybillid = $returnbuybillId;

                        $returnBuyBillExt->updateConditions($returnBuyBill);

                        //returnbuybilldetail
                        $returnbuybilldetailData = $returnBuyBillDetailDAO->queryByReturnbuybillid($returnbuybillId);

                        if (count($returnbuybilldetailData) > 0) {
                            foreach ($returnbuybilldetailData as $data) {
                                $productId = $data->returnbuybilldetailproductid;
                                $pronum = $data->returnbuybilldetailquantity;
                                $scunitname = $data->otherdetailquantity;
                                if ($data->storeid > 0) {
                                    $storeId = $data->storeid;
                                } else {
                                    $storeId = $returnBuyBill->returnbuybillstoreid;
                                }

                                $parcode = $data->parcode;

                                $productunitId = $data->productunitid;

                                $sizeId = $data->sizeid;
                                $colorId = $data->colorid;

                                $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);

                                if (isset($productId)) {
                                    $isService = isService($productId);
                                    if ($isService == 0) { //if product
                                        $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                        $allStoredetailData = $storeDetailData[0];
                                        $storeDetailId = $storeDetailData[1];
                                        $productQuantityBefore = $storeDetailData[2];


                                        $productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
                                        $productnumber = $productunitData->productnumber;
                                        $finalquantity = $pronum * $productnumber;

                                        $issold = $myProductserialEx->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");
                                        if (isset($issold->productserailid) && $issold->productserailid > 0) {
                                            $productserailId = $issold->productserailid;
                                            //updateSerailDon($productserailId, 1, $sellbillId);
                                            updateSerailQty_ForReturn($productserailId, $finalquantity);
                                        }

                                        print_r($productunitData);
                                        print_r('<br>' . $finalquantity);

                                        if (count($allStoredetailData) > 0) {
                                            //update productquantity in storedetail
                                            $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $finalquantity, $sizeColorStoreDetailId, $sizeId, $colorId);

                                            //insert in storereport
                                            insertStorereport($productId, $storeId, $finalquantity, $productQuantityBefore, $productQuantityAfter, 0, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $sizeId, $colorId);
                                        } else {
                                            //insert in storedetail tbl
                                            insertStoredetail($storeId, $productId, $finalquantity, $sizeColorStoreDetailId, $sizeId, $colorId);

                                            //insert in storereport
                                            insertStorereport($productId, $storeId, $finalquantity, 0, $finalquantity, 0, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $sizeId, $colorId);
                                        }






                                        $allStoredetailData2 = getStoreDetails($storeId, $productId, 1, $sizeColorStoreDetailId, $sizeId, $colorId);
                                        $allStoredetailDataother = $allStoredetailData2[0];
                                        $storeDetailIdother = $allStoredetailData2[1];
                                        $productQuantityBeforeother = $allStoredetailData2[2];



                                        if (count($allStoredetailDataother) > 0 && $scunitname > 0) {
                                            //update productquantity in storedetail
                                            print_r('in if');
                                            $finalquantityother = $productQuantityBeforeother + $scunitname;
                                            $productQuantityAfter = updateProductQuantitotherunit2($storeDetailIdother, $finalquantityother, 1);

                                            //insert in storereport
                                            insertStorereportupdate2($productId, $storeId, $scunitname, $productQuantityBeforeother, $productQuantityAfter, 1, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, 1);
                                        } else {
                                            //insert in storedetail tbl
                                            if ($scunitname > 0) {
                                                insertStoredetailupdate2($storeId, $productId, $scunitname, $buybillDate, 1);

                                                //insert in storereport
                                                insertStorereportupdate2($productId, $storeId, $scunitname, 0, $scunitname, 0, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $buybillDate, 1);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //****************** Update supplier dept ********************//
                        //check if supplier deptAfter change from  supplier deptBefor
                        //if($totaldeptafter != $totaldeptbefore)
                        //{

                        $supplierData = loadSupplierDataById($supplierId);
                        $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                        $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;
                        $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) + ($finalbill * (-1));
                        $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) + ($buybillfinalbillC * (-1));

                        //update supplierdebt
                        updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);

                        insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 0, "حذف فاتورة مردودات مشتريات", $returnbuybillId, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "returnBuyBillController.php", "حذف فاتورة مردودات مشتريات");
                        //}
                        //****************** Update save value ************************//
                        //check if payed or not to change the save value
                        //if($totalpayed > 0)
                        //{
                        ##curr conversion
                        $saveConversionFactor = 0;
                        if ($currencyId > 1) {
                            $billCurrData = $returnBuyBllCurrEX->queryOneByBuybillid($returnbuybillId);
                            $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
                        }
                        $totalpayed = abs($totalpayed);
                        //get saveValue before and saveValue after plus totalPayed
                        $saveData = getSaveValueAndMins($saveId, $totalpayed, $saveConversionFactor);
                        $saveId = $saveData[0];
                        $saveValuebefore = $saveData[1];
                        $saveValueafter = $saveData[2];
                        ##curr conversion
                        $totalpayedSaveCurr = $saveData[3];
                        $saveConversionFactor = $saveData[4];

                        //update saveFrom value after add transfer
                        updateSave($saveId, $saveValueafter);

                        //insert into savedaily tbl from savefrom
                        insertSavedaily($saveValuebefore, $totalpayedSaveCurr, 1, $saveId, "حذف فاتورة مردودات مشتريات", $returnbuybillId, $saveValueafter, "returnBuyBillController.php");
                    }
                }
            }
        } else {
            $operationType = $_POST['operation'];
            $smarty->assign("operationType", $operationType);

            $choosedItemArr = $_POST['choosedItem'];

            if (count($choosedItemArr) > 0) {
                $i = 1;
                foreach ($choosedItemArr as $returnbuybillId) {
                    if ($operationType == '1') {
                        if (isset($returnbuybillId)) {
                            $returnbuybillData = $returnBuyBillDAO->load($returnbuybillId);
                            $billCurrData = $returnBuyBllCurrEX->queryOneByBuybillid($returnbuybillId);
                            if (count($returnbuybillData) > 0 && $returnbuybillData->conditions == 0) {
                                foreach (explode(',', $dailyentryid) as $entryid) {
                                    reverseEntryWithItsID($entryid, 1);
                                }
                                $deleteOrNot = $returnbuybillData->conditions;
                                if (isset($deleteOrNot) && $deleteOrNot != 1) {
                                    $totaldeptafter = $returnbuybillData->returnbuybilltotaldeptafter;
                                    $totaldeptbefore = $returnbuybillData->returnbuybilltotaldeptbefor;
                                    $totalpayed = $returnbuybillData->returnbuybilltotalpayed;
                                    $finalbill = $returnbuybillData->returnbuybillfinalbill;
                                    $buybillfinalbillC = $billCurrData->returnbuybillfinalbillC;
                                    $storeId = $returnbuybillData->returnbuybillstoreid;
                                    $supplierId = $returnbuybillData->returnbuybillsupplierid;
                                    $saveId = $returnbuybillData->returnbuybillsaveid;

                                    $returnBuyBill->conditions = 1;
                                    $returnBuyBill->returnbuybillsysdate = date("Y-m-d H:i:s");
                                    //$returnBuyBill->userid = $_SESSION['userid'];
                                    $returnBuyBill->userid = $returnbuybillData->userid;
                                    $returnBuyBill->delbyuserid = $_SESSION['userid'];
                                    $returnBuyBill->returnbuybillid = $returnbuybillId;

                                    $returnBuyBillExt->updateConditions($returnBuyBill);

                                    //returnbuybilldetail
                                    $returnbuybilldetailData = $returnBuyBillDetailDAO->queryByReturnbuybillid($returnbuybillId);

                                    if (count($returnbuybilldetailData) > 0) {
                                        foreach ($returnbuybilldetailData as $data) {
                                            $productId = $data->returnbuybilldetailproductid;
                                            $pronum = $data->returnbuybilldetailquantity;

                                            if ($data->storeid > 0) {
                                                $storeId = $data->storeid;
                                            } else {
                                                $storeId = $returnBuyBill->returnbuybillstoreid;
                                            }

                                            $sizeId = $data->sizeid;
                                            $colorId = $data->colorid;

                                            $sizeColorStoreDetailId = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productId, $storeId, $sizeId, $colorId);

                                            if (isset($productId)) {
                                                $isService = isService($productId);
                                                if ($isService == 0) { //if product
                                                    $storeDetailData = getStoreDetails($storeId, $productId, 0, $sizeColorStoreDetailId, $sizeId, $colorId);

                                                    $allStoredetailData = $storeDetailData[0];
                                                    $storeDetailId = $storeDetailData[1];
                                                    $productQuantityBefore = $storeDetailData[2];

                                                    if (count($allStoredetailData) > 0) {
                                                        //update productquantity in storedetail
                                                        $productQuantityAfter = increaseProductQuantity($storeDetailId, $productQuantityBefore, $pronum, $sizeColorStoreDetailId, $sizeId, $colorId);

                                                        //insert in storereport
                                                        insertStorereport($productId, $storeId, $pronum, $productQuantityBefore, $productQuantityAfter, 0, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $sizeId, $colorId);
                                                    } else {
                                                        //insert in storedetail tbl
                                                        insertStoredetail($storeId, $productId, $pronum, $sizeColorStoreDetailId, $sizeId, $colorId);

                                                        //insert in storereport
                                                        insertStorereport($productId, $storeId, $pronum, 0, $pronum, 0, $returnbuybillId, "حذف فاتورة مردودات مشتريات", "returnBuyBillController.php", $sizeId, $colorId);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //************ Update supplier dept ***************//
                                    //check if supplier deptAfter change from  supplier deptBefor
                                    //if($totaldeptafter != $totaldeptbefore)
                                    //{

                                    $supplierData = loadSupplierDataById($supplierId);
                                    $supplierDeptBeforeInMainCurr = $supplierData->suppliercurrentDebt;
                                    $supplierDeptBefore = $supplierData->suppliercurrentDebtInCurrency;
                                    $supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) + ($finalbill * (-1));
                                    $supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) + ($buybillfinalbillC * (-1));

                                    //update supplierdebt
                                    updateSupplierDebt($supplierId, $supplierDeptAfter, $supplierDeptAfterInMainCurr);

                                    insertSupplierDebtChange($supplierId, $supplierDeptBefore, $supplierDeptBeforeInMainCurr, abs($finalbill), abs($buybillfinalbillC), 0, "حذف فاتورة مردودات مشتريات", $returnbuybillId, $supplierDeptAfter, $supplierDeptAfterInMainCurr, "returnBuyBillController.php", "حذف فاتورة مردودات مشتريات");
                                    //}
                                    //************** Update save value ****************//
                                    //check if payed or not to change the save value
                                    //if($totalpayed > 0)
                                    //{
                                    $totalpayed = $totalpayed * (-1);
                                    //get saveValue before and saveValue after plus totalPayed
                                    $saveData = getSaveValueAndMins($saveId, $totalpayed);
                                    $saveId = $saveData[0];
                                    $saveValuebefore = $saveData[1];
                                    $saveValueafter = $saveData[2];

                                    //update saveFrom value after add transfer
                                    updateSave($saveId, $saveValueafter);

                                    //insert into savedaily tbl from savefrom
                                    insertSavedaily($saveValuebefore, $totalpayed, 1, $saveId, "حذف فاتورة مردودات مشتريات", $returnbuybillId, $saveValueafter, "returnBuyBillController.php");
                                }
                            }
                        }
                    }
                    $i++;
                }
            }
        }

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

function loadSupplierDataById($supplierid) {
    global $supplierDAO;

    //load client by Id tbl
    $supplierData = $supplierDAO->load($supplierid);
    return $supplierData;
}

////////////////////////////save///////////////////////////
// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid) {
    global $save;
    global $saveDAO;

    $saveData = $saveDAO->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

//get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged, $saveConversionFactor = 0) {
    global $save;
    global $saveExt;

    $saveData = $saveExt->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $savevaluechanged, $saveConversionFactor);
}

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged, $saveConversionFactor = 0) {
    global $save;
    global $saveExt;

    $saveData = $saveExt->loadForUpdateEx($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }
    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter, $savevaluechanged, $saveConversionFactor);
}

// update in Save tbl
function updateSave($saveid, $savevalueafter) {
    global $save;
    global $saveExt;

    //update initialvalue in Save tbl
    $save->savecurrentvalue = $savevalueafter;
    $save->userid = $_SESSION['userid'];
    $save->saveid = $saveid;

    $saveExt->updateSaveValue($save);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {
    global $saveDaily;
    global $saveDailyDAO;

    //insert in Savedaily tbl
    $saveDaily->savedailydate = date("Y-m-d H:i:s");
    $saveDaily->userid = $_SESSION['userid'];
    $saveDaily->savedailysavebefore = $savedailysavebefore;
    $saveDaily->savedailychangeamount = $savedailychangeamount;
    $saveDaily->savedailychangetype = $savedailychangetype;
    $saveDaily->saveid = $saveid;
    $saveDaily->processname = $processname;
    $saveDaily->savedailymodelid = $savedailymodelid;
    $saveDaily->savedailysaveafter = $savedailysaveafter;
    $saveDaily->tablename = $tablename;

    $saveDailyDAO->insert($saveDaily);
}

/////////////////////////////////store////////////////////////////

function getStoreDetails($storeId, $productId, $unittype, $sizeColorStoreDetailId, $sizeId, $colorId) {
    // get productquantity from storedetail tbl
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;

    if ((isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) || ($sizeId > 0 && $colorId > 0)) { //sizecolor product
        if ((!isset($sizeColorStoreDetailId) || empty($sizeColorStoreDetailId)) && ($sizeId > 0 && $colorId > 0)) {
            $storeDetailId = 0;
            $productQuantityBefore = 0;
        } else {
            $storeDetailData = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
            $storeDetailId = $storeDetailData->id;
            $productQuantityBefore = $storeDetailData->quantity;
        }
    } else {

        //select data from storedetails by storeid and productid
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $storeId, $unittype);

        $storeDetailId = $storeDetailData->storedetailid;
        $productQuantityBefore = $storeDetailData->productquantity;
    }
    return array($storeDetailData, $storeDetailId, $productQuantityBefore);
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId) {

    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;

    $myStoredetail = $storeDetailDAO->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = 0;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, abs($productChangeAmount), 1);
        //affect product to make it have total quantity
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //            $storeDetailExt->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 0);
            $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $storeDetail->storedetailid = $storedetailId;
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->productquantity = $productquantityAfter;

        $storeDetailExt->updateProductquantity($storeDetail);
        onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);
    }

    return $productquantityAfter;
}

//update and decrease product quantity in storedetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $storeDetail;
    global $storeDetailExt;
    global $storeDetailDAO;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;

    //decrease productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    $myStoredetail = $storeDetailDAO->load($storedetailId);
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($myStoredetail->productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $myStoredetail->storeid;
        $sizeColorStoreDetail->quantity = 0;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }

    if (isset($sizeColorStoreDetailId) && $sizeColorStoreDetailId > 0) {
        $sizecolorstoredetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId);
        $sizecolorstoredetail->userid = $_SESSION['userid'];
        $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
        $sizecolorstoredetail->quantity = $productquantityAfter;
        $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
        onlineTempStoreDetailFunc($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, (abs($productChangeAmount) * -1), 1);
        //affect product to make it have total quantity
        $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($sizecolorstoredetail->productid, $sizecolorstoredetail->storeid, 0);
        if (!isset($storeDetailData) || empty($storeDetailData->storedetailid)) {
            insertStoredetail($sizecolorstoredetail->storeid, $productId, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId);
        } else {
            //            $storeDetailExt->updateQuantityPlusEqualORMinusEqual($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), $productChangeAmount, 0, 1);
            $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        }
    } else {
        //update productquantity in storedetail tbl
        $storeDetail->storedetailid = $storedetailId;
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");

        $storeDetail->productquantity = $productquantityAfter;

        $storeDetailExt->updateProductquantity($storeDetail);
        onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, (abs($productChangeAmount) * -1), 1);
    }
    return $productquantityAfter;
}

//add in storedetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount, $sizeColorStoreDetailId, $sizeId, $colorId) {
    global $storeDetail;
    global $storeDetailExt;
    global $storeDetailDAO;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;


    //increase productquantity
    if (empty($sizeColorStoreDetailId) && $sizeId > 0 && $colorId > 0) {
        //try to copy from existing data in store 1
        $sizeColorStoreDetailId2 = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX($productid, 1, $sizeId, $colorId);
        $sizeColorStoreDetail = $sizeColorStoreDetailDAO->load($sizeColorStoreDetailId2);

        $sizeColorStoreDetail->storeid = $storeid;
        $sizeColorStoreDetail->quantity = $productChangeAmount;
        $sizeColorStoreDetail->userid = $_SESSION['userid'];
        $sizeColorStoreDetail->sysdate = date("Y-m-d H:i:s");

        $sizeColorStoreDetailId = $sizeColorStoreDetailDAO->insert($sizeColorStoreDetail);
    }
    $row = $storeDetailExt->queryByStoreidAndProductid($productid, $storeid);
    if (!isset($row->storedetailid) || $row->storedetailid < 1) {
        $storeDetail->userid = $_SESSION['userid'];
        $storeDetail->storedetaildate = date("Y-m-d");
        $storeDetail->productquantity = $productChangeAmount;
        $storeDetail->storeid = $storeid;
        $storeDetail->productid = $productid;

        $storeDetailDAO->insert($storeDetail);
    } else {
        $storeDetailExt->updateQuantityWithSumChild($row->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $storeid, $productid);
    }
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $sizeId, $colorId) {
    global $storeReport;
    global $storeReportDAO;

    $storeReport->processname = $processname;
    $storeReport->productafter = $productafter;
    $storeReport->productbefore = $productbefore;
    $storeReport->productquantity = $productChangeAmount;
    $storeReport->productid = $productid;
    $storeReport->storeid = $storeid;
    $storeReport->storereportdate = date("Y-m-d");
    $storeReport->storereportmodelid = $storereportmodelid;
    $storeReport->storereporttype = $storereporttype;
    $storeReport->tablename = $tablename;
    $storeReport->userid = $_SESSION['userid'];
    $storeReport->sizeid = $sizeId;
    $storeReport->colorid = $colorId;

    $id = $storeReportDAO->insert($storeReport);
    $storeReport->storereportid = $id;
    onlineTempStoreReportFunc($storeReport);
}

///////////////////////////////////suppliers//////////////////////
// update in rawmaterialssuppliers tbl
function updateSupplierDebt($supplierId, $supplierDebtAfter, $totaldeptafterInMainCurr) {
    global $supplier;
    global $supplierExt;
    global $today;

    //update clientdebt in client tbl
    $supplier->userid = $_SESSION['userid'];
    $supplier->suppliercurrentDebt = $totaldeptafterInMainCurr;
    $supplier->suppliercurrentDebtInCurrency = $supplierDebtAfter;
    $supplier->supplierid = $supplierId;
    $supplier->supplierdate = $today;

    $supplierExt->updatedept($supplier);
}

// insert data into Clientdebtchange tbl
function insertSupplierDebtChange($supplierId, $supplierDebtChangeBefore, $supplierDebtChangeBeforeInMainCurr, $supplierDebtChangeAmountInMainCurr, $supplierDebtChangeAmount, $supplierDebtChangeType, $processname, $supplierDebtChangeModelId, $supplierDebtChangeAfter, $supplierDebtChangeAfterInMainCurr, $tablename, $comment) {
    global $supplierDebtChange;
    global $supplierDebtChangeDAO;
    global $today;

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfterInMainCurr;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmountInMainCurr;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBeforeInMainCurr;
    $supplierDebtChange->debtchangafterInSupplierCurrency = $supplierDebtChangeAfter;
    $supplierDebtChange->debtchangamountInSupplierCurrency = $supplierDebtChangeAmount;
    $supplierDebtChange->debtchangbeforeInSupplierCurrency = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = $today;
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;

    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

function loadProductUnitWithProductAndUnit($productId, $unitId) {

    //to use the variable out side the funcion
    global $myProductunitEx;

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);

    return $productunitData;
}

function updateProductQuantitotherunit2($storedetailId, $productquantityAfter, $unittype) {
    global $storeDetail;
    global $storeDetailExt;


    //update productquantity in storedetail tbl


    $storeDetailExt->updateProductquantity2($storedetailId, $_SESSION['userid'], date("Y-m-d"), $productquantityAfter, $unittype);

    return $productquantityAfter;
}

function insertStorereportupdate2($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $mydate, $unittype) {
    global $storeReport;
    global $storeReportExt;

    $storeReport->processname = $processname;
    $storeReport->productafter = $productafter;
    $storeReport->productbefore = $productbefore;
    $storeReport->productquantity = $productChangeAmount;
    $storeReport->productid = $productid;
    $storeReport->storeid = $storeid;
    $storeReport->storereportdate = $mydate; //date("Y-m-d");
    $storeReport->storereportmodelid = $storereportmodelid;
    $storeReport->storereporttype = $storereporttype;
    $storeReport->tablename = $tablename;
    $storeReport->userid = $_SESSION['userid'];
    $storeReport->unittype = $unittype;

    print_r($storeReport);

    $storeReportExt->insertEX($storeReport);
}

function updateSerailQty($productserailId, $soldQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);
    if ($productQuantity > 0) {
        $availableQty = $productQuantity - $soldQuantity;
        //if(isset($availableQty) && $availableQty < 0)
        //			{
        //				//في حالة بيع منتج بكمية أكبر من عدد السريالات
        //			}
        //			else
        //			{
        //
        //			}

        $myProductserial->productserailid = $productserailId;
        $myProductserial->don = $availableQty;
        //print_r($myProductserial);
        $myProductserialEx->updateDon($myProductserial);
    }
}

function updateSerailQty_ForReturn($productserailId, $returnedQuantity) {
    global $myProductserial;
    global $myProductserialEx;

    $productQuantity = $myProductserialEx->getProductQuantity($productserailId);

    //print_r('<br>returnedQuantity'.$returnedQuantity);
    //print_r('<br>productQuantity'.$productQuantity);
    //    if ($productQuantity > 0) {
    $availableQty = $productQuantity + $returnedQuantity;

    //print_r('<br>availableQty'.$availableQty);
    $myProductserial->productserailid = $productserailId;
    $myProductserial->don = $availableQty;
    //print_r('<br>cccccccccccccccccccc'.$productserailId);
    $myProductserialEx->updateDon($myProductserial);
    //    }
}

function isService($id) {

    global $myProductRecord;

    $pro = $myProductRecord->load($id);
    return $pro->isService;
}
