<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.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');
//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');

//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 :- supplierReportsController

  OPERTATION in Controller

  1- عرض تقرير دفعات
  2-  تقرير لمورد معين

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

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

//here goes the instances and general variables
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
//$buyBillDAO->load();
$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();
//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();
//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();

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

//check and use the condition that suite this action
if (empty($do) || $do == "show") {// تقرير دفعات
    //here the permssion check
    include_once("../public/authentication.php");

    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $supplierId = $_POST['supplierId'];

    if ((isset($supplierId) && $supplierId != "-1") || (!empty($startDate) && !empty($endDate))) {
        $messageData = $supplierDAO->load($supplierId);
        $message = " اسم المورد : " . $messageData->suppliername . "التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        showx($supplierId, $startDate, $endDate);
    } else {
        //showall();
        show($today, $today);
    }
    /* if(isset($startDate) && isset($endDate) && $startDate !="" && $endDate !="")
      {
      $message = "التاريخ: من: ".$startDate." إلى: ".$endDate;
      $smarty->assign("message",$message);

      show($startDate, $endDate);
      }

      else
      {
      $today=date("Y-m-d");
      show($today, $today);
      } */
    $smarty->assign("customSupplierReports", 1);
    $smarty->display("supplierReportsview/show.html");
} elseif ($do == "remove") {
    include_once("../public/authentication.php");
    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");

        print_r($e);
    }
} elseif ($do == "oneSupplier") { // تقرير لمورد معين
    include_once("../public/authentication.php");

    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);

    $supplierid = $_REQUEST['supplierid'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    if (!empty($supplierid) && $supplierid != '-1' || !empty($startDate) && !empty($endDate) && $startDate != "" && $endDate != "") {
        $messageData = $supplierDAO->load($supplierid);
        $message = "إسم المورد: " . $messageData->suppliername;
        $message .= "<br>التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        supplierShow($supplierid, $startDate, $endDate);
    }
    $smarty->display("supplierReportsview/supplierShow.html");
} elseif ($do == "editprint") { // تقرير لمورد معين
    include_once("../public/authentication.php");

    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);

    $alldata = editprint();
    $smarty->assign('alldata', $alldata);

    //print_r($alldata);

    $smarty->display("supplierReportsview/editprint.html");
} else if ($do == "all") {//تقارير الموردين (الدفعات)
    //عرض فواتير المشتريات والمردودات والعمليات الأخرى للمورد
    include_once("../public/authentication.php");

    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);

    $supplierid = $_REQUEST['supplierid'];
    $supplierDept = $supplierDAO->load($supplierid);
    $smarty->assign('supplierDept', $supplierDept);
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    if (!empty($supplierid) && $supplierid != '-1' && !empty($startDate) && !empty($endDate) && $startDate != "" && $endDate != "") {
        $messageData = $supplierDAO->load($supplierid);
        $message = "إسم المورد: " . $messageData->suppliername;
        $message .= "<br>التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        showAllOperations($supplierid, $startDate, $endDate);
    }
    $smarty->display("supplierReportsview/reportForAll.html");
} 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 getSupplierData() {
    global $supplierDAO;
    global $supplierExt;

    $alldata = $supplierDAO->queryAll();
    return $alldata;
}

function delete() {
    global $supplier;
    global $supplierExt;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $supplierDeptChangeExt;

    $dailyentry = $_GET['dailyentry'];

    $supplierDebtChangeId = $_GET['id'];
    $supplierData = $supplierDeptChangeDAO->load($supplierDebtChangeId);
    $supplierId = $supplierData->supplierid;
    $supplierDebtAfter = $supplierData->supplierdebtchangeafter;
    $supplierDebtBefore = $supplierData->supplierdebtchangebefore;
    $payedDebt = $supplierData->supplierdebtchangeamount;
    $supplierDate = $supplierData->supplierdebtchangedate;

    $supplierDebtAfterTotal = $supplierDebtAfter + $payedDebt;

    $supplier->suppliercurrentDebt = $supplierDebtAfterTotal;
    $supplier->userid = $_SESSION['userid'];
    $supplier->supplierdate = $supplierDate;
    $supplier->supplierid = $supplierId;

    $supplierExt->updatedept($supplier);

    //insert into supplierdeptchange tbl

    $supplierDeptChange->comment = "";
    $supplierDeptChange->processname = "الغاء سداد ديون مورد معين";
    $supplierDeptChange->supplierdebtchangeafter = $supplierDebtAfterTotal;
    $supplierDeptChange->supplierdebtchangeamount = $payedDebt;
    $supplierDeptChange->supplierdebtchangebefore = $supplierDebtAfter;
    $supplierDeptChange->supplierdebtchangedate = $supplierDate;
    $supplierDeptChange->supplierdebtchangemodelid = -1;
    $supplierDeptChange->supplierdebtchangetype = 1;
    $supplierDeptChange->tablename = "supplierPayedDeptController.php";
    $supplierDeptChange->userid = $_SESSION['userid'];
    $supplierDeptChange->del = 1;
    $supplierDeptChange->supplierid = $supplierId;
    $supplierDeptChange->dailyentryid = $supplierData->dailyentryid;
    $supplierDeptChange->paytype = 0;



    $supplierDeptChangeExt->updateDebt($supplierDeptChange);
    $supplierDeptChangeId = $supplierDeptChangeDAO->insert1($supplierDeptChange);

    //update save's current value
    //get saveVsalue before and saveValue after mins payedDept
    $valueData = getSaveValueAndMins($payedDebt);
    if (count($valueData) > 0) {
        $saveId = $valueData[0];
        $saveValuebefore = $valueData[1];
        $saveValueafter = $valueData[2];

        //update save value after payedDept
        updateSave($saveId, $saveValueafter);
        //insert into savedaily tbl
        insertSavedaily($saveValuebefore, $payedDebt, 1, $saveId, "الغاء سداد ديون مورد", $supplierDeptChangeId, $saveValueafter, "supplierReportsController.php");
    }


    reverseEntryWithItsID($dailyentry);
}

function getSaveValueAndMins($savevaluechanged) {
    global $Save;
    global $SaveDAO;

    $saveData = $SaveDAO->load($_SESSION['saveid']);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update Save tbl
function updateSave($saveid, $savevalueafter) {
    global $Save;
    global $SaveExt;

    //update savecurrentvalue 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) {

    //to use the variable out side the funcion
    global $Savedaily;
    global $SavedailyDAO;

    //insert in Savedaily tbl
    $Savedaily->savedailydate = date("Y-m-d");
    $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);
}

//editprint
function editprint() {
    global $supplierDeptChangeExt;
    global $supplierDeptChangeDAO;

    $id = $_GET["id"];
    $alldata = $supplierDeptChangeDAO->load($id);

    return $alldata;
}

//show
function show($startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $smarty;


    // get the all colums number
    $shownData = $supplierDeptChangeExt->queryPayedDeptOnly($startDate, $endDate);

    $sum;
    foreach ($shownData as $data) {
        $sum += $data->supplierdebtchangeamount;
    }
    $smarty->assign('sum', $sum);

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

function supplierShow2($supplierid, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $smarty;


    // get the all colums number
    $shownData = $supplierDeptChangeExt->queryBySupplierIdAndDate($supplierid, $startDate, $endDate);


    foreach ($shownData as $data) {
        if ($data->supplierdebtchangemodelid != -1) {

            if ($data->tablename == "buyBillController.php") {
                $data->link = "buyBillController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "returnBuyBillController.php") {
                $data->link = "returnBuyBillController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "buyAndReturnBillController.php") {
                $data->link = "buyAndReturnBillController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "kempialaController.php") {
                $data->link = "kempialaController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "checkwithdrawalController.php") {
                $data->link = "checkwithdrawalController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            }
        } else {
            $data->link = "#";
        }
    }

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

function showAllOperations($supplierid, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $sellBillDAO;
    global $buyBillDAO;
    global $returnBuyBillDAO;
    global $smarty;
    global $myBuybillandruternRecord;

    //فواتير المشتريات
    //from buybill table and buyandruternbill table
    $buybillData = showBuyBillsBySupplierAndDate($supplierid, $startDate, $endDate);

    //فواتير مردودات المشتريات
    //from returnbuybill table and buyandruternbill table
    $returnbuybillData = showReturnBuyBillsBySupplierAndDate($supplierid, $startDate, $endDate);

    //get from supplierdebtchange table
    $SupplierShowData = $supplierDeptChangeExt->queryBySupplierIdAndDate($supplierid, $startDate, $endDate);

    //print_r($SupplierShowData);
    if (count($SupplierShowData) > 0) {
        foreach ($SupplierShowData as $c) {//when the money form buy bill must select form the buy bill table
            // ihis is canceld  not selected now
            if ($c->tablename == "buyBillController.php") {
                $alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);

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

                if ($c->supplierdebtchangetype == 0) {
                    $totalPrice += $c->supplierdebtchangeamount;
                } else {
                    $totalPrice -= $c->supplierdebtchangeamount;
                }
            }
            //print_r($c);
            $alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);

            //print_r($alldatabuy);
        }
    }

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

///nora//////////////////

function supplierShow($supplierid, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $supplierDAO;
    global $buyBillDAO;
    global $returnBuyBillDAO;
    global $buyAndReturnBillDAO;
    global $smarty;


    $bure = $_POST["bure"];

    $queryString = ' WHERE';


    if (isset($supplierid) && $supplierid != '-1') {
        $suppliernamedata = $supplierDAO->load($supplierid);
        $message = " اسم المورد " . $suppliernamedata->suppliername;
        $smarty->assign('message', $message);

        $queryString .= ' supplierdebtchange.supplierid =' . $supplierid . ' AND';
    }

    if (!empty($startDate) && !empty($endDate)) {

        $message = " تقرير عميل من تاريخ  " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);

        $queryString .= '  date( supplierdebtchange.supplierdebtchangedate ) >= "' . $startDate . '" AND date( supplierdebtchange.supplierdebtchangedate ) <= "' . $endDate . '" AND';
    }

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

    // get the all colums number
    $shownData = $supplierDeptChangeExt->queryBySupplierIdAndDate2($queryString);


    foreach ($shownData as $data) {

        if ($data->supplierdebtchangemodelid != -1) {

            if ($data->tablename == "buyBillController.php") {
                $buybillid = $buyBillDAO->load($data->supplierdebtchangemodelid);
                $data->totalbillvalue = $buybillid->buybillaftertotalbill;
                $data->buybillpaid = $buybillid->buybilltotalpayed;
                $data->link = "buyBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "returnBuyBillController.php") {
                $buyreturnbillid = $returnBuyBillDAO->load($data->supplierdebtchangemodelid);
                $data->totalbillvalue = $buyreturnbillid->returnbuybillaftertotalbill;
                $data->buybillpaid = $buyreturnbillid->returnbuybilltotalpayed;
                $data->link = "returnBuyBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "buyAndReturnBillController.php") {
                $buyAndReturnBill = $buyAndReturnBillDAO->load($data->supplierdebtchangemodelid);
                $data->totalbillvalue = $buyAndReturnBill->buybillaftertotalbill;
                $data->buybillpaid = $buyAndReturnBill->buybilltotalpayed;
                $data->link = "buyAndReturnBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "kempialaController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "kempialaController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "checkwithdrawalController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "checkwithdrawalController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            }
        } else {
            $data->totalbillvalue = $data->supplierdebtchangeamount;
            $data->buybillpaid = $data->supplierdebtchangeamount;
            $data->link = "#";
        }
    }


    if ($bure == "1") {

        $smarty->assign('burex', $bure);
        foreach ($shownData as $datax) {
            //print_r($datax);

            $finalstring = $datax->finalstring;

            //print_r($finalstring.'<br>');
            $type = $datax->supplierdebtchangetype;
            $supplierdebtchangeid = $datax->supplierdebtchangeid;



            if ($type == 1) {

                $otherfinal = substr_replace($finalstring, '0', -1);

                foreach ($shownData as $xx) {

                    if ($xx->finalstring == $otherfinal) {



                        $xx->supplierdebtchangeid = -1;
                        $datax->supplierdebtchangeid = -1;

                        print_r($datax->supplierdebtchangeid . '<br>');
                    }
                }
            }
        }
    }



    $ii = 0;
    //select all data from storemovement
    $startvalue = 0;
    $startbefore = 0;
    $startafter = 0;

    foreach ($shownData as $mov) {


        if ($bure == "1" && $mov->supplierdebtchangeid > 0) {


            if ($ii == 0) {

                $startvalue = $mov->supplierdebtchangeamount;
                $mov->supplierdebtchangeamount = $startvalue;
                $startbefore = $mov->supplierdebtchangebefore;
                $mov->supplierdebtchangebefore = $startbefore;
                $startafter = $mov->supplierdebtchangeafter;
                $mov->supplierdebtchangeafter = $startafter;
            } else {

                $startvalue = $mov->supplierdebtchangeamount;
                $mov->supplierdebtchangeafter = $startbefore;

                if ($mov->supplierdebtchangetype == "1") {

                    //print_r('in if<br>');
                    $mov->supplierdebtchangebefore = $startbefore + $startvalue;
                    $startbefore = $startbefore + $startvalue;
                } else {
                    //print_r('in else if<br>');
                    //print_r('startafter'.$startbefore .'<br>');
                    //print_r('startvalue'.$startbefore .'<br>');
                    //	print_r($startafter - $startvalue .'<br>');
                    $mov->supplierdebtchangebefore = $startbefore - $startvalue;
                    $startbefore = $startbefore - $startvalue;
                }


                //new product name with all path
            }





            $ii++;
        }
    }


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

function showBuyBillsBySupplierAndDate($supplierid, $startDate, $endDate) {
    global $buyBillExt;
    global $buyAndReturnBillExt;
    global $buyBillDetailExt;
    global $buyAndReturnBillDetailExt;
    global $smarty;

    $totalBills = 0;
    $totalQTY = 0;

    $buybillData = $buyBillExt->queryWithSupplierIdAndDate($supplierid, $startDate, $endDate);
    //get products number in buy bills

    if (count($buybillData) > 0) {
        foreach ($buybillData as $bill) {
            $totalQty1 = $buyBillDetailExt->countProductInBuyBill($bill->buybillid);
            $bill->totalQty = $totalQty1;
            $totalQTY += $totalQty1;
            $totalBills += $bill->buybillaftertotalbill;
        }
    }

    //get buy bills from  buyandruternbill table
    $buybillandruternData = $buyAndReturnBillExt->queryBuyBillsOnlyWithSupplierIdAndDate($supplierid, $startDate, $endDate);
    //get products number in  buyandruternbill
    if (count($buybillandruternData) > 0) {
        foreach ($buybillandruternData as $bill) {
            $buybillid = $bill->buybillid;
            $buybilldiscountrype = $bill->buybilldiscountrype;
            $buybilldiscount = $bill->buybilldiscount;

            $allmydetales = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buybillid, 0);
            //	print_r($allmydetales);

            $mytotal = 0;
            foreach ($allmydetales as $myallmydetales) {

                $buybilldetailtotalprice = $myallmydetales->buybilldetailtotalprice;
                $mytotal += $buybilldetailtotalprice;
            }

            //print_r('<br>');
            //print_r($mytotal);
            $myfialtotal = 0;
            //خصم مباشر
            if ($buybilldiscountrype == 0) {
                //print_r("in if <br>".$buybilldiscount);
                $myfialtotal = $mytotal - $buybilldiscount;
            } else {
                //print_r("in else <br>".$buybilldiscount.'<br>');
                //print_r((($mytotal*$buybilldiscount)/100).'<br>');
                $myfialtotal = $mytotal - (($mytotal * $buybilldiscount) / 100);
            }

            $bill->buybillaftertotalbill = $myfialtotal;
            $totalQty2 = $buyAndReturnBillDetailExt->countProductInBuyBillsOnly($bill->buybillid);
            $bill->totalQty = $totalQty2;
            $totalQTY += $totalQty2;
            $totalBills += $bill->buybillaftertotalbill;
        }
    }

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

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

    return $buybillData;
}

function showReturnBuyBillsBySupplierAndDate($supplierid, $startDate, $endDate) {
    global $returnBuyBillExt;
    global $buyAndReturnBillExt;
    global $returnBuyBillDetailExt;
    global $buyAndReturnBillDetailExt;
    global $smarty;

    $totalBills = 0;
    $totalQTY = 0;

    $returnbuybillData = $returnBuyBillExt->queryWithSupplierIdAndDate($supplierid, $startDate, $endDate);
    //get products number in return buy bills
    if (count($returnbuybillData) > 0) {
        foreach ($returnbuybillData as $bill) {
            //print_r($bill);
            if ($bill->returnbuybillaftertotalbill < 0) {
                $bill->returnbuybillaftertotalbill = ($bill->returnbuybillaftertotalbill * -1 );
            }
            $totalQty1 = $returnBuyBillDetailExt->countProductInBuyBill($bill->returnbuybillid);
            $bill->totalQty = $totalQty1;
            $totalQTY += $totalQty1;
            if ($bill->returnbuybillaftertotalbill > 0) {
                $totalBills += $bill->returnbuybillaftertotalbill;
            } else {

                $totalBills -= $bill->returnbuybillaftertotalbill;
            }
        }
    }


    //get return buy bills from  buyandruternbill table
    $buybillandruternData = $buyAndReturnBillExt->queryReturnBuyBillsOnlyWithSupplierIdAndDate($supplierid, $startDate, $endDate);

    if (count($buybillandruternData) > 0) {
        foreach ($buybillandruternData as $buy) {
            $buy->returnbuybillid = $buy->buybillid;

            $allmydetales = $buyAndReturnBillDetailExt->queryByBuybillidANDType($buy->buybillid, 1);
            //	print_r($allmydetales);

            $mytotal = 0;
            foreach ($allmydetales as $myallmydetales) {

                $buybilldetailtotalprice = $myallmydetales->buybilldetailtotalprice;
                $mytotal += $buybilldetailtotalprice;
            }

            $buy->buybillaftertotalbill = $mytotal;

            $buy->returnbuybillSerial = $buy->buybillSerial;
            $buy->returnbuybillaftertotalbill = $buy->buybillaftertotalbill;
            $buy->returnbuybilldate = $buy->buybilldate;

            $totalQty2 = $buyAndReturnBillDetailExt->countProductInReturnBuyBillsOnly($buy->buybillid);
            $buy->totalQty = $totalQty2;
            $totalQTY += $totalQty2;
            $totalBills += $mytotal; //$bill->buybillaftertotalbill;
        }
    }
    $returnbuybillData = array_merge($returnbuybillData, $buybillandruternData);

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

    return $returnbuybillData;
}

function showx($supplierId, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $supplierdebtchange;
    global $supplierDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($supplierId) && $supplierId != "-1" && $supplierId != "-2") {
        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid =' . $supplierId . ' AND';
    }

    if (isset($supplierId) && $supplierId != "-1" && $supplierId == "-2") {

        $message = " كل الموردين ";
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid > 0 AND';
    }


    if (!empty($startDate) && !empty($endDate)) {



        $message = " تقرير عجز مورد من تاريخ " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);


        $queryString .= ' supplierdebtchange.supplierdebtchangedate >= "' . $startDate . '" AND supplierdebtchange.supplierdebtchangedate <= "' . $endDate . '" AND';
    }

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

    $shownData = $supplierDeptChangeExt->searchPayedDeptOnly($queryString);

    $sum;
    foreach ($shownData as $data) {
        $sum += $data->supplierdebtchangeamount;
    }
    $smarty->assign('sum', $sum);

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

?>