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/supplierPayedDeptController.php
<?php

/////////////////////    سداد ديون مورد معين
//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");
//global varable
global $showoutside;

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


//here the db files that include in the file
include("../public/include_dao.php");
include("../library/uploadImages.php");
include '../library/Classes/PHPExcel/IOFactory.php';

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

//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.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');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');

//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/BankDAO.class.php');
require_once('../models/dto/Bank.class.php');
require_once('../models/mysql/BankMySqlDAO.class.php');
require_once('../models/mysql/ext/BankMySqlExtDAO.class.php');

//get the do the action
$do = isset($_GET['do']) ? $_GET['do'] : '';

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

  Controller Name :- supplierPayedDeptController

  OPERTATION in Controller

  1- display add form
  2- add row in supplierdebtchange tbl
  3- update supplier dept in supplier tbl
  ======================== */
if ($_POST['curlpost'] != 1) {
    //here the global templates
    $smarty->display("header.html");
}

//here goes the instances and general variables

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


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

//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();
//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();

$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();

//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();

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

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
eval(base64_decode("ZnVuY3Rpb24gZ2VuZXJhdGVVVUlEKCkgewogICAgJGhvc3RuYW1lID0gZXhwbG9kZSgnY29udHJvbGxlcnMnLCAkX1NFUlZFUlsnU0NSSVBUX1VSSSddKVswXTsgLy9nZXRob3N0bmFtZSgpOwogICAgJGhvc3RuYW1lID0gc3RyX3JlcGxhY2UoYXJyYXkoImh0dHA6Ly8iLCAiaHR0cHM6Ly8iKSwgIiIsICRob3N0bmFtZSk7CgogICAgLy8gR2VuZXJhdGUgYW4gTUQ1IGhhc2ggb2YgdGhlIGlucHV0CiAgICAkZGF0YSA9IG1kNSgkaG9zdG5hbWUpOwogICAgLy8gRm9ybWF0IHRoZSBoYXNoIGFzIGEgVVVJRAogICAgJHV1aWQgPSBzcHJpbnRmKAogICAgICAgICAgICAnJTA4cy0lMDRzLSUwNHgtJTA0eC0lMTJzJywKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCAwLCA4KSwKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCA4LCA0KSwKICAgICAgICAgICAgKGhleGRlYyhzdWJzdHIoJGRhdGEsIDEyLCA0KSkgJiAweDBmZmYpIHwgMHg0MDAwLAogICAgICAgICAgICAoaGV4ZGVjKHN1YnN0cigkZGF0YSwgMTYsIDQpKSAmIDB4M2ZmZikgfCAweDgwMDAsCiAgICAgICAgICAgIHN1YnN0cigkZGF0YSwgMjAsIDEyKQogICAgKTsKICAgICR1dWlkID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICR1dWlkKTsKICAgIHJldHVybiAkdXVpZDsKfQ=="));
eval(base64_decode("ZnVuY3Rpb24gc2VyaWFsY2hlY2soKSB7CiAgICBpZiAoc3RydG91cHBlcihzdWJzdHIoUEhQX09TLCAwLCAzKSkgPT09ICdXSU4nKSB7CiAgICAgICAgLy91dWlkIG9mIHdpbmRvd3MKICAgICAgICBleGVjKCdDOlxXaW5kb3dzXFN5c3RlbTMyXHdiZW1cd21pYyBjc3Byb2R1Y3QgZ2V0ICJVVUlEIicsICRtYWNhZGRyZXNzLCAkaXNFeGVjdXRlZCk7CiAgICAgICAgJG1hY2FkZHJlc3MgPSAkbWFjYWRkcmVzc1sxXTsKICAgICAgICAkbWFjID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICRtYWNhZGRyZXNzKTsKICAgIH0gZWxzZSB7Ly9ub3Qgd2luZG93cyB1c2UgbGludXggbWFjCiAgICAgICAgJG1hYyA9IGdlbmVyYXRlVVVJRCgpOwogICAgfQoKICAgICRyYW5kb21fc2FsdCA9IGhhc2goJ3NoYTUxMicsICcxMzA1Jyk7CiAgICAvLyBDcmVhdGUgc2FsdGVkIHBhc3N3b3JkCiAgICAkaGFzaGVkTWFjID0gaGFzaCgnc2hhNTEyJywgJG1hYyAuICRyYW5kb21fc2FsdCk7CiAgICByZXR1cm4gJGhhc2hlZE1hYzsKfQ=="));
eval(base64_decode("JHNlcmlhbENhbCA9IHNlcmlhbGNoZWNrKCk7CmlmICgoJHByb2ctPnNlcmlhbCAhPSAkc2VyaWFsQ2FsICYmICRwcm9nLT5zZXJpYWwyICE9ICRzZXJpYWxDYWwpIHx8ICRfU0VTU0lPTlsnbGljX2RhdGV0byddIDwgZGF0ZSgnWS1tLWQnKSkgewogICAgLy9zZW5kIHRoZSB1c2VyIHRvIHRoZSBsb2dvdXQgcGFnZQogICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dvdXQucGhwIik7CiAgICBleGl0KCk7Cn0="));

//bank
$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExtDAO = new BankMySqlExtDAO;

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

//check and use the condition that suite this action
$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
eval(base64_decode("aWYgKCFmdW5jdGlvbl9leGlzdHMoJ3NlcmlhbGNoZWNrJykpIHsKICAgIENVUkxfSVQyKGFycmF5KCksICdzZWxsYmlsbEFqYXhDb250cm9sbGVyLnBocD9kbz1jYXRjaCcpOwogICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dvdXQucGhwIik7Cn0="));
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

    $allCostcenter = $CostcenterEX->queryAllnotdel();
    $smarty->assign("allCostcenter", $allCostcenter);

    $sellers = $myUserEx->queryWithGroupId(2);
    $smarty->assign("sellers", $sellers);

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

    $loaddata = $supplierDeptChangeExt->getlastInGeneral();
    $todayx = (int) $load_last_row->supplierdebtchangemodelid;
    $todayx = $todayx + 1;

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



    $userData = $myUserRecord->load($_SESSION['userid']);
    $smarty->assign("userData", $userData);
    $allSave = $SaveExt->queryAllEX2();
    $smarty->assign("allSave", $allSave);

    $allCurrency = $currencyDAO->queryByConditions(0);
    $smarty->assign("allCurrency", $allCurrency);


    $bank = $bankExtDAO->queryAllExt();
    $smarty->assign("bank", $bank);

    $paySerialNo = (int) R::getCell('SELECT MAX(paySerialNo) FROM supplierdebtchange') + 1;
    $smarty->assign("paySerialNo", $paySerialNo);

    $smarty->assign("suplliernegative", $_SESSION['suplliernegative']);
    //here the smarty templates
    $smarty->assign("customdepositcheck", 1);
    $smarty->assign("customSupplierPayedDept", 1);
    $smarty->display("supplierPayedDeptview/add.html");
} elseif ($do == "show") {
    header("location:supplierReportsController.php");
} elseif ($do == "add") {
    // include_once("../public/authentication.php");
    //    add();
    try {
        $data_arr = add();
        if ($_POST['curlpost'] == 1) {
            echo (int) $data_arr[1];
        } else {
            if ($data_arr[0] == '0') {
                header("location:?do=sucess");
            } else {
                header("location:supplierReportsController.php?do=editprint&id=" . $data_arr[1] . "");
            }
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");

    $supplierdebtchangeId = $_GET['id'];

    $supplierdebtchangeData = edit($supplierdebtchangeId);
    $smarty->assign("supplierdebtchangeData", $supplierdebtchangeData);

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

    $smarty->display("supplierPayedDeptview/editprint.html");

    $smarty->assign("customPrint", 1);
} elseif ($do == "addexcel") {
    //here the permssion check
    include_once("../public/authentication.php");

    //get suppliers who have debt
    $suppliersData = $supplierExt->queryAllsupWithDebt();
    //empty excel file
    //start excel
    $inputFileName = 'preformatted_excel/suppliers_for_pay_debt.xlsx';
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);

    $objPHPExcel = $objReader->load($inputFileName);
    //  Get worksheet dimensions
    $sheet = $objPHPExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();

    $number_rows = $sheet->getHighestRow() - 4; // number of rows count
    if ($sheet != NULL) {
        if ($sheet->removeRow(4, $number_rows)) {

        }
    }
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $inputFileType);
    $objWriter->save($inputFileName);
    //end empty  excel file
    //start excel
    $inputFileName = 'preformatted_excel/suppliers_for_pay_debt.xlsx';
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);

    $objPHPExcel = $objReader->load($inputFileName);

    $RowStartTitles = 3;
    $col = 0;

    ## Auto size columns for active sheet
    $RowStartSupplier = 4;

    foreach ($suppliersData as $supData) {
        $col = 0;
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartSupplier, $supData->suppliername);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartSupplier, $supData->supplierphone);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartSupplier, $supData->suppliercode);
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($col++, $RowStartSupplier, $supData->suppliercurrentDebt);
        $col++;
        $RowStartSupplier++;
    }

    foreach (range('A', 'Z') as $columnID) {
        $objPHPExcel->getActiveSheet()
                ->getColumnDimension($columnID)->setWidth(17.1); //->setAutoSize(true);
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $inputFileType);
    $objWriter->save($inputFileName);
    //Clearing a Workbook from memory
    $objPHPExcel->disconnectWorksheets();
    unset($objPHPExcel);

    //here the smarty templates
    $smarty->display("supplierPayedDeptview/uploadexcel.html");
} elseif ($do == "addfromexcel") {
    include_once("../public/authentication.php");
    try {
        addFromExcel();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("customValidation", 1);
if ($_POST['curlpost'] != 1) {
    $smarty->display("footer.html");
}
/* ===============================
  function in this CONTROLLER
  ================================ */

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

// add in supplierdebtchange tbl
function add() {
    global $supplierExt;
    global $supplierDAO;
    global $supplier;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $currencyEX;
    global $today;

    global $mySave;
    global $mySaveRecord;


    //Dailyentry
    global $dailyEntry;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    global $accountsTreeDAO;
    global $accountsTree;


    //Transaction
    $mytransactions = new Transaction();

    try {
        $supplierid = $_POST["supplierid"];
        $costcenterid = $_POST["Costcenterid"];
        $payedDept = $_POST["payedDept"];
        $comment = $_POST["comment"];
        $currentDate = $_POST["currentDate"];
        $saveid = (int) $_POST['saveid'];
        $paySerialNo = (int) $_POST["paySerialNo"];
        $saveorbank = (int) $_POST['saveorbank'];
        if (empty($saveorbank)) {
            $saveorbank = 1;
        }
        $clientorsupplier = $_POST['clientorsupplier'];
        $currencyId = (isset($_POST['currencyId']) && !empty($_POST['currencyId'])) ? (int) $_POST['currencyId'] : 1;
        $cFactor = (isset($_POST['cFactor']) && !empty($_POST['cFactor'])) ? (float) $_POST['cFactor'] : 1;
        $payedDeptCurr = (isset($_POST['payedDeptCurr']) && !empty($_POST['payedDeptCurr'])) ? (float) $_POST['payedDeptCurr'] : $payedDept;
        if (isset($saveid) && !empty($saveid) && $saveorbank == 1) {
            //
            $dataSave = $mySaveRecord->load($saveid);


            $supplierdata = getSupplierDataFromSupplierInUseSP($supplierid);
            //$supplierdata = $supplierDAO->load($supplierid);
            $debtBefore = $supplierdata->suppliercurrentDebt;
            if ($clientorsupplier == 2) {
                $debtAfter = $debtBefore + $payedDept;
                $supplierdebtchangetype = 0;
                $processname = "ايصال تحصيل (( قبض من مورد ))";
                $texts = "ايصال تحصيل (( قبض من مورد ))";
            } else {
                $debtAfter = $debtBefore - $payedDept;
                $processname = "ايصال دفع لمورد";
                $texts = "ايصال دفع لمورد";
                $supplierdebtchangetype = 1;
            }


            $supplierdebtchangemodelid = $_POST['voucher'];

            //insert into supplierdeptchange tbl
            $supplierDeptChange->comment = $comment;
            $supplierDeptChange->processname = $processname;
            $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
            $supplierDeptChange->supplierdebtchangeamount = $payedDept;
            $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
            $supplierDeptChange->supplierdebtchangedate = $currentDate; //date("Y-m-d H:i:s");
            $supplierDeptChange->supplierdebtchangemodelid = $supplierdebtchangemodelid;
            $supplierDeptChange->supplierdebtchangetype = $supplierdebtchangetype;
            $supplierDeptChange->tablename = "supplierPayedDeptController.php";
            $supplierDeptChange->userid = $_SESSION['userid'];
            $supplierDeptChange->supplierid = $supplierid;
            $supplierDeptChange->dailyentryid = 0;
            $supplierDeptChange->saveid = $saveid;
            $supplierDeptChange->costcenterid = $costcenterid;
            $supplierDeptChange->currencyId = $currencyId;
            $supplierDeptChange->conversionFactor = $cFactor;
            $supplierDeptChange->payedInCurrency = $payedDeptCurr;
            $supplierDeptChange->paySerialNo = $paySerialNo;

            //Insert
            $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);
            $saveConversionFactor = 0;
            if (isset($supplierDeptChangeId)) {
                $suppData = $supplierDAO->load($supplierid);
                //update current dept in supplier tbl
                $supplier->suppliercurrentDebt = $debtAfter;
                $supplier->suppliercurrentDebtInCurrency = $debtAfter;


                $payedInSuppCurr = $debtAfter;
                if ($suppData->sullpierCurrencyid > 1) {
                    if ($currencyId == $suppData->sullpierCurrencyid) {
                        $payedInSuppCurr = $payedDeptCurr;
                    } else {
                        $conversionFactorSupp = R::getCell('select conversionFactor from currency where id=' . $suppData->sullpierCurrencyid);
                        $payedInSuppCurr = $debtAfter / $conversionFactorSupp;
                    }

                    if ($clientorsupplier == 2) {
                        $supplier->suppliercurrentDebtInCurrency = $suppData->suppliercurrentDebtInCurrency + $payedInSuppCurr;
                    } else {
                        $supplier->suppliercurrentDebtInCurrency = $suppData->suppliercurrentDebtInCurrency - $payedInSuppCurr;
                    }
                }
                $supplierDeptChange->debtchangbeforeInSupplierCurrency = $suppData->suppliercurrentDebtInCurrency;
                $supplierDeptChange->debtchangamountInSupplierCurrency = $payedInSuppCurr;
                $supplierDeptChange->debtchangafterInSupplierCurrency = $supplier->suppliercurrentDebtInCurrency;
                $supplierDeptChangeDAO->update($supplierDeptChange);


                $supplier->userid = $_SESSION['userid'];
                $supplier->supplierdate = $today;
                $supplier->supplierid = $supplierid;

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

                //update save's current value
                //get saveVsalue before and saveValue after mins payedDept
                $valueData = getSaveValueAndMins($payedDept, $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, 1, $saveId, $texts, $supplierDeptChangeId, $saveValueafter, "supplierPayedDeptController.php");
                }
            }

            //update currency conversionfactor
            if ($currencyId > 1 && $currencyId == $dataSave->currencyId) {
                $currencyEX->updateConversionFactor($cFactor, $currencyId);
            }

            $supName = $supplierdata->suppliername;
            $dailyEntry->entryComment = $texts . ' ( ' . $supName . ' ) ';
            $dailyEntry->fromFlag = 1;

            // start 7saaab L da2noon
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $payedDept;
            $oldSupplier = $supplierDAO->load($supplierid);

            if ($oldSupplier->treeId > 0) {
                $treeId = $oldSupplier->treeId;
            } else {
                $supplierTypeForTree = 0;
                if ($supplierTypeForTree == 0)
                    $parent = 81;
                elseif ($supplierTypeForTree == 1)
                    $parent = 87;

                $treeId = addTreeElement($oldSupplier->suppliername, $parent, 1, 0, 1, '', $oldSupplier->suppliercurrentDebt, 0);
            }
            $dailyEntryDebtor->accountstreeid = $treeId;


            /// end 7saaab L da2noon
            //start Save
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $payedDept;

            //$dataSave = $mySaveRecord->load($saveid);

            if ($dataSave->treeId > 0) {
                $idTreeSave = $dataSave->treeId;
            } else {
                $idTreeSave = addTreeElement($dataSave->savename, 40, 3, 0, 1, '', $dataSave->savecurrentvalue, 0);
            }
            $dailyEntryCreditor->accountstreeid = $idTreeSave;
            /// end Save

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $supplierDeptChangeId, "supplierReportsController.php?do=show&id=$supplierDeptChangeId");
            $did = $returnedData[1];
            $rowData = $supplierDeptChangeDAO->load($supplierDeptChangeId);

            $rowData->dailyentryid = $did;
            $rowData->saveConversionFactor = $saveConversionFactor;

            $supplierDeptChangeDAO->update($rowData);

            $add_print = $_POST['add_print'];
            $data_arr = array($add_print, $supplierDeptChangeId);
        }
        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        markSupplierAsNOTInUse($_POST["supplierid"]);
    }
    return $data_arr;
}

function edit($supplierDeptChangeId) {
    global $supplierDeptChangeDAO;

    $supplierdebtchangeData = $supplierDeptChangeDAO->load($supplierDeptChangeId);

    return $supplierdebtchangeData;
}

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

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

    if ($saveConversionFactor == 0) { // if not given conversion factor use conversion factor of save
        $saveConversionFactor = $saveData->conversionFactor;
    }

    $savevaluechanged = round(($savevaluechanged * $saveConversionFactor), 4); //convert from main curr
    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

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

function getClients() {
    global $clientDAO;
    $clientsData = $clientDAO->queryByCondition(0);
    return $clientsData;
}

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 CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

function addFromExcel() {
    global $supplierDAO;
    global $supplierDeptChangeExt;

    ## upload file temporarely
    $handle = new upload($_FILES['supplierssheet']);
    $excelfileName = uploadfile($handle, "../upload/supplierPayedDebt");
    $inputFileName = "../upload/supplierPayedDebt/" . $excelfileName;

    //Transaction
    $mytransactions = new Transaction();
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);

        $objPHPExcel = $objReader->load($inputFileName);



        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        for ($row = 4; $row <= $highestRow; $row++) {
            //  Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $rowData = $rowData[0];

            $col = 0;
            $suppliername = $rowData[$col]; //$_POST["txtName"];
            $col++;
            $supplierphone = $rowData[$col]; //$_POST["txtPhone"];
            $col++;
            $suppliercode = $rowData[$col]; //$_POST["textDetails"];
            $col++;
            $suppliercurrentDebt = $rowData[$col]; //$_POST["txtDebt"];
            $col++;
            $payedAmount = $rowData[$col]; //$_POST["textDetails"];
            $col++;

            if ($payedAmount > 0) {
                $supplierData = $supplierDAO->queryBySuppliername($suppliername);

                $_POST["supplierid"] = $supplierData[0]->supplierid;
                $_POST["payedDept"] = $payedAmount;
                $_POST["comment"] = '';
                $_POST["currentDate"] = date('Y-m-d H:i:s');
                $_POST['saveid'] = $_SESSION['saveid'];
                $_POST['clientorsupplier'] = 1;
                $_POST['debtBefore'] = $supplierData[0]->suppliercurrentDebt;
                $_POST['payedDeptCurr'] = $payedAmount;
                $_POST['debtAfter'] = ($supplierData[0]->suppliercurrentDebt - $payedAmount);

                $last_supplierdebtchangeid = (int) R::getCell('SELECT supplierdebtchangeid FROM supplierdebtchange order by supplierdebtchangeid desc limit 1');
                $_POST['voucher'] = $last_supplierdebtchangeid + 1;
                add();
            }
        }
        unlink($inputFileName);
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}