HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/supplierReportsController.php
<?php

$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("showallajax", "showallajaxCheques");
if (!in_array($do, $ajaxDoArr)) {
    //the global file operation
    include("../public/impOpreation.php");
}

//global varable
global $showoutside;
include_once("initiateStaticSessionCommingWithCurl.php");

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

require_once('../models/dao/CheckwithdrawalDAO.class.php');
require_once('../models/dto/Checkwithdrawal.class.php');
require_once('../models/mysql/CheckwithdrawalMySqlDAO.class.php');
require_once('../models/mysql/ext/CheckwithdrawalMySqlExtDAO.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');
//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');
//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');
//Currency
require_once('../models/dao/CurrencyDAO.class.php');
require_once('../models/dto/Currency.class.php');
require_once('../models/mysql/CurrencyMySqlDAO.class.php');
require_once('../models/mysql/ext/CurrencyMySqlExtDAO.class.php');

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

//get the do the action
$do = $_GET['do'];
$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");
/* ======================

  Controller Name :- supplierReportsController

  OPERTATION in Controller

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

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

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

//here goes the instances and general variables

$checkWithdrawalDAO = new CheckwithdrawalMySqlDAO;
$checkWithdrawalExtDAO = new CheckwithdrawalMySqlExtDAO;
$checkWithdrawal = new Checkwithdrawal;
//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();
$SavedailyExt = new SavedailyMySqlExtDAO();
//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

$today = $todaydDateOnly = date("Y-m-d");
$smarty->assign('todaydDateOnly', $todaydDateOnly);

$programsettingsdata = $ProgramsettingDAO->load(1);
$smarty->assign('programsettingsdata', $programsettingsdata);

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

    $projectid = $_GET['proid'];
    $smarty->assign("projectid", $projectid);
    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

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

    $saveData = getSaveData();
    $smarty->assign('saveData', $saveData);

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $supplierId = $_POST['supplierId'];
    $saveId = filter_input(INPUT_POST, 'saveId');

    $id = (int) $_GET["id"];
    $smarty->assign("idsearch", $id);

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

      showx($supplierId, $saveId, $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 == "showallajax") {
    showallajax();
} elseif ($do == "showallajaxCheques") {
    showallajaxCheques();
} 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'];
    $order = (int) $_REQUEST['order'];
    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, $order);
    }
    $smarty->display("supplierReportsview/supplierShow.html");
} elseif ($do == "edit") { // تقرير لمورد معين
    include_once("../public/authentication.php");

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

    $alldata = editprint();
    $smarty->assign('alldata', $alldata);
    $smarty->display("supplierReportsview/edit.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    $supplierdebtchangeId = $_POST['id'];
    $comment = $_POST['comment'];
    try {
        $supplierDeptChangeExt->updateComment($comment, $supplierdebtchangeId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} 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");
}
if ($do == "supplierShowforbuyonly") { // تقرير لعميل معين
    include_once("../public/authentication.php");

    $supplierData = $supplierDAO->queryByCondition(0);
    $smarty->assign('supplierData', $supplierData);

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

    $supplierid = $_REQUEST['supplierid'];

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

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

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

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

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

    $supplierid = $_REQUEST['supplierid'];
    $supplierDept = $supplierDAO->load($supplierid);
    $smarty->assign('supplierDept', $supplierDept);
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    if (empty($startDate) && empty($endDate)) {
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
    }

    if (!empty($supplierid) && $supplierid != '-1') {
        ########
        $Programsetting = $ProgramsettingDAO->load(1);
        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
            $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
            $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
        } else {
            $endDate = $endDate . ' 23:59:59';
            $startDate = $startDate . " 00:00:00";
        }
        #############
        if (!empty($supplierid)) {
            $messageData = $supplierDAO->load($supplierid);
            $message = "إسم المورد: " . $messageData->suppliername;
        }
        if (!empty($startDate)) {
            $message .= "<br>التاريخ: من: " . $startDate;
        }
        if (!empty($endDate)) {
            $message .= " إلى: " . $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");
}


$smarty->assign('customSupplierReports', 1);
//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("footer.html");
}

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

function getSupplierData()
{
    global $supplierDAO;
    global $supplierExt;

    // $alldata = $supplierDAO->queryAll();
    $alldata = $supplierExt->queryByCondition(0);
    return $alldata;
}

function getSaveData()
{
    global $SaveDAO;

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

function delete()
{
    //global

    $supplier;
    global $supplierExt;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $supplierDeptChangeExt;
    global $SavedailyExt;
    global $supplierDAO;



    //Transaction
    $mytransactions = new Transaction();
    try {
        $dailyentry = $_GET['dailyentry'];

        $supplierDebtChangeId = $_GET['id'];
        $supplierData = $supplierDeptChangeDAO->load1($supplierDebtChangeId);
        $supplierId = $supplierData->supplierid;
        $dailyentry = $supplierData->dailyentryid;
        //$supplierDebtAfter = $supplierData->supplierdebtchangeafter;
        $supplierDebtBefore = $supplierData->supplierdebtchangebefore;
        $payedDebt = $supplierData->supplierdebtchangeamount;
        $supplierDate = $supplierData->supplierdebtchangedate;
        $supplierDebtBeforeInSuppCurr = $supplierData->debtchangbeforeInSupplierCurrency;
        $payedDebtInSuppCurr = $supplierData->debtchangamountInSupplierCurrency;
        $saveId = $supplierData->saveid;
        //
        $currencyId = $supplierData->currencyId;
        $cFactor = $supplierData->conversionFactor;
        $payedDeptCurr = $supplierData->payedInCurrency;
        $saveConversionFactor = $supplierData->saveConversionFactor;


        $supplierdata = getSupplierDataFromSupplierInUseSP($supplierId);
        $suppData = $supplierDAO->load($supplierId);
        //$supplierData = $supplierDAO->load($supplierId);
        $supplierDebtAfter = $supplierdata->suppliercurrentDebt;
        $supplierDebtAfterInSuppCurr = $suppData->suppliercurrentDebtInCurrency;
        $supplierDebtAfterTotal = $supplierDebtAfter + $payedDebt;
        $supplierDebtAfterTotalInSuppCurr = $supplierDebtAfterInSuppCurr + $payedDebtInSuppCurr;

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

        $supplierExt->updatedept($supplier);
        markSupplierAsNOTInUse($supplierId);

        //insert into supplierdeptchange tbl

        $supplierDeptChange->comment = "delRow" . $supplierDebtChangeId;
        $supplierDeptChange->processname = "الغاء سداد ديون مورد معين";
        $supplierDeptChange->supplierdebtchangeafter = $supplierDebtAfterTotal;
        $supplierDeptChange->supplierdebtchangeamount = $payedDebt;
        $supplierDeptChange->supplierdebtchangebefore = $supplierDebtAfter;
        $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s"); //$supplierDate;
        $supplierDeptChange->supplierdebtchangemodelid = -1;
        $supplierDeptChange->supplierdebtchangetype = 0;
        $supplierDeptChange->tablename = "supplierPayedDeptController.php";
        $supplierDeptChange->userid = $_SESSION['userid'];
        $supplierDeptChange->del = 1;
        $supplierDeptChange->supplierid = $supplierId;
        $supplierDeptChange->dailyentryid = $supplierData->dailyentryid;
        $supplierDeptChange->paytype = 0;
        $supplierDeptChange->supplierdebtchangeid = $supplierDebtChangeId;
        $supplierDeptChange->saveid = $saveId;
        $supplierDeptChange->currencyId = $currencyId;
        $supplierDeptChange->conversionFactor = $cFactor;
        $supplierDeptChange->payedInCurrency = $payedDeptCurr;
        $supplierDeptChange->saveConversionFactor = $saveConversionFactor;
        $supplierDeptChange->debtchangbeforeInSupplierCurrency = $supplierDebtAfterInSuppCurr;
        $supplierDeptChange->debtchangamountInSupplierCurrency = $payedDebtInSuppCurr;
        $supplierDeptChange->debtchangafterInSupplierCurrency = $supplierDebtAfterTotalInSuppCurr;

        $supplierDeptChangeExt->updateDebt($supplierDeptChange);

        $newSupplierDeptChangeId = $supplierDeptChangeDAO->insert1($supplierDeptChange);

        //update save's current value
        //get saveVsalue before and saveValue after mins payedDept
        //get save id
        $queryString = ' tablename = "supplierPayedDeptController.php" and savedailymodelid = ' . $supplierDebtChangeId . ' ';
        $saveDaily = $SavedailyExt->querybyqueryString($queryString);
        $saveid = $saveDaily[0]->saveid;
        $valueData = getSaveValueAndPlus($payedDebt, $saveid, $saveConversionFactor);
        if (count($valueData) > 0) {
            $saveId = $valueData[0];
            $saveValuebefore = $valueData[1];
            $saveValueafter = $valueData[2];
            $payedDeptAmountCurr = $valueData[3]; //needed because of currency
            $saveConversionFactor = $valueData[4]; //needed because of currency
            //update save value after payedDept
            updateSave($saveId, $saveValueafter);
            //insert into savedaily tbl
            insertSavedaily($saveValuebefore, $payedDeptAmountCurr, 0, $saveId, "الغاء سداد ديون مورد", $newSupplierDeptChangeId, $saveValueafter, "supplierReportsController.php");
        }


        reverseEntryWithItsID($dailyentry, 1);
        $mytransactions->commit();
    } catch (Exception $ex) {
        markSupplierAsNOTInUse($supplierId);
        $mytransactions->rollback();
    }
}

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

    $saveData = $SaveExt->loadForUpdateEx($saveid); //$saveDAO->load($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 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 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
    );
}

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

    $id = $_GET["id"];
    $alldata = $supplierDeptChangeDAO->load($id);
    $alldata->savename = R::getCell('select savename from save where saveid = ' . $alldata->saveid);
    return $alldata;
}

//show
function show($startDate, $endDate)
{
    global $supplierDeptChangeExt;
    global $myUserRecord;
    global $smarty;
    $queryString = '';
    $userdata = $myUserRecord->load($_SESSION['userid']);
    if ($userdata->searchinonesave == 1) {
        $queryString = ' and supplierdebtchange.saveid = ' . $userdata->saveid;
    }

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

    $sum;
    foreach ($shownData as $data) {
        $deletdRows = $supplierDeptChangeExt->queryByComment($data->supplierdebtchangeid);
        if (count($deletdRows) <= 0) {
            $sum += $data->supplierdebtchangeamount;
        } else {
            $data->del = 1;
        }
    }
    $smarty->assign('sum', $sum);


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

function showallajax()
{
    global $supplierDeptChangeExt;
    global $ProgramsettingDAO;

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

    $sIndexColumn = "supplierdebtchangeid";

    /* DB table to use */
    $sTable = " supplierdebtchange
		JOIN supplier ON supplier.supplierid  = supplierdebtchange.supplierid
                JOIN user ON user.userid  = supplierdebtchange.userid
                JOIN savedaily on (savedaily.savedailymodelid = supplierdebtchange.supplierdebtchangeid and savedaily.tablename='supplierPayedDeptController.php')
                join save on savedaily.saveid =  save.saveid
		AND supplierdebtchange.tablename = 'supplierPayedDeptController.php' ";

    $aColumns = array('supplierdebtchangeid', 'paySerialNo', 'suppliername', 'supplierdebtchangedate', 'supplierdebtchangebefore', 'supplierdebtchangeamount', 'supplierdebtchangeafter', 'comment', 'employeename', 'savename', 'del', 'supplierdebtchange.dailyentryid', 'supplierdebtchange.tablename');

    // Indexed column (used for fast and accurate table cardinality)

    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
            intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'];
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
                " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "supplierdebtchangedate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }

    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $supplierId = (int) $_REQUEST["supplierId"];
    //   $bure = (int) $_REQUEST["bure"];
    $saveId = (int) $_REQUEST["saveId"];
    $debtchangeid = (int) $_REQUEST["debtchangeid"];
    $Costcenterid = (int) $_REQUEST["Costcenterid"];
    $paySerialNo = (int) $_REQUEST["paySerialNo"];

    $queryString .= '';
    /////

    if (isset($supplierId) && $supplierId > 0) {
        $queryString .= ' supplierdebtchange.supplierid =' . $supplierId . ' AND';
    } else if (isset($supplierId) && $supplierId != "-1" && $supplierId == "-2") {
        //$queryString .= ' supplierdebtchange.supplierid > 0 AND';
    }
    if (isset($saveId) && $saveId > 0) {
        $queryString .= ' save.saveid =' . $saveId . ' AND';
    }
    if (isset($paySerialNo) && $paySerialNo > 0) {
        $queryString .= ' supplierdebtchange.paySerialNo = ' . $paySerialNo . ' AND';
    }

    if (isset($Costcenterid) && $Costcenterid > 0) {
        $queryString .= ' supplierdebtchange.costcenterid =' . $Costcenterid . ' AND';
    }


    if (isset($debtchangeid) && $debtchangeid > 0) {
        $queryString .= ' supplierdebtchange.supplierdebtchangeid = ' . $debtchangeid . ' AND';
    }
    /* serch with date is done below
     * if (isset($startDate) && !empty($startDate)) {
      $startDate = $startDate . " 00:00:00";
      $queryString .= ' supplierdebtchange.supplierdebtchangedate >= "' . $startDate . '" AND';
      }
      if (isset($endDate) && !empty($endDate)) {
      $endDate = $endDate . " 23:59:59";
      $queryString .= ' supplierdebtchange.supplierdebtchangedate <= "' . $endDate . '" AND';
      } */
    if ($bure == 1) { //hide deleted
        $queryString .= ' supplierdebtchange.del = 0 AND';
    }

    ##needed Data
    $Programsetting = $ProgramsettingDAO->load(1);
    ##############
    ##fatma
    //    $search = $_REQUEST['searchDate'];
    //    if ($search == "null" || empty($search)) {
    $search = "dateOnly";
    //    }
    if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "" && $tabDateGuide != "today") {
        if ($search == "dateOnly") {
            //display the converted time ##reportsPlusHours
            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
                $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
                $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
            } else {
                $endDate = $endDate . ' 23:59:59';
                $startDate = $startDate . " 00:00:00";
            }
        }
        $queryString .= ' supplierdebtchange.supplierdebtchangedate >= "' . $startDate . '" and supplierdebtchange.supplierdebtchangedate <= "' . $endDate . '" AND';
        $queryString .= ' savedaily.savedailydate >= "' . $startDate . '" and savedaily.savedailydate <= "' . $endDate . '" AND';
    }

    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;

    $sWhere .= $queryString;
    //----------------------------------------------------------------------


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
    //echo $sQuery;
    //if empty qquery dont go to db
    if ($queryString != "") {
        $rResult = $supplierDeptChangeExt->runSelectQuery($sQuery);

        /* Data set length after filtering */
        /* $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as supplierdebtchangeid  FROM  $sTable "; //$sOrder
          $rResultFilterTotal = $supplierDeptChangeExt->runSelectQuery($sQuery);
          foreach ($rResultFilterTotal as $oneis) {
          $countis = $oneis->supplierdebtchangeid;
          }
          $iFilteredTotal = $countis; */
        /* Total data set length */
        $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as supplierdebtchangeid FROM  $sTable $sWhere ";
        $rResultTotal = $supplierDeptChangeExt->runSelectQuery($sQuery);


        foreach ($rResultTotal as $oneis) {
            $countit = $oneis->supplierdebtchangeid;
        }
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = $countit;
        //make count = count of result not all o available for speed
        $iFilteredTotal = $countit;
    } else {
        //dont get data at all
        $rResultFilterTotal = array();
        $countis = 0;
        $iFilteredTotal = 0;
        $rResultTotal = array();
        $countit = 0;
        $iTotal = 0;
    }




    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    $totalRecits = 0;

    foreach ($rResult as $aRow) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "supplierdebtchangeid":
                    $class = "";
                    if ($aRow->del == 1) {
                        $class = "danger";
                    }
                    $row[] = "<span class='" . $class . "'>$rowno</span>";
                    $row[] = $aRow->$aColumns[0];
                    break;
                case "paySerialNo":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "supplierdebtchangedate":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "supplierdebtchangebefore":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "supplierdebtchangeamount":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "supplierdebtchangeafter":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "comment":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "suppliername":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "employeename":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "savename":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                default:
                    break;
            }
        }
        ////
        $row[] = '<a href="supplierReportsController.php?do=edit&id=' . $aRow->supplierdebtchangeid . '" target="_blank" type="button" class="btn btn-default btn-lg editicon"> </a>';
        $delBtn = '';
        if ($aRow->del == 0) {
            $delBtn = '<a href="#" ><input id="delbtn' . $rowno . '" data-itr="' . $rowno . '" data-action="supplierReportsController.php?do=remove&id=' . $aRow->supplierdebtchangeid . '&dailyentry=' . $aRow->dailyentryid . '" type="button"  class="btn btn-danger pull-right" value="حذف" /> </a>';
        } else {
            $delBtn = 'محذوف';
        }
        $row[] = $delBtn;

        $row[] = '<a target="_blank" href="supplierReportsController.php?do=editprint&id=' . $aRow->supplierdebtchangeid . '" ><input  type="button"  class="btn btn-success pull-right" value="طباعه" /> </a>';
        $row[] = '<a href="dailyentry.php?id=' . $aRow->dailyentryid . '" target="_blank" type="button" class="btn btn-default btn-lg editicon"> </a>'; //pull-right
        ///
        if ($aRow->del == 0) {
            $totalRecits += $aRow->supplierdebtchangeamount;
        }

        $output['data'][] = $row;
        $rowno++;
    }

    //if empty qquery dont go to db
    if ($queryString != "") {
        $output['totals']["totalRecitsResults"] = $totalRecits; //total of shown "search result"
        $sQuery = "SELECT sum(supplierdebtchangeamount) as supplierdebtchangeamount FROM  $sTable $sWhere and del = 0 "; //$sOrder $sLimit
        $rResult = $supplierDeptChangeExt->runSelectQuery($sQuery);
        $output['totals']["totalRecitsAll"] = (float) $rResult[0]->supplierdebtchangeamount; //total of all
    } else {
        $output['totals']["totalRecitsResults"] = 0; //total of shown "search result"
        $output['totals']["totalRecitsAll"] = 0; //total of all
    }

    //print_r($output);
    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

function showallajaxCheques()
{
    global $checkWithdrawalExtDAO;

    $sIndexColumn = "checkwithdrawalid";

    /* DB table to use */
    $sTable = " checkwithdrawal c
                JOIN  bankaccount a ON a.accountid = c.bankaccountid
                JOIN  bank b ON b.bankid = a.bankid
                left JOIN supplier s ON s.supplierid = c.supplierid ";

    $aColumns = array('checkwithdrawalnumber', 'bankname', 'accountname', 'suppliername', 'checkwithdrawalamount', 'c.conditions', 'c.dailyentryid', 'checkwithdrawalid');

    // Indexed column (used for fast and accurate table cardinality)

    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
        $sLimit = "LIMIT " . intval($_POST['start']) . ", " .
            intval($_POST['length']);
    }

    /*
     * Ordering
     */
    $sOrder = "";

    if (isset($_POST['order'][0])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_POST['columns']); $i++) {
            $orderByColumnIndex = $_POST['order'][0]['column'];
            $sOrder .= $aColumns[intval($_POST['columns'][$orderByColumnIndex]['data'])] . "
                " . ($_POST['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc') . ", ";
        }
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY ") {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    // where del =0 and aqarstatus =0 and updatestatus in(1,2,3,4) and complete=1
    $sWhere = '';
    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        $sWhere = " where  (";
        for ($i = 0; $i < count($aColumns); $i++) {
            if ($aColumns[$i] == "checkwithdrawaldate") {
                //to get numbers and english chars only
                ##only alpha numeric is allowed . space not allowed
                $search = preg_replace('/[^#A-Za-z0-9]/', '', $_POST['search']['value']); // Removes special chars.
                if (!empty($search)) {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $search . "%' OR ";
                }
            } else {
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_POST['search']['value'] . "%' OR ";
            }
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ")";
    }
    //-- search ------------------------------------------------------------
    if ($sWhere == '') {
        $queryString = ' WHERE';
    } else {
        $queryString = ' AND';
    }

    $message = "";
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $supplierId = (int) $_REQUEST["supplierId"];

    $queryString .= '';
    /////

    if (isset($supplierId) && $supplierId > 0) {
        $queryString .= ' c.supplierid =' . $supplierId . ' AND';
    } else {
        //$queryString .= ' c.supplierid >0 AND';
    }


    if (isset($startDate) && !empty($startDate)) {
        $queryString .= ' c.checkwithdrawaldate >= "' . $startDate . '" AND';
    }
    if (isset($endDate) && !empty($endDate)) {
        $queryString .= ' c.checkwithdrawaldate <= "' . $endDate . '" AND';
    }
    /*
      ##needed Data
      $Programsetting = $ProgramsettingDAO->load(1);
      ##############
      ##fatma
      //    $search = $_REQUEST['searchDate'];
      //    if ($search == "null" || empty($search)) {
      $search = "dateOnly";
      //    }
      if (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "" && $tabDateGuide != "today") {
      if ($search == "dateOnly") {
      //display the converted time ##reportsPlusHours
      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
      $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
      $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
      } else {
      $endDate = $endDate . ' 23:59:59';
      $startDate = $startDate . " 00:00:00";
      }
      }
      $queryString .= ' supplierdebtchange.supplierdebtchangedate >= "' . $startDate . '" and supplierdebtchange.supplierdebtchangedate <= "' . $endDate . '" AND';
      $queryString .= ' savedaily.savedailydate >= "' . $startDate . '" and savedaily.savedailydate <= "' . $endDate . '" AND';
      }
     */
    $arr = explode(' ', $queryString);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }
        if ($lastWord == 'WHERE') { //remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        }

        //print("<br>queryString: ".$queryString."<br>");
    }

    $totalBills = 0;

    $sWhere .= $queryString;
    //----------------------------------------------------------------------


    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
    //echo $sQuery;
    //if empty qquery dont go to db
    if ($queryString != "") {
        $rResult = $checkWithdrawalExtDAO->runSelectQuery($sQuery);

        /* Data set length after filtering */
        /* $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as checkwithdrawalid  FROM  $sTable "; //$sOrder
          $rResultFilterTotal = $supplierDeptChangeExt->runSelectQuery($sQuery);
          foreach ($rResultFilterTotal as $oneis) {
          $countis = $oneis->checkwithdrawalid;
          }
          $iFilteredTotal = $countis; */
        /* Total data set length */
        $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as checkwithdrawalid FROM  $sTable $sWhere ";
        $rResultTotal = $checkWithdrawalExtDAO->runSelectQuery($sQuery);


        foreach ($rResultTotal as $oneis) {
            $countit = $oneis->checkwithdrawalid;
        }
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = $countit;
        //make count = count of result not all o available for speed
        $iFilteredTotal = $countit;
    } else {
        //dont get data at all
        $rResult = array();
        $rResultFilterTotal = array();
        $countis = 0;
        $iFilteredTotal = 0;
        $rResultTotal = array();
        $countit = 0;
        $iTotal = 0;
    }




    $output = array(
        "draw" => intval(filter_input(INPUT_POST, 'sEcho')), //$_REQUEST['draw'], //intval(filter_input(INPUT_POST, 'sEcho')),
        "recordsTotal" => intval($iTotal),
        "recordsFiltered" => intval($iFilteredTotal),
        "totals" => array(),
        "data" => array()
    );
    $rowno = 1;
    $totalRecits = 0;

    foreach ($rResult as $aRow) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            switch ($aColumns[$i]) {
                case "checkwithdrawalnumber":
                    $class = "";
                    if ($aRow->conditions == 1) {
                        $class = "danger";
                    }
                    $row[] = "<span class='" . $class . "'>" . $aRow->$aColumns[$i] . "</span>";
                    //$row[] = $aRow->$aColumns[0];
                    break;
                case "bankname":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "accountname":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "suppliername":
                    if (empty($aRow->$aColumns[$i])) {
                        $aRow->$aColumns[$i] = 'شراء اصل';
                    }
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "checkwithdrawalamount":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                default:
                    break;
            }
        }
        ////

        $delBtn = '';
        if ($aRow->conditions == 0) {
            $delBtn = '<a href="#"  name="dd" id="delbtn_cheques' . $rowno . '" data-itr="' . $rowno . '" data-action="checkwithdrawalController.php?do=delete&id=' . $aRow->checkwithdrawalid . '&action=' . $aRow->dailyentryid . '"   type="button" class="btn btn-default btn-lg deleteicon"> </a>';
            //$delBtn = '<a href="#" ><input id="delbtn' . $rowno . '" data-itr="' . $rowno . '" data-action="checkwithdrawalController.php?do=delete&id=' . $aRow->checkwithdrawalid . '&action=' . $aRow->dailyentryid . '" type="button"  class="btn btn-danger pull-right" value="حذف" /> </a>';
        } else {
            $delBtn = 'محذوف';
        }
        $row[] = $delBtn;

        $row[] = '<a href="checkwithdrawalController.php?do=edit&id=' . $aRow->checkwithdrawalid . '" type="button" class="btn btn-default btn-lg editicon"></a>';
        $row[] = '<a href="checkwithdrawalController.php?do=editprint&id=' . $aRow->checkwithdrawalid . '" type="button" class="btn btn-default btn-lg printicon"></a>';
        ///
        if ($aRow->conditions == 0) {
            $totalRecits += $aRow->checkwithdrawalamount;
        }

        $output['data'][] = $row;
        $rowno++;
    }

    //if empty qquery dont go to db
    if ($queryString != "") {
        $output['totals']["totalRecitsResults"] = $totalRecits; //total of shown "search result"
        $sQuery = "SELECT sum(checkwithdrawalamount) as checkwithdrawalamount FROM  $sTable $sWhere and c.conditions = 0 "; //$sOrder $sLimit
        $rResult = $checkWithdrawalExtDAO->runSelectQuery($sQuery);
        $output['totals']["totalRecitsAll"] = (float) $rResult[0]->checkwithdrawalamount; //total of all
    } else {
        $output['totals']["totalRecitsResults"] = 0; //total of shown "search result"
        $output['totals']["totalRecitsAll"] = 0; //total of all
    }

    echo json_encode($output, JSON_UNESCAPED_SLASHES);
}

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 if ($data->tablename == "policyController.php") {
                $data->link = "policyController.php?do=edit&policyId=" . $data->clientdebtchangemodelid;
            }
        } 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;
    global $checkWithdrawalExtDAO;


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

    //فواتير مردودات المشتريات
    //from returnbuybill table and buyandruternbill table
    $returnbuybillData = showReturnBuyBillsBySupplierAndDate($supplierid, $startDate, $endDate);
    $queryString = '';
    if (!empty($supplierid)) {
        $queryString .= ' AND supplierdebtchange.supplierid = ' . $supplierid . '';
    }
    if (!empty($_REQUEST['from'])) {
        $queryString .= ' AND date( supplierdebtchange.supplierdebtchangedate ) >= "' . $_REQUEST['from'] . '"';
    }
    if (!empty($_REQUEST['to'])) {
        $queryString .= ' AND date( supplierdebtchange.supplierdebtchangedate ) <= "' . $_REQUEST['to'] . '"';
    }
    //get from supplierdebtchange table
    $SupplierShowData = $supplierDeptChangeExt->queryBySupplierIdAndDateNew_f($queryString);

    //print_r($SupplierShowData);
    if (count($SupplierShowData) > 0) {
        $i = 1;

        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 == "supplierPayedDeptController.php" && $c->del == 1) {
              $c->del = 0;
              $newC = new stdClass();
              $newC->supplierdebtchangetype = 0;
              $newC->processname = 'الغاء سداد ديون مورد معين';
              $newC->del = 1;
              $newC->tablename = $c->tablename;
              $newC->supplierdebtchangeamount = $c->supplierdebtchangeamount;
              $newC->supplierdebtchangemodelid = $c->supplierdebtchangemodelid;
              $newC->supplierdebtchangedate = $c->supplierdebtchangedate;
              $totalPrice += $newC->supplierdebtchangeamount;
              array_splice($SupplierShowData, $i, 0, array($newC));
              //print_r($c);
              //$alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);
              } */
            if ($c->tablename == "buyBillController.php") {
                $alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);

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

                if ($c->supplierdebtchangetype == 0) { //in case of 0 subtract
                    $totalPrice -= $c->supplierdebtchangeamount;
                } else {
                    $totalPrice += $c->supplierdebtchangeamount;
                }
            }

            if ($c->tablename == "checkwithdrawalController.php") {

                $id = $c->supplierdebtchangemodelid;
                $checkdata = $checkWithdrawalExtDAO->queryByIdExt($id);
                $c->bankname = $checkdata->bankname;
                $c->accountname = $checkdata->accountname;
            }
            //print_r($c);
            //$alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);
            //print_r($alldatabuy);
            $i++;
        }
    }

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

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

    // 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, $order)
{
    global $supplierDeptChangeExt;
    global $supplierDAO;
    global $buyBillDAO;
    global $returnBuyBillDAO;
    global $buyAndReturnBillDAO;
    global $smarty;
    global $checkWithdrawalExtDAO;


    $bure = $_POST["bure"];

    $queryString = ' WHERE';


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

        $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>");
    }

    if ($order == 1) {
        $orderBy = " order by supplierdebtchangedate desc ";
    } else {
        $orderBy = " order by supplierdebtchangeid desc ";
    }

    // get the all colums number
    $shownData = $supplierDeptChangeExt->queryBySupplierIdAndDate2($queryString, $orderBy);
    //    var_dump($shownData);
    $i = 1;
    foreach ($shownData as $data) {
        /* if ($data->tablename == "supplierPayedDeptController.php" && $data->del == 1) {
          $data->del = 0;
          $newData = new stdClass();
          $newData->supplierdebtchangeid = $data->supplierdebtchangeid;
          $newData->supplierid = $data->supplierid;
          $newData->supplierdebtchangebefore = $data->supplierdebtchangebefore;
          $newData->supplierdebtchangeamount = $data->supplierdebtchangeamount;
          $newData->supplierdebtchangetype = 0;
          $newData->processname = 'الغاء سداد ديون مورد معين';
          $newData->supplierdebtchangemodelid = $data->supplierdebtchangemodelid;
          $newData->supplierdebtchangeafter = $data->supplierdebtchangeafter;
          $newData->supplierdebtchangedate = $data->supplierdebtchangedate;
          $newData->userid = $data->userid;
          $newData->comment = $data->comment;
          $newData->suppliername = $data->suppliername;
          $newData->finalstring = $data->finalstring;
          $newData->del = 1;
          $newData->tablename = $data->tablename;

          $newData->dailyentryid = $data->dailyentryid;
          $newData->totalbillvalue = $data->supplierdebtchangeamount; //$data->totalbillvalue;
          $newData->buybillpaid = $data->buybillpaid;
          $newData->link = $data->link;

          //$totalPrice += $newData->supplierdebtchangeamount;
          array_splice($shownData, $i, 0, array($newData));
          //$alldatabuy = $buyBillDAO->load($c->supplierdebtchangemodelid);
          } */
        if ($data->tablename == "supplierPayedDeptController.php" && $data->del == 0) {
            $data->totalbillvalue = $data->supplierdebtchangeamount; //$data->totalbillvalue;
        }
        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 = abs($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 = abs($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;

                $id = $data->supplierdebtchangemodelid;
                $checkdata = $checkWithdrawalExtDAO->queryByIdExt($id);
                $data->bankname = $checkdata->bankname;
                $data->accountname = $checkdata->accountname;
            } elseif ($data->tablename == "checkwithdrawalController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "checkwithdrawalController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "supplierController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "supplierController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "supplierPayedDeptController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "supplierReportsController.php?do=editprint&id=" . $data->supplierdebtchangeid;
            } elseif ($data->tablename == "expensesController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "expensesController.php?do=editprint&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "datedCheckedController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "datedCheckedController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            } elseif ($data->tablename == "assetController.php?type=1") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->buybillpaid = $data->supplierdebtchangeamount;
                $data->link = "assetController.php?do=editprint&id=" . $data->supplierdebtchangemodelid . "&type=1";
            } else if ($data->tablename == "policyController.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->link = "policyController.php?do=edit&policyId=" . $data->supplierdebtchangemodelid;
            } else if ($data->tablename == "dailyentry.php") {
                $data->totalbillvalue = $data->supplierdebtchangeamount;
                $data->link = "dailyentry.php?id=" . $data->supplierdebtchangemodelid;
            }
        } else {
            $data->totalbillvalue = $data->supplierdebtchangeamount;
            $data->buybillpaid = $data->supplierdebtchangeamount;
            $data->link = "#";
        }
        $i++;
    }

    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) {



                        $xx->supplierdebtchangeid = -1;
                        $datax->supplierdebtchangeid = -1;
                        break;
                        //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;
    $queryString = '';
    $queryString1 = '';
    if (!empty($supplierid)) {
        $queryString .= ' AND buybill.buybillsupplierid = ' . $supplierid . '';
        $queryString1 .= ' AND buyandruternbill.buybillsupplierid = ' . $supplierid . '';
    }
    if (!empty($startDate)) {
        $queryString .= ' AND buybill.buybilldate >= "' . $startDate . '"';
        $queryString1 .= ' AND buyandruternbill.buybilldate >= "' . $startDate . '"';
    }
    if (!empty($endDate)) {
        $queryString .= ' AND buybill.buybilldate <= "' . $endDate . '"';
        $queryString1 .= ' AND buyandruternbill.buybilldate <= "' . $endDate . '"';
    }

    $buybillData = $buyBillExt->queryWithSupplierIdAndDateNew($queryString);
    //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->queryBuyBillsOnlyWithSupplierIdAndDateNew($queryString1);
    //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;

    $queryString = '';
    $queryString1 = '';
    if (!empty($supplierid)) {
        $queryString .= ' AND returnbuybill.returnbuybillsupplierid = ' . $supplierid . '';
        $queryString1 .= ' AND buyandruternbill.buybillsupplierid = ' . $supplierid . '';
    }
    if (!empty($startDate)) {
        $queryString .= ' AND returnbuybill.returnbuybilldate >= "' . $startDate . '"';
        $queryString1 .= ' AND buyandruternbill.buybilldate >= "' . $startDate . '"';
    }
    if (!empty($endDate)) {
        $queryString .= ' AND returnbuybill.returnbuybilldate <= "' . $endDate . '"';
        $queryString1 .= ' AND buyandruternbill.buybilldate <= "' . $endDate . '"';
    }

    $returnbuybillData = $returnBuyBillExt->queryWithSupplierIdAndDateNew($queryString);
    //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->queryReturnBuyBillsOnlyWithSupplierIdAndDateNew($queryString1);

    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, $saveId, $startDate, $endDate)
{
    global $supplierDeptChangeExt;
    global $supplierdebtchange;
    global $supplierDAO;
    global $myUserRecord;
    global $smarty;
    global $queryString;
    global $SaveDAO;

    $queryString = ' WHERE';
    $message = 'تقرير عجز مورد ';

    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($saveId) && $saveId != "-1") {
        $messageData = $SaveDAO->load($saveId);
        $message .= "  إسم الخزنة: " . $messageData->savename;

        $queryString .= ' supplierdebtchange.saveid =' . $saveId . ' 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';
    }

    $userdata = $myUserRecord->load($_SESSION['userid']);
    if ($userdata->searchinonesave == 1) {
        $queryString .= ' supplierdebtchange.saveid = ' . $userdata->saveid . ' 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->searchPayedDeptOnlyNew($queryString);

    $sum;
    foreach ($shownData as $data) {
        $deletdRows = $supplierDeptChangeExt->queryByComment($data->supplierdebtchangeid);
        if (count($deletdRows) <= 0) {
            $sum += $data->supplierdebtchangeamount;
        } else {
            $data->del = 1;
        }
    }
    $smarty->assign('sum', $sum);


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

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

function getSupplierDataFromSupplierInUseSP($supplier)
{
    global $supplierExt;
    global $supplierDAO;
    if ($supplier == 1) {
        $supplier_data = $supplierDAO->load($supplier);
    } elseif ($supplier > 1) {
        $noOfTries = 0;
        $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        while ($supplier_data->suppliercurrentDebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free supplier=$supplier with redbean");
                R::exec('UPDATE supplier SET  inUse = 0 where supplierid = ' . $supplier);
            }
            $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        }
    }
    return $supplier_data;
}

function markSupplierAsNOTInUse($supplier)
{ //mark as not in use "free him to be able to change debt again"
    global $supplierExt;
    if ($supplier == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $supplierExt->markSupplierAsNOTInUse($supplier);
    }
}

function liveBackupComment($txt)
{
    $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
    $toWrite = "\r\n-- ----------------------------------------------------------------------------------------------------\r\n";
    $toWrite .= $txt;
    $toWrite .= "\r\n-- ----------------------------------------------------------------------------------------------------\r\n\r\n";
    fwrite($myfile, $toWrite);
}

function supplierShowforbuyonly($supplierid, $startDate, $endDate)
{

    global $supplierDeptChangeExt;
    global $smarty;
    global $saveDAO;
    global $myUserRecord;


    $bure = $_POST['bure'];

    $queryString = ' AND';

    $userData = $myUserRecord->load($_SESSION['userid']);
    if ($userData->viewbills == 0) {
        $queryString .= ' user.userid =' . $_SESSION['userid'] . ' AND';
    } else if ($userData->viewbills == 2) {
        $queryString .= ' user.usergroupid =' . $_SESSION['usergroupid'] . ' AND';
    }

    if ($supplierid > 0) {


        $queryString .= ' supplierdebtchange.supplierid =' . $supplierid . ' 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 = $clientDeptChangeExt->clientShowforsellonly($queryString);
    $shownData = $supplierDeptChangeExt->supplierShowAll($queryString);

    //print_r($shownData);

    $i = 1;
    $allPcsPlus = 0;
    $allPcsMinus = 0;
    $allPayed = 0;
    $allTax = 0;

    $showArr = array();
    foreach ($shownData as $data) {

        // إجمالي الفاتورة و إجمالى المستحق من فاتورة المشتريات
        if ($data->tablename == "buyBillController.php") {
            //print("d");
            $data->link = "buyBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            $sellBillData = (object) R::getRow('select * from buybill where buybillid = ' . $data->supplierdebtchangemodelid);

            $saveData = $saveDAO->load($sellBillData->buybillsaveid);
            $data->savename = $saveData->savename;

            $data->sellbilltotalpayed = $sellBillData->buybilltotalpayed; // إجمالي الفاتورة
            $data->sellbillfinalbill = $sellBillData->buybillfinalbill; ////الباقى
            $discount = 0;
            if ($sellBillData->buybilldiscount > 0) {
                if ($sellBillData->buybilldiscountrype == 1)
                    $discount = $sellBillData->buybilldiscount;
                else {
                    $discount = $sellBillData->buybilltotalbill * $sellBillData->buybilldiscount / 100;
                }
            }

            $data->tax = ($sellBillData->buybilltotalbill - $discount) * $sellBillData->payedtax / 100;
            $allTax += $data->tax;


            $myselldata = R::getAll('select buybilldetail.* ,product.productName, productcat.productCatName ,unit.unitName
                from buybilldetail
                JOIN product ON buybilldetail.buybilldetailproductid = product.productId
                JOIN productunit ON buybilldetail.productunitid = productunit.productunitid
		JOIN unit ON unit.unitId = productunit.unitid
		JOIN productcat ON productcat.productCatId = product.productCatId
                where buybillid=' . $data->supplierdebtchangemodelid);
            //array to object
            $myselldata = array_map(function ($array) {
                return (object) $array;
            }, $myselldata);
            foreach ($myselldata as $sellData) {
                if (!$bure || ($bure == 1 && $sellBillData->conditions == 0)) {
                    $allPayed += $sellData->buybilldetailtotalprice;
                    $allPcsPlus += $sellData->buybilldetailquantity;
                }
            }
            $smarty->assign('myselldata' . $i, $myselldata);

            if ($sellBillData->conditions == 0) {
                $data->mysellData = $myselldata;
                array_push($showArr, $data);
            }

            //print_r($myselldata);
            $i++;
        } else if ($data->tablename == "returnBuyBillController.php") {
            $data->link = "returnBuyBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;
            $returnSellBillData = (object) R::getRow('select * from returnbuybill where returnbuybillid = ' . $data->supplierdebtchangemodelid);

            $saveData = $saveDAO->load($returnSellBillData->returnbuybillsaveid);
            $data->savename = $saveData->savename;

            $data->sellbilltotalpayed = $returnSellBillData->returnbuybilltotalpayed; // إجمالي الفاتورة
            $data->sellbillfinalbill = $returnSellBillData->returnbuybillfinalbill; ////الباقى
            if ($returnSellBillData->returnbuybilldiscount > 0) {
                if ($returnSellBillData->returnbuybilldiscountrype == 1)
                    $discount = $returnSellBillData->returnbuybilldiscount;
                else {
                    $discount = $returnSellBillData->returnbuybilltotalbill * $returnSellBillData->returnbuybilldiscount / 100;
                }
            }

            $tax = ($returnSellBillData->returnbuybilltotalbill - $discount) * $returnSellBillData->payedtax / 100;
            $data->tax = $tax * -1;
            $allTax += $data->tax;

            $myselldata = R::getAll('select returnbuybilldetail.*,product.productName, productcat.productCatName ,unit.unitName
                    from returnbuybilldetail
                    JOIN product ON returnbuybilldetail.returnbuybilldetailproductid = product.productId
                    JOIN productunit ON returnbuybilldetail.productunitid = productunit.productunitid
                    JOIN unit ON unit.unitId = productunit.unitid
                    JOIN productcat ON productcat.productCatId = product.productCatId
                    where returnbuybillid=' . $data->supplierdebtchangemodelid);
            //array to object
            $myselldata = array_map(function ($array) {
                return (object) $array;
            }, $myselldata);
            foreach ($myselldata as $sellData) {
                if (!$bure || ($bure == 1 && $returnSellBillData->conditions == 0)) {
                    $allPcsMinus += $sellData->returnbuybilldetailquantity;
                    $allPayed -= $sellData->returnbuybilldetailtotalprice;
                }
            }
            $smarty->assign('myselldata' . $i, $myselldata);


            if ($returnSellBillData->conditions == 0) {
                $data->mysellData = $myselldata;
                array_push($showArr, $data);
            }

            $i++;
        } else if ($data->tablename == "buyAndReturnBillController.php") {
            $data->link = "buyAndReturnBillController.php?do=details&id=" . $data->supplierdebtchangemodelid;

            $sellAndReturnBillData = (object) R::getRow('select * from buyandruternbill where buybillid = ' . $data->supplierdebtchangemodelid);

            $saveData = $saveDAO->load($sellAndReturnBillData->buybillsaveid);
            $data->savename = $saveData->savename;

            $data->sellbilltotalpayed = $sellAndReturnBillData->buybilltotalpayed; // إجمالي الفاتورة
            $data->sellbillfinalbill = $sellAndReturnBillData->buybillfinalbill; ////الباقى

            $myselldata = R::getAll('select buyandruternbilldetail.*,product.productName, productcat.productCatName ,unit.unitName
                     from buyandruternbilldetail
                     JOIN product ON ON buyandruternbilldetail.buybilldetailproductid = product.productId
                     JOIN productunit ON buyandruternbilldetail.productunitid = productunit.productunitid
                     JOIN unit ON unit.unitId = productunit.unitid
                     JOIN productcat ON productcat.productCatId = product.productCatId
                     where buybillid=' . $data->supplierdebtchangemodelid);
            //array to object
            $myselldata = array_map(function ($array) {
                return (object) $array;
            }, $myselldata);

            foreach ($myselldata as $sellData) {
                if (!$bure || ($bure == 1 && $sellAndReturnBillData->conditions == 0)) {
                    if ($sellData->selltype != 1) {
                        $allPayed += $sellData->buybilldetailtotalprice;
                        $allPcsPlus += $sellData->buybilldetailquantity;
                    } else {
                        $allPayed -= $sellData->buybilldetailtotalprice;
                        $allPcsMinus += $sellData->buybilldetailquantity;
                    }
                }
            }

            $smarty->assign('myselldata' . $i, $myselldata);


            if ($sellAndReturnBillData->conditions == 0) {
                $data->mysellData = $myselldata;
                array_push($showArr, $data);
            }
            $i++;
        } elseif ($data->tablename != "buyBillController.php" && $data->tablename != "returnBuyBillController.php" && $data->tablename != "buyAndReturnBillController.php") {
            //unset($data->mysellData);
            $data->sellbilltotalpayed = $data->supplierdebtchangeamount; // التغير
            $smarty->assign('myselldata' . $i, array());
            array_push($showArr, $data);
            $i++;
        }
    }

    $smarty->assign('allPayed', $allPayed);
    $smarty->assign('allPcsPlus', $allPcsPlus);
    $smarty->assign('allPcsMinus', $allPcsMinus);
    $smarty->assign('allTax', $allTax);


    // assign db results to the template
    if ($bure == 1) {
        $smarty->assign('shownData', $showArr);
    } else {
        $smarty->assign('shownData', $shownData);
    }
}