<?php

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

// get the config file
include_once("../public/config.php");

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


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

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');



//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');
//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');
//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.class.php');

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

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

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

$do = $_GET['do'];

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

  Controller Name :- storedetailCTRL تقرير مخزون اول مدة

  OPERTATION in Controller

  1-load save data
  2-display show form

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

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

//here goes the instances and general variables
//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();
//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();
##################################
//bill
$billsBuy = new Billsbuy();
$billsBuyDAO = new BillsbuyMySqlDAO();
$billsBuyEX = new BillsbuyMySqlExtDAO();

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

$billsProductsBuy = new Billsproductsbuy();
$billsProductsBuyDAO = new BillsproductsbuyMySqlDAO();
$billsProductsBuyEX = new BillsproductsbuyMySqlExtDAO();

//supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierEX = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

$catsIDS = "";
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");
    $Programsetting = $ProgramsettingDAO->load(1);
    ##########################################################################
    //prepare search tools
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

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

    $user = $userDAO->load($_SESSION['userid']);
    $smarty->assign("user", $user);
    if ($user->userstoreid == 0) {
        $storeData = loadStore();
        $smarty->assign("storeData", $storeData);
    }
    if ($user->branchId == 0) {
        $branchData = loadBranch();
        $smarty->assign("branchData", $branchData);
    }
    $userData = loadusers();
    $smarty->assign("userData", $userData);
    ###########################################################################
    //search
    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');

    $queryString = " where 1 "; //bills
    $queryStringR = " where 1 "; //billsreturn
    $queryString1 = " where 1 and buybill.conditions = 0 "; //buybill
    $queryString1R = " where 1 and returnbuybill.conditions = 0 "; //buybillreturn
    $queryString1SR = " where 1 and buyandruternbill.conditions = 0 "; //buybillandreturn
    ##date
    if (isset($datefrom) && !empty($datefrom)) {
        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
            $datefrom = date('Y-m-d ', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($datefrom)));
        } else {
            $datefrom = $datefrom . " 00:00:00";
        }
        $queryString .= ' and billsbuy.billdate  >= "' . $datefrom . '" ';
        $queryStringR .= ' and billsreturn.`date`  >= "' . $datefrom . '" ';
        $queryString1 .= ' and buybill.buybilldate  >= "' . $datefrom . '" ';
        $queryString1R .= ' and returnbuybill.returnbuybilldate  >= "' . $datefrom . '" ';
        $queryString1SR .= ' and buyandruternbill.buybilldate  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        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
            $dateto = date('Y-m-d ', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($dateto)));
        } else {
            $dateto = $dateto . ' 23:59:59';
        }
        $queryString .= ' and billsbuy.billdate  <= "' . $dateto . '" ';
        $queryStringR .= ' and  billsreturn.`date`  <= "' . $dateto . '" ';
        $queryString1 .= ' and buybill.buybilldate  <= "' . $dateto . '" ';
        $queryString1R .= ' and returnbuybill.returnbuybilldate  <= "' . $dateto . '" ';
        $queryString1SR .= ' and buyandruternbill.buybilldate  <= "' . $dateto . '" ';
    }

    if (!empty($datefrom) && !empty($dateto)) {
        $datefrom = $datefrom . ' 00:00:00';
        $dateto = $dateto . ' 23:59:59';
    }


    getData($datefrom, $dateto, $queryString, $queryStringR, $queryString1, $queryString1R, $queryString1SR);
    $smarty->assign("salesreport", 1);
    //here the smarty templates
    $smarty->display("orderSuppliersWithBuys/show.html");

    //$smarty->assign("settlementstoreshow", 1);
}
//here the global templates
$smarty->display("footer.html");

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

function getData($datefrom, $dateto, $queryString, $queryStringR, $queryString1, $queryString1R, $queryString1SR)
{
    global $smarty;
    // m7md
    global $buyBillExt;
    global $returnBuyBillExt;
    global $buyAndReturnBillExt;
    global $billsBuyEX;
    global $billsReturnEX;

    class supplierData
    {

        public $supplierid;
        public $suppliername;
        public $totalbuy = 0;
        public $totalreturn = 0;
        public $totaldiscount = 0;
        public $supplierdebt = 0;
    }

    $existId = array();
    $buybillDataArr = array();
    $resultsCount = 0;

    if (empty($datefrom) && empty($dateto)) {
        ##if no search make it today
        ##date
        $today = date("Y-m-d");
        $queryString .= ' and date(billsbuy.billdate)  = "' . $today . '" ';
        $queryStringR .= ' and date(billsreturn.`date`)  = "' . $today . '" ';
        $queryString1 .= ' and  buybill.buybilldate  = "' . $today . '" ';
        $queryString1R .= ' and returnbuybill.returnbuybilldate  = "' . $today . '" ';
        $queryString1SR .= ' and buyandruternbill.buybilldate  = "' . $today . '" ';
    }
    $billsData = $billsBuyEX->orderClientsWithBillsSells($queryString);
    $billsDataReturn = $billsReturnEX->orderClientsWithBillsReturnSells($queryStringR);
    $buyBillData = $buyBillExt->orderSuppliersWithBuybillsBuys($queryString1);
    $buyBillDataReturn = $returnBuyBillExt->orderSuppliersWithReturnBuybillsBuys($queryString1R);
    $buyBillDataAndReturn = $buyAndReturnBillExt->orderSuppliersWithBuyAndReturnBuybillsBuys($queryString1SR);
    $resultsCount = count($billsData) + count($billsDataReturn) + count($buyBillData) + count($buyBillDataReturn) + count($buyBillDataAndReturn);
    $smarty->assign("resultsCount", $resultsCount);



    ##فاتورة المشتريات
    foreach ($buyBillData as $key => $value) {
        if (in_array($value->buybillsupplierid, $existId)) {
            $key = array_search($value->buybillsupplierid, $existId);
            $mysupplier = $buybillDataArr[$key];
        } else {
            $key = -1;
            $mysupplier = new supplierData();
            $mysupplier->supplierid = $value->buybillsupplierid;
            array_push($existId, $value->buybillsupplierid);
        }

        $mysupplier->suppliername = $value->suppliername;
        $mysupplier->totalbuy = $value->allGenTotal;
        $mysupplier->buybillaftertotalbill += $value->buybillaftertotalbill;
        $mysupplier->supplierdebt = $value->supplierdebt;
        $mysupplier->buydis += $value->allGenTotal - $value->buybillaftertotalbill;

        if ($key == -1) {
            array_push($buybillDataArr, $mysupplier);
        }
    }

    ##فاتورة  مردودات المشتريات
    foreach ($buyBillDataReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value->returnbuybillsupplierid, $existId)) {
            $key = array_search($value->returnbuybillsupplierid, $existId);
            $mysupplier = $buybillDataArr[$key];
        } else {
            $key = -1;
            $mysupplier = new supplierData();
            $mysupplier->supplierid = $value->returnbuybillsupplierid;
            array_push($existId, $value->returnbuybillsupplierid);
        }

        $mysupplier->suppliername = $value->suppliername;
        $mysupplier->totalreturn += $value->allGenTotalReturn;
        $mysupplier->returnbuybillaftertotalbill += $value->returnbuybillaftertotalbill;
        $mysupplier->returnbuydis += $value->allGenTotalReturn - $value->returnbuybillaftertotalbill;


        if ($key == -1) {
            array_push($buybillDataArr, $mysupplier);
        }
    }

    ##فاتورة  مشتريات ومرتجعات
    foreach ($buyBillDataAndReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value->buybillsupplierid, $existId)) {
            $key = array_search($value->buybillsupplierid, $existId);
            $mysupplier = $buybillDataArr[$key];
        } else {
            $key = -1;
            $mysupplier = new supplierData();
            $mysupplier->supplierid = $value->buybillsupplierid;
            array_push($existId, $value->buybillsupplierid);
        }

        $mysupplier->suppliername = $value->suppliername;
        if ($value->allGenTotalBuyAndReturn >= 0) {
            $mysupplier->totalbuy += $value->allGenTotalBuyAndReturn;
        } else {
            $mysupplier->totalreturn += $value->allGenTotalBuyAndReturn;
        }
        $mysupplier->buybillaftertotalbill += $value->buybillaftertotalbill;
        $mysupplier->buyandreturndis += $value->allGenTotalBuyAndReturn - $value->buybillaftertotalbill;


        if ($key == -1) {
            array_push($buybillDataArr, $mysupplier);
        }
    }

    ##فاتورة  مشتريات البصريات
    foreach ($billsData as $key => $value) {
        if (in_array($value->supplierid, $existId)) {
            $key = array_search($value->supplierid, $existId);
            $mysupplier = $buybillDataArr[$key];
        } else {
            $key = -1;
            $mysupplier = new supplierData();
            $mysupplier->supplierid = $value->supplierid;
            array_push($existId, $value->supplierid);
        }

        $mysupplier->suppliername = $value->suppliername;
        $mysupplier->totalbuy += $value->totalNet;
        $mysupplier->totaldiscount += $value->totaldiscount;

        if ($key == -1) {
            array_push($buybillDataArr, $mysupplier);
        }
    }

    ##فاتورة  مرتجعات البصريات
    foreach ($billsDataReturn as $key => $value) {
        if (in_array($value->supplierid, $existId)) {
            $key = array_search($value->supplierid, $existId);
            $mysupplier = $buybillDataArr[$key];
        } else {
            $key = -1;
            $mysupplier = new supplierData();
            $mysupplier->supplierid = $value->supplierid;
            array_push($existId, $value->supplierid);
        }

        $mysupplier->suppliername = $value->suppliername;
        $mysupplier->totalreturn += $value->supplierreceivevalue;

        if ($key == -1) {
            array_push($buybillDataArr, $mysupplier);
        }
    }

    ##صاقى المشتريات ,واجمالى الخصومات
    //    $t_bure = 0;
    $t_discount = 0;
    foreach ($buybillDataArr as $t_data) {
        //        var_dump($t_data);
        $t_data->t_bure = $t_data->buybillaftertotalbill - $t_data->returnbuybillaftertotalbill;
        $t_data->t_dis = $t_data->buydis - $t_data->returnbuydis + $t_data->buyandreturndis;
        $t_discount += $t_data->t_dis;
    }

    foreach ($buybillDataArr as $dataa) {

        $supplierid = $dataa->supplierid;

        $totalPrice = getSupplierPayedDeptData($supplierid, $datefrom, $dateto);
        $dataa->totalPrice = $totalPrice;
    }



    $smarty->assign("t_discount", $t_discount);
    $smarty->assign("resultsCount", $resultsCount);
    $smarty->assign("buybillDataArr", $buybillDataArr);
}

function showAllOperations($supplierid, $datefrom, $dateto)
{
    global $supplierDeptChangeExt;
    global $buyBillDAO;
    //فواتير المشتريات

    $buybillData = showBuyBillsBySupplierAndDate($supplierid, $datefrom, $dateto);
    //فواتير مردودات المشتريات
    $returnbuybillData = showReturnBuyBillsByClientAndDate($supplierid, $datefrom, $dateto);



    //get from supplierdeptchange table
    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $cliDate = '  DATE(supplierdebtchange.supplierdebtchangedate) >=  "' . $datefrom . '"  AND DATE(supplierdebtchange.supplierdebtchangedate) <= "' . $dateto . '" AND ';
    }
    $supplierShowData = $supplierDeptChangeExt->queryBySupplierIdAndDate($supplierid, $datefrom,$dateto);
    if (count($supplierShowData) > 0) {
        //        print_r($supplierShowData);

        foreach ($supplierShowData as $c) { //when the payment is in the bill must select from the sel bill
            //            print_r('<pre>');
            //            print_r($c);
            //            print_r('<pre>');
            if ($c->tablename == "buybillController.php") {
                $alldata = $buyBillDAO->load($c->supplierdebtchangemodelid);

                $c->supplierdebtchangeamount = $alldata->buybilltotalpayed;
                $totalPrice += $alldata->buybilltotalpayed;
            } else {

                $supplierdebtchangetype = $c->supplierdebtchangetype;
                //print_r($supplierdebtchangetype.'<br>');
                if ($c->tablename != 'supplierController.php') {
                    if ($supplierdebtchangetype == 0) {
                        //$totalPrice += $c->buybilltotalpayed;
                        $totalPrice -= $c->supplierdebtchangeamount;
                    } else {
                        $totalPrice += $c->supplierdebtchangeamount;
                        //$totalPrice -= $c->buybilltotalpayed;
                    }
                } else {
                    $supplierControllerVal = $c->supplierdebtchangeamount;
                }

                //$totalPrice += $c->supplierdebtchangeamount;
            }

            //print_r('<br>$totalPrice = ' . $totalPrice . '  process name =  ' . $c->processname);
        }

        //print_r($supplierShowData);
    }
    //    var_dump($totalPrice);
    //# جمع دفعة فى فاتورة مشتريات على اجمالى الدفعات
    foreach ($buybillData as $data) {
        if ($data->buybilltotalpayed != 0 && $data->conditions == 0) {
            $totalPrice += $data->buybilltotalpayed;
        }
    }

    //# جمع دفعة فى فاتورة المشتريات والمرتجعات على اجمالى الدفعات
    foreach ($returnbuybillData[1] as $data) {
        if ($data->buybilltotalpayed != 0 && $data->conditions == 0) {
            $totalPrice += $data->buybilltotalpayed;
        }
    }

    //print_r('$supplierControllerVal = ' . $supplierControllerVal);
    // assign db results to the template

    return $totalPrice;
}

function getSupplierPayedDeptData($supplierid, $datefrom, $dateto)
{
    global $supplierDeptChangeExt;
    global $buyBillDAO;
    global $returnBuyBillDAO;

    $payed = " - ";
    if ($supplierid > 0) {
        $queryString = ' and supplierid = ' . $supplierid;
        if (isset($datefrom) && !empty($datefrom)) {
            $queryString .= " AND date( supplierdebtchange.supplierdebtchangedate ) >= '" . $datefrom . "' ";
        }
        if (isset($dateto) && !empty($dateto)) {
            $queryString .= "AND date( supplierdebtchange.supplierdebtchangedate ) <= '" . $dateto . "' ";
        }
        // $payedDeptAndPayedDeptInBills = $supplierDeptChangeExt->queryPayedDeptAndPayedDeptInBills($queryString);
        $payedDeptAndPayedDeptInBills = $supplierDeptChangeExt->queryPayedDeptAndPayedDeptInBillsWithoutABS($queryString);
        $payed = $payedDeptAndPayedDeptInBills;

        $qString = ' AND supplierdebtchange.tablename NOT IN("supplierPayedDeptController.php","supplierController.php")';
        if (isset($datefrom) && !empty($datefrom)) {
            $qString .= " AND supplierdebtchange.supplierdebtchangedate >= '" . $datefrom . "' ";
        }
        if (isset($dateto) && !empty($dateto)) {
            $qString .= "AND supplierdebtchange.supplierdebtchangedate <= '" . $dateto . "' ";
        }
        if (!$payed || $payed == null) {
            $payed = 0;
        }

        $supDeptChanges = $supplierDeptChangeExt->queryBySupplierIdNotDeleted($supplierid, $qString);
        if ($supDeptChanges) {
            foreach ($supDeptChanges as $change) {
                if (in_array($change->tablename, ["datedCheckedController.php", "checkwithdrawalController.php"])) {
                    if ($change->supplierdebtchangetype == 0)
                        $payed -= $change->supplierdebtchangeamount;
                    else
                        $payed += $change->supplierdebtchangeamount;
                } elseif ($change->tablename == "buyBillController.php") {
                    $buybillid = $buyBillDAO->load($change->supplierdebtchangemodelid);
                    if ($buybillid->conditions == 0)
                        $payed += $buybillid->buybilltotalpayed;
                } elseif ($change->tablename == "returnBuyBillController.php") {
                    $buyreturnbillid = $returnBuyBillDAO->load($change->supplierdebtchangemodelid);
                    if ($buyreturnbillid->conditions == 0)
                        $payed += $buyreturnbillid->returnbuybilltotalpayed;
                } elseif ($change->tablename == "dailyentry.php") {
                    if ($change->supplierdebtchangetype == 0)
                        $payed -= $change->supplierdebtchangeamount;
                    else
                        $payed += $change->supplierdebtchangeamount;
                }
            }
        }
    }
    return $payed;
}

function showBuyBillsBySupplierAndDate($supplierid, $datefrom, $dateto)
{
    global $buyBillExt;
    global $buyAndReturnBillExt;
    global $buyBillDetailExt;
    global $buyAndReturnBillDetailExt;
    global $smarty;

    $bure = $_POST['bure'];

    $totalBills = 0;
    $totalQTY = 0;

    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $buyBillDate = ' buybill.buybilldate  >= "' . $datefrom . '" and buybill.buybilldate <= "' . $dateto . '" AND ';
        $buyBillReData = 'buyandruternbill.buybilldate  >= "' . $datefrom . '" and buyandruternbill.buybilldate <= "' . $dateto . '" and ';
    }
    $buybillData = $buyBillExt->queryWithSupplierIdAndDate($supplierid, $datefrom, $dateto);

    //get products number in buy bills
    if (count($buybillData) > 0) {
        foreach ($buybillData as $bill) {
            $totalQty1 = $buyBillDetailExt->countProductInBuyBill($bill->buybillid);
            $bill->buyQuantity = $totalQty1;
            if ($bill->conditions == 0) {
                $totalQTY += $totalQty1;
                $totalBills += $bill->buybillaftertotalbill;
            } /* else {
              $totalQTY -= $totalQty1;
              $totalBills -= $bill->buybillaftertotalbill;
              } */
        }
    }


    //get buy bills from buybillandrutern table
    $buybillandruternData = $buyAndReturnBillExt->queryBuyBillsOnlyWithSupplierIdAndDate($supplierid, $datefrom, $dateto);

    //get products number in buybillandrutern
    if (count($buybillandruternData) > 0) {
        foreach ($buybillandruternData as $bill) {

            $bill->userid = -1;
            $buybilldiscounttype = $bill->buybilldiscounttype;
            $buybilldiscount = $bill->buybilldiscount;
            $buybillprice;
            if ($buybilldiscounttype == 1) {
                $buybillprice = ($bill->buybillprice) - ($bill->buybilldiscount);
            } else {

                $buybillprice = ($bill->buybillprice) - ((($bill->buybillprice) * ($bill->buybilldiscount)) / 100);
            }
            $bill->buybillprice = $buybillprice;
            //print_r($bill);
            $totalQty2 = $buyAndReturnBillDetailExt->countProductInBuyBillsOnly($bill->buybillid);
            $bill->buyQuantity = $totalQty2;

            if ($bill->conditions == 0) {
                $totalQTY += $totalQty2;
                $totalBills += $buybillprice; //(($bill->buybillprice)-($bill->buybilldiscount));
            } /* else {
              $totalQTY -= $totalQty2;
              $totalBills -= $buybillprice; //(($bill->buybillprice)-($bill->buybilldiscount));
              } */
        }
    }

    $buybillData = array_merge($buybillData, $buybillandruternData);

    //print_r($buybillData);
    $smarty->assign("buytotalQTY", $totalQTY);
    $smarty->assign("buytotalBills", $totalBills);

    return $buybillData;
}

function showReturnBuyBillsByClientAndDate($supplierid, $datefrom, $dateto)
{
    global $returnBuyBillExt;
    global $buyAndReturnBillExt;
    global $returnBuyBillDetailExt;
    global $buyAndReturnBillDetailExt;
    global $smarty;



    $totalBills = 0;
    $totalQTY = 0;

    $bure = $_POST['bure'];

    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $returnBuyBillDate = ' returnbuybill.returnbuybilldate  >= "' . $datefrom . '" and returnbuybill.returnbuybilldate <= "' . $dateto . '" AND ';
        $selbillandruternReData = '  buyandruternbill.buybilldate  >= "' . $datefrom . '" and buyandruternbill.buybilldate <= "' . $dateto . '" and ';
    }
    $returnbuybillData = $returnBuyBillExt->queryWithSupplierIdAndDate($supplierid, $datefrom, $dateto);

    //get products number in returnbuybill
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            $totalQty1 = $returnBuyBillDetailExt->countProductInBuyBill($bill->returnbuybillid);
            $bill->returnbuyQuantity = $totalQty1;
            if ($bill->conditions == 0) {
                $totalQTY += $totalQty1;
                $totalBills += $bill->returnbuybillaftertotalbill;
            }
        }
    }


    //get return buy bills from buybillandrutern table
    $buybillandruternData = $buyAndReturnBillExt->queryReturnBuyBillsOnlyWithSupplierIdAndDate($supplierid, $datefrom, $dateto);


    if (count($buybillandruternData) > 0) {
        foreach ($buybillandruternData as $buy) {

            $buy->userid = -1;

            $returnbuybillprice = ($buy->returnbuybillprice);


            /////////////////////
            if ($buy->conditions == 0) {
                $totalBills += $returnbuybillprice; //$buy->buybillaftertotalbill;
            }
            /* else {
              $totalBills -= $returnbuybillprice;
              } */

            $buy->returnbuybillid = $buy->buybillid;
            $buy->returnbuybillserial = $buy->buybillserial;
            $buy->returnbuybillaftertotalbill = $buy->buybillaftertotalbill;
            $buy->returnbuybilldate = $buy->buybilldate;
            $totalQty2 = $buyAndReturnBillDetailExt->countProductInReturnBuyBillsOnly($buy->buybillid);
            $buy->buyQuantity = $totalQty2;
            if ($buy->conditions == 0) {
                $totalQTY += $totalQty2;
            }
        }
    }
    $returnbuybillData = array_merge($returnbuybillData, $buybillandruternData);
    $returnbuybill = array($returnbuybillData, $buybillandruternData);

    $smarty->assign("returntotalQTY", $totalQTY);
    $smarty->assign("returntotalBills", $totalBills);

    return $returnbuybill;
}
