<?php

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

/////////////////////    سداد ديون عميل معين
//the global file operation
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');

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

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

//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');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.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');

//Premium
require_once('../models/dao/PremiumDAO.class.php');
require_once('../models/dto/Premium.class.php');
require_once('../models/mysql/PremiumMySqlDAO.class.php');
require_once('../models/mysql/ext/PremiumMySqlExtDAO.class.php');
//
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//Expensetype
require_once('../models/dao/ExpensestypeDAO.class.php');
require_once('../models/dto/Expensestype.class.php');
require_once('../models/mysql/ExpensestypeMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensestypeMySqlExtDAO.class.php');
//ExpensesDAO
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.php');
//
require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.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');
//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 = isset($_GET['do']) ? $_GET['do'] : '';
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';


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

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

  Controller Name :- clientPayedDeptController

  OPERTATION in Controller

  1- display add form
  2- add row in clientdebtchange tbl
  3- update client dept in client tbl
  ======================== */

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    if (!in_array($do, $ajaxDoArr)) {
        $smarty->display("header.html");
    }
}

//here goes the instances and general variables

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

//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();

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

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();
//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();
//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();
$SavedailyExt = new SavedailyMySqlExtDAO();

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

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

//Premium
$premium = new Premium();
$premiumDAO = new PremiumMySqlDAO();
$premiumExt = new PremiumMySqlExtDAO();
//
$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$userGroupEX = new UsergroupMySqlExtDAO();
//Expensetype
$expenseType = new Expensestype();
$expenseTypeDAO = new ExpensestypeMySqlDAO();
$expenseTypeEX = new ExpensestypeMySqlExtDAO();
//Expenses
$expense = new Expense();
$expenseDAO = new ExpensesMySqlDAO();
$expenseEX = new ExpensesMySqlExtDAO();
//creat object from employeePersonal
$EmployeepersonnelDAO = new EmployeepersonnelMySqlDAO();
$Employeepersonnel = new Employeepersonnel();
$EmployeepersonnelEX = new EmployeepersonnelMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//bank
$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExtDAO = new BankMySqlExtDAO;
//Currency
$currency = new Currency();
$currencyDAO = new CurrencyMySqlDAO();
$currencyEX = new CurrencyMySqlExtDAO();
eval(base64_decode("ZnVuY3Rpb24gZ2VuZXJhdGVVVUlEKCkgewogICAgJGhvc3RuYW1lID0gZXhwbG9kZSgnY29udHJvbGxlcnMnLCAkX1NFUlZFUlsnU0NSSVBUX1VSSSddKVswXTsgLy9nZXRob3N0bmFtZSgpOwogICAgJGhvc3RuYW1lID0gc3RyX3JlcGxhY2UoYXJyYXkoImh0dHA6Ly8iLCAiaHR0cHM6Ly8iKSwgIiIsICRob3N0bmFtZSk7CgogICAgLy8gR2VuZXJhdGUgYW4gTUQ1IGhhc2ggb2YgdGhlIGlucHV0CiAgICAkZGF0YSA9IG1kNSgkaG9zdG5hbWUpOwogICAgLy8gRm9ybWF0IHRoZSBoYXNoIGFzIGEgVVVJRAogICAgJHV1aWQgPSBzcHJpbnRmKAogICAgICAgICAgICAnJTA4cy0lMDRzLSUwNHgtJTA0eC0lMTJzJywKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCAwLCA4KSwKICAgICAgICAgICAgc3Vic3RyKCRkYXRhLCA4LCA0KSwKICAgICAgICAgICAgKGhleGRlYyhzdWJzdHIoJGRhdGEsIDEyLCA0KSkgJiAweDBmZmYpIHwgMHg0MDAwLAogICAgICAgICAgICAoaGV4ZGVjKHN1YnN0cigkZGF0YSwgMTYsIDQpKSAmIDB4M2ZmZikgfCAweDgwMDAsCiAgICAgICAgICAgIHN1YnN0cigkZGF0YSwgMjAsIDEyKQogICAgKTsKICAgICR1dWlkID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICR1dWlkKTsKICAgIHJldHVybiAkdXVpZDsKfQ=="));
eval(base64_decode("ZnVuY3Rpb24gc2VyaWFsY2hlY2soKSB7CiAgICBpZiAoc3RydG91cHBlcihzdWJzdHIoUEhQX09TLCAwLCAzKSkgPT09ICdXSU4nKSB7CiAgICAgICAgLy91dWlkIG9mIHdpbmRvd3MKICAgICAgICBleGVjKCdDOlxXaW5kb3dzXFN5c3RlbTMyXHdiZW1cd21pYyBjc3Byb2R1Y3QgZ2V0ICJVVUlEIicsICRtYWNhZGRyZXNzLCAkaXNFeGVjdXRlZCk7CiAgICAgICAgJG1hY2FkZHJlc3MgPSAkbWFjYWRkcmVzc1sxXTsKICAgICAgICAkbWFjID0gc3RyX3JlcGxhY2UoYXJyYXkoJy0nKSwgJycsICRtYWNhZGRyZXNzKTsKICAgIH0gZWxzZSB7Ly9ub3Qgd2luZG93cyB1c2UgbGludXggbWFjCiAgICAgICAgJG1hYyA9IGdlbmVyYXRlVVVJRCgpOwogICAgfQoKICAgICRyYW5kb21fc2FsdCA9IGhhc2goJ3NoYTUxMicsICcxMzA1Jyk7CiAgICAvLyBDcmVhdGUgc2FsdGVkIHBhc3N3b3JkCiAgICAkaGFzaGVkTWFjID0gaGFzaCgnc2hhNTEyJywgJG1hYyAuICRyYW5kb21fc2FsdCk7CiAgICByZXR1cm4gJGhhc2hlZE1hYzsKfQ=="));

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

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

    // $todayx = date("Ymd");
    //    $loaddata = $clientDeptChangeExt->loadvouchernumber($todayx);
    //    $vouchernumber = $loaddata->clientdebtchangemodelid;
    //    if ($vouchernumber != "") {
    //
    //        $year = substr($vouchernumber, 8, 2);
    //        $year++;
    //        $todayx = $todayx . $year;
    //    } else {
    //
    //        $todayx = $todayx . '1';
    //    }

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

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

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

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

    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $SaveExt->queryAllEX2();
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $SaveExt->queryAllEX2($queryString);
        }
        $smarty->assign("allSave", $saves);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $smarty->assign('allSave', $_SESSION['saveid']);
    }


    if ($_SESSION['bankids'] == 0) {
        $bank = $bankExtDAO->queryAllExt();
    } else {
        $queryString = ' and bankid in (' . $_SESSION['bankids'] . ')';
        $bank = $bankExtDAO->queryAllExt($queryString);
    }
    $smarty->assign("bank", $bank);

    // $allSave = $SaveExt->queryAllEX2();
    // $smarty->assign("allSave", $allSave);

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

    $load_last_row = $clientDeptChangeExt->getlastInGeneral();
    $todayx = (int) $load_last_row->clientdebtchangeid;
    $todayx = $todayx + 1;

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

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

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

    $clientidFromGET = (int) $_GET['clientid'];
    $smarty->assign("clientidFromGET", $clientidFromGET);


    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);
    $smarty->assign("today", $today);
    $smarty->assign("todayx", $todayx);
    $smarty->assign("clientnegative", $_SESSION['clientnegative']);
    //here the smarty templates
    if ($lang == "en")
        $smarty->display("clientPayedDeptview/add_ltr.html");
    else
        $smarty->display("clientPayedDeptview/add.html");

    $smarty->assign("customClientPayedDept", 1);
    $smarty->assign("clientPremium", 1);

    $smarty->assign('customdepositchec', 1);
    $smarty->assign('customdepositcheck', 1);
} elseif ($do == "add") {
    // include_once("../public/authentication.php");
    //    add();
    try {

        $add_data = add();
        if ($_POST['curlpost'] == 1) {
            echo $add_data[1];
        } else {
            if ($add_data[0] == '0') {
                $addAndNew = (int) $_POST['add_And_New'];
                if ($addAndNew == 1) {
                    header("location: clientPayedDeptController.php");
                } else {
                    header("location:?do=sucess");
                }
            } else {
                if ($Programsettingdata->printSand == 0) {
                    header("location: clientPayedDeptController.php?do=editprint2&id= " . $add_data[1] . " ");
                } else if ($Programsettingdata->printSand == 1) {
                    header("location: clientPayedDeptController.php?do=editprint2&id= " . $add_data[1] . " ");
                } else if ($Programsettingdata->printSand == 2) {
                    header("location: clientPayedDeptController.php?do=editprint2&id= " . $add_data[1] . " ");
                }
            }
        }
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "remove") {
    // include_once("../public/authentication.php");

    try {
        $flag = delete();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            echo $flag;
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        //        var_dump($e);
        //   print_r($e);
        header("location:?do=error");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");
    $projectid = filter_input(INPUT_GET, "proid");

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //    $allmydata = $clientDeptChangeExt->queryreceipt();
    //    $smarty->assign("allmydata", $allmydata);
    //    $clientsData = getClients(); //undeleted clients
    //    $smarty->assign("clientsData", $clientsData);

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

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $clientid = $_POST["clientid"];
    if (empty($clientid))
        $clientid = $_GET["clientid"];
    $clientdebtchangemodelid = $_POST["clientdebtchangemodelid"];
    $bure = (int) $_POST["bure"];
    $onlyReceipt = (int) $_POST["onlyReceipt"];
    $Costcenterid = $_REQUEST['Costcenterid'];
    if ($projectid > 0) {
        $clientid = $projectid;
        $client = $clientDAO->load($projectid);
    }
    $smarty->assign("client", $client);

    /* if ((isset($clientid) && $clientid != '-1') || (isset($clientdebtchangemodelid) && $clientdebtchangemodelid != '-1') || (!empty($startDate) && !empty($endDate))) {
      $clientnamedata = $clientDAO->load($clientname);
      $ccid = $clientname;
      $message = " اسم العميل " . $clientnamedata->clientname . " لعمليه " . $processid . "التاريخ: من: " . $startDate . " إلى: " . $endDate;

      showx($clientid, $clientdebtchangemodelid, $startDate, $endDate, $bure);
      } else {
      $today = date("Y-m-d");
      showx($clientid, $clientdebtchangemodelid, $today, $today, $bure);
      } */

    /* if(isset($startDate) && isset($endDate) && $startDate !="" && $endDate !="")
      {

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

      show($startDate, $endDate);
      }

      elseif( isset($clientdebtchangemodelid) && $clientdebtchangemodelid !="-1")
      {

      $message = "رقم الوصل : ".$clientdebtchangemodelid;
      $smarty->assign("message",$message);

      showbymodelid($clientdebtchangemodelid);
      }


      else
      {
      $today=date("Y-m-d");
      show($today, $today);

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

    $id = (int) $_GET["id"];
    $smarty->assign("idsearch", $id);
    $smarty->display("clientPayedDeptview/show.html");
} elseif ($do == "showallajax") {
    showallajax();
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $clientdebtchangeId = $_GET['id'];
    $clientdebtchangeData = edit($clientdebtchangeId);
    $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);
    $smarty->display("clientPayedDeptview/edit.html");
    $smarty->assign("customPrint", 1);
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    $clientdebtchangeId = $_POST['id'];
    $comment = $_POST['comment'];
    try {
        $clientDeptChangeExt->updateComment($comment, $clientdebtchangeId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");
    $clientdebtchangeId = $_GET['id'];

    $clientdebtchangeData = edit($clientdebtchangeId);


    $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
    //print_r($clientdebtchangeData);

    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

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

    $smarty->assign("customPrint", 1);
} elseif ($do == "editprint2") {
    include_once("../public/authentication.php");
    if ($Programsettingdata->printSand == 0) {
        $clientdebtchangeId = $_GET['id'];

        $clientdebtchangeData = edit($clientdebtchangeId);


        $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
        //print_r($clientdebtchangeData);

        $clientsData = getClients(); //undeleted clients
        $smarty->assign("clientsData", $clientsData);

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

        $smarty->assign("customPrint", 1);
    } else if ($Programsettingdata->printSand == 1) {
        $clientdebtchangeId = $_GET['id'];

        $clientdebtchangeData = edit($clientdebtchangeId);


        $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
        //print_r($clientdebtchangeData);

        $clientsData = getClients(); //undeleted clients
        $smarty->assign("clientsData", $clientsData);

        //
        $ar_number = new convert_ar($clientdebtchangeData->clientdebtchangeamount, "male");
        $ar_number = $ar_number->convert_number();


        $smarty->assign("ar_number", $ar_number);
        $smarty->display("clientPayedDeptview/editprint2.html");
    } else if ($Programsettingdata->printSand == 2) {
        $clientdebtchangeId = $_GET['id'];
        //        var_dump($clientdebtchangeId);

        $clientdebtchangeData = edit($clientdebtchangeId);
        $clientData = $clientDAO->load($clientdebtchangeData->clientid);
        $clientdebtchangeData->clientname = $clientData->clientname;
        $smarty->assign("clientdebtchangeData", $clientdebtchangeData);

        $ar_number = new convert_ar($clientdebtchangeData->clientdebtchangeamount, "male");
        $ar_number = $ar_number->convert_number();

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

        $smarty->display("clientPayedDeptview/editprint3.html");
    }
} elseif ($do == "addexcel") {
    //here the permssion check
    include_once("../public/authentication.php");

    //get suppliers who have debt
    $clientsData = getClients();

    //empty excel file
    //start excel
    $inputFileName = 'preformatted_excel/clients_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/clients_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();

    $RowStartTitles = 3;
    $col = 0;

    ## Auto size columns for active sheet
    $RowStartClient = 4;
    foreach ($clientsData as $clientData) {
        if ($clientData->clientdebt != 0) {
            $col = 0;
            $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($col++, $RowStartClient, $clientData->clientname);
            $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($col++, $RowStartClient, $clientData->clientphone);
            $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($col++, $RowStartClient, $clientData->clientcode);
            $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($col++, $RowStartClient, $clientData->clientdebt);
            $col++;
            $RowStartClient++;
        }
    }

    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("clientPayedDeptview/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");
} ##
elseif ($do == "mandobreport") {
    //needed data
    $sellers = $myUserEx->queryWithGroupId(2);
    $smarty->assign("sellers", $sellers);


    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    //recieve search data
    $mandob = (int) filter_input(INPUT_POST, 'mandob');
    $from = filter_input(INPUT_POST, 'from');
    $to = filter_input(INPUT_POST, 'to');
    if (isset($mandob) && $mandob > 0) {
        $smarty->assign("choosenMandob", $mandob);
        $user = $myUserRecord->load($mandob);
        $userGroupData = $userGroupDAO->load($user->usergroupid);
        $smarty->assign("userGroupData", $userGroupData);
        //
        $typeId = addExpenseType();
        $queryString = " and clientdebtchange.seller=$mandob ";
        $queryStringExpense = " and expensesname= '" . $user->employeename . "' and expensestypeid=$typeId ";
        if (!empty($from)) {
            $queryString .= " and date(clientdebtchange.clientdebtchangedate) >= '" . $from . "' ";
            $queryStringExpense .= " and expensesdate >= '" . $from . "' ";
        }
        if (!empty($to)) {
            $queryString .= " and date(clientdebtchange.clientdebtchangedate) <= '" . $to . "' ";
            $queryStringExpense .= " and expensesdate <= '" . $to . "' ";
        }
        $mandobCollectData = $clientDeptChangeExt->getMandobCollectData($queryString);
        $smarty->assign("mandobCollectData", $mandobCollectData);
        //
        $mandobTakenMoneyArr = array();
        $expenses = $expenseEX->queryByQueryString($queryStringExpense);
        $rewards = $EmployeepersonnelEX->getMandobRewards($user->empid, $from, $to);
        foreach ($expenses as $value) {
            $temp = new stdClass();
            $temp->value = $value->expensesValue;
            $temp->date = $value->expensesdate;
            $temp->type = 1;
            array_push($mandobTakenMoneyArr, $temp);
        }
        foreach ($rewards as $value) {
            $temp = new stdClass();
            $temp->value = $value->employeepersonnelvalue;
            $temp->date = $value->employeepersonneldate;
            $temp->type = 2;
            array_push($mandobTakenMoneyArr, $temp);
        }
        $smarty->assign("mandobTakenMoneyArr", $mandobTakenMoneyArr);
    }

    $smarty->display("clientPayedDeptview/mandobreport.html");
} elseif ($do == "paymandob") {
    $choosenMandob = (int) filter_input(INPUT_POST, "choosenMandob");
    $mandobMethod = (int) filter_input(INPUT_POST, "mandobMethod");
    $amount = (float) filter_input(INPUT_POST, "amount");
    if ($choosenMandob > 0 && $amount > 0) {
        $user = $myUserRecord->load($choosenMandob);
        if ($mandobMethod == 0) { //as expense
            $typeId = addExpenseType();
            addExpense($user->employeename, $amount, $typeId, $_SESSION['saveid']);
        } elseif ($mandobMethod == 1 && $user->empid > 0) { //as reward
            addEmployeePersonal($user->empid, date('Y-m-d H:i:s'), $amount, 1, $_SESSION['saveid']);
        }
    }


    $url = "clientPayedDeptController.php?do=mandobreport";
    $smarty->assign('urldirect', $url);
    $note = "تمت العملية بنجاح";
    $smarty->assign('msgnote', $note);
    $smarty->display("notes2.html");
}
$smarty->assign("customClientPayedDept", 1);

$smarty->assign("customValidation", 1);

//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    if (!in_array($do, $ajaxDoArr)) {
        $smarty->display("footer.html");
    }
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function getClients() {
    global $clientDAO;
    global $clientExt;
    global $myUserRecord;
    $userData = $myUserRecord->load($_SESSION['userid']);
    $queryString = '';
    if ($userData->viewclients == 0) {
        $queryString .= ' AND client.userid =' . $_SESSION['userid'];
    }
    $clientsData = $clientExt->queryByCondition($queryString);
    return $clientsData;
}

function add() {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $currencyEX;
    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    global $accountsTreeDAO;
    global $accountsTree;

    //save
    global $mySave;
    global $SaveDAO;

    global $premium;
    global $premiumDAO;
    global $premiumExt;

    liveBackupComment("-- clientPayedDeptController add - with modelid =" . $_POST['voucher']);
    //Transaction
    $mytransactions = new Transaction();
    try {

        $clientid = $_POST["clientid"];
        $costcenterid = $_POST["Costcenterid"];
        //$lastDate = $_POST["lastDate"];
        $currentDate = $_POST["currentDate"];
        $debtBefore = $_POST["debtBefore"];
        $payedDept = $_POST["payedDept"];
        //        $debtAfter = $_POST["debtAfter"];
        $earlyRepayment = $_POST["earlyRepayment"];
        $voucher = (int) $_POST["voucher"];
        $paySerialNo = (int) $_POST["paySerialNo"];
        $voucherpremium = $_POST["voucherpremium"];
        $comment = $_POST["comment"];
        $premiumid = filter_input(INPUT_POST, 'premiumid');
        $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;
        //
        $saveid = (int) $_POST["saveid"];
        $seller = (int) $_POST["seller"];
        $clientorsupplier = $_POST['clientorsupplier'];
        $saveorbank = (int) $_POST['saveorbank'];
        if (empty($saveorbank)) {
            $saveorbank = 1;
        }
        $saveorbankPremium = $_POST['saveorbankPremium'];
        $bankid = (int) $_POST["ddlBank"];
        $bankaccountid = (int) $_POST["accountid"];
        $payedDeptBank = (float) $_POST["txtAmount"];
        $checkNo = $_POST["txtcheckNum"];
        $checkUser = $_POST["txtUser"];
        $totalpayments = $_POST["totalpayments"];

        $clientpremium = (int) filter_input(INPUT_POST, 'clientpremium');
        $premiumDetailId = (int) filter_input(INPUT_POST, 'premiumDetailId');
        $notPremium = $_POST['notPremium']; //filter_input(INPUT_POST, 'notPremium');
        $Premium = filter_input(INPUT_POST, 'Premium');
        if (isset($saveid) && !empty($saveid) && ($saveorbank == 1 || $saveorbankPremium == 1)) {
            $dataSave = $SaveDAO->load($saveid);
            //
            $saveConversionFactor = 0;

            if (isset($clientid) && $clientid != '-1' && $notPremium == 'notPremium') {
                $clientdataSP = getClientDataFromClientInUseSP($clientid);
                $client = $clientDAO->load($clientid);
                //update current dept in client tbl
                if ($earlyRepayment) {
                    if ($clientorsupplier == 2) {
                        $payedDeptall = $clientdataSP->clientdebt + $payedDept;
                        $debtAfter = $payedDeptall + $earlyRepayment;
                        $processname = "ايصال دفع لعميل";
                        $texts = "ايصال دفع لعميل";
                        $clientdebtchangetype = 0;
                    } else {
                        $payedDeptall = $clientdataSP->clientdebt - $payedDept;
                        $debtAfter = $payedDeptall - $earlyRepayment;
                        $processname = "ايصال تحصيل (( قبض من عميل ))";
                        $texts = "ايصال تحصيل (( قبض من عميل ))";
                        $clientdebtchangetype = 1;
                    }
                } else {
                    if ($clientorsupplier == 2) {
                        $debtAfter = $clientdataSP->clientdebt + $payedDept;
                        $processname = "ايصال دفع لعميل";
                        $texts = "ايصال دفع لعميل";
                        $clientdebtchangetype = 0;
                    } else {
                        $debtAfter = $clientdataSP->clientdebt - $payedDept;
                        $processname = "ايصال تحصيل (( قبض من عميل ))";
                        $texts = "ايصال تحصيل (( قبض من عميل ))";
                        $clientdebtchangetype = 1;
                    }
                }
                $client->clientdebt = $debtAfter;
                $client->userid = $_SESSION['userid'];
                $client->clientdate = $today;
                $client->clientid = $clientid;

                $clientExt->updatedept($client);
                markClientAsNOTInUse($clientid);

                //insert into supplierdeptchange tbl
                $clientDeptChange->comment = $comment;
                $clientDeptChange->processname = $processname;
                $clientDeptChange->clientdebtchangeafter = $debtAfter;
                $clientDeptChange->clientdebtchangeamount = $payedDept;
                $clientDeptChange->totalOperationCost = $payedDept;
                $clientDeptChange->clientdebtchangebefore = $debtBefore;
                $clientDeptChange->clientdebtchangedate = $currentDate; //$today;
                $clientDeptChange->clientdebtchangemodelid = $voucher;
                $clientDeptChange->paySerialNo = $paySerialNo;
                $clientDeptChange->clientdebtchangetype = $clientdebtchangetype;
                $clientDeptChange->tablename = "clientPayedDeptController.php";
                $clientDeptChange->userid = $_SESSION['userid'];
                $clientDeptChange->clientid = $clientid;
                $clientDeptChange->seller = $seller;
                $clientDeptChange->dailyentryid = 0;
                $clientDeptChange->discountearlyRepayment = $earlyRepayment;
                $clientDeptChange->costcenterid = $costcenterid;
                $clientDeptChange->currencyId = $currencyId;
                $clientDeptChange->conversionFactor = $cFactor;
                $clientDeptChange->payedInCurrency = $payedDeptCurr;
                $clientDeptChange->totalpayments = $totalpayments;
                //Insert
                $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);

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

                //update save's current value
                //get saveVsalue before and saveValue after plus payedDept
                $valueData = getSaveValueAndPlus($payedDept, $saveid, $saveConversionFactor);

                //  print_r($valueData);
                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, $texts, $clientdebtchangeId, $saveValueafter, "clientPayedDeptController.php");
                }
            } else {
                //                var_dump($_POST);
                //                die();
                //                $clientdataSP = getClientDataFromClientInUseSP($clientid);
                $client = $clientDAO->load($clientid);
                if ($clientorsupplier == 2) {
                    $payedDeptall = $clientdataSP->clientdebt + $payedDept;
                    $processname = "ايصال دفع لعميل";
                    $texts = "ايصال دفع لعميل";
                    $clientdebtchangetype = 0;
                } else {
                    $debtAfter = $client->clientdebt - $payedDept;
                    $processname = "ايصال تحصيل (( قبض من عميل ))";
                    $texts = "ايصال تحصيل (( قبض من عميل ))";
                    $clientdebtchangetype = 1;
                }



                $client->clientdebt = $debtAfter;
                $client->userid = $_SESSION['userid'];
                $client->clientdate = $today;
                $client->clientid = $clientid;

                $clientExt->updatedept($client);

                //insert            into supplierdeptchange tbl
                $clientDeptChange->clientdebtchangebefore = $debtBefore ? $debtBefore : $clientdataSP->clientdebt;
                $clientDeptChange->comment = $comment;
                $clientDeptChange->processname = $processname;
                $clientDeptChange->clientdebtchangeafter = $debtAfter;
                $clientDeptChange->clientdebtchangeamount = $payedDept;
                $clientDeptChange->totalOperationCost = $payedDept;
                $clientDeptChange->clientdebtchangedate = $currentDate ? $currentDate : $today; //$today;
                $clientDeptChange->clientdebtchangemodelid = $premiumid;
                $clientDeptChange->clientdebtchangetype = $clientdebtchangetype;
                $clientDeptChange->tablename = "premiumController.php";
                $clientDeptChange->userid = $_SESSION['userid'];
                $clientDeptChange->clientid = $clientid;
                $clientDeptChange->seller = $seller;
                $clientDeptChange->dailyentryid = 0;
                $clientDeptChange->discountearlyRepayment = $earlyRepayment;
                $clientDeptChange->costcenterid = $costcenterid;
                $clientDeptChange->currencyId = $currencyId;
                $clientDeptChange->conversionFactor = $cFactor;
                $clientDeptChange->payedInCurrency = $payedDeptCurr;
                $clientDeptChange->totalpayments = $totalpayments;

                //Insert
                $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);

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

                //update save's current value
                //get saveVsalue before and saveValue after plus payedDept

                $valueData = getSaveValueAndPlus($payedDept, $saveid, $saveConversionFactor);

                //  print_r($valueData);
                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, $texts, $clientdebtchangeId, $saveValueafter, "premiumController.php");
                }

                $premiumData = $premiumDAO->load($premiumid);
                $dept_rest = $premiumData->value - $premiumData->rest;

                if ($dept_rest < $payedDept) {
                    ## close chosed  $dept_details
                    $rest = $payedDept - $dept_rest;

                    $premiumData->payed = 1;
                    $premiumData->rest = $premiumData->rest + $rest;
                    $premiumData->value = $premiumData->value;
                    $premiumDAO->update($premiumData);

                    ## calculate the rest paid money
                    ## get all uncompleted installment
                    $premiumDetailId = filter_input(INPUT_POST, 'premiumDetailId');
                    $ClientPremiumData = $premiumExt->queryByPremiumclientConditionPayed($premiumDetailId);

                    foreach ($ClientPremiumData as $data) {
                        if ($rest <= 0) {
                            break;
                        }
                        ##
                        elseif ($rest >= ($data->value - $data->rest)) {
                            $data->payed = 1;
                            $data->rest = $data->value;
                            $premiumDAO->update($data);
                            $rest = $rest - $data->value;
                        }
                        ##
                        elseif ($rest < ($data->value - $data->rest)) {
                            $data->rest = $data->rest + $rest;
                            $premiumDAO->update($data);
                            $rest = 0;
                        }
                    }
                }
                ##
                elseif ($dept_rest == $payedDept) {
                    $premiumData->payed = 1;
                    $premiumData->rest = $premiumData->rest + $dept_rest;
                    $premiumDAO->update($premiumData);
                }
                ##
                else {
                    $premiumData->rest = $premiumData->rest + $payedDept;
                    $premiumDAO->update($premiumData);
                }

                $premiumData->payment_date = date('Y-m-d H:i:s');
                $premiumDAO->update($premiumData);
            }

            $clientData = $clientDAO->load($clientid);

            $dailyEntry->entryComment = 'اضافة ايصال سداد للعميل ' . $clientData->clientname;

            // start save
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $payedDept;

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

            $idTreeSave = $dataSave->treeId;

            if ($idTreeSave < 1) {
                $idTreeSave = addTreeElement($dataSave->savename, 40, 3, 0, 1, '', '', $dataSave->savecurrentvalue, 0);
            }
            $dailyEntryDebtor->accountstreeid = $idTreeSave;
            /// end save
            //
            /// start L 7sab L da2non
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $payedDept;
            $oldClient = $clientDAO->load($clientid);
            $treeId = $oldClient->treeId;
            if ($treeId < 1) {
                $clientTypeForTree = 0;
                if ($clientTypeForTree == 0)
                    $parent = 58;
                elseif ($clientTypeForTree == 1)
                    $parent = 60;
                $treeId = addTreeElement($oldClient->clientname, $parent, 3, 0, 1, '', 0, $oldClient->clientdebt);
            }
            // print_r($treeId . 'aaaaaaaaaaaaa');
            $dailyEntryCreditor->accountstreeid = $treeId;
            /// end L 7sab L da2non

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

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1, $clientdebtchangeId, "clientPayedDeptController.php?do=show&id=$clientdebtchangeId");
            $did = $returnedData[1];
            //
            $rowData = $clientDeptChangeDAO->load($clientdebtchangeId);

            $clientDeptChange->comment = $rowData->comment;
            $clientDeptChange->processname = $rowData->processname;
            $clientDeptChange->clientdebtchangeafter = $rowData->clientdebtchangeafter;
            $clientDeptChange->clientdebtchangeamount = $rowData->clientdebtchangeamount;
            $clientDeptChange->totalOperationCost = $rowData->totalOperationCost;
            $clientDeptChange->clientdebtchangebefore = $rowData->clientdebtchangebefore;
            $clientDeptChange->clientdebtchangedate = $rowData->clientdebtchangedate;
            if ($_POST['idIsModelId'] == 1) {
                $clientDeptChange->clientdebtchangemodelid = $rowData->clientdebtchangeid;
            } else {
                $clientDeptChange->clientdebtchangemodelid = $rowData->clientdebtchangemodelid;
            }
            $clientDeptChange->clientdebtchangetype = $rowData->clientdebtchangetype;
            $clientDeptChange->tablename = $rowData->tablename;
            $clientDeptChange->userid = $rowData->userid;
            $clientDeptChange->clientid = $rowData->clientid;
            $clientDeptChange->seller = $seller;
            $clientDeptChange->dailyentryid = $did;
            $clientDeptChange->saveConversionFactor = $saveConversionFactor;
            //            var_dump($clientDeptChange);
            //            die();
            $clientDeptChangeDAO->update($clientDeptChange);

            $add_print = filter_input(INPUT_POST, 'add_print');

            $data_arr = array($add_print, $clientdebtchangeId);
            //
        }
        ##
        //        elseif (isset($bankid) && !empty($bankid) && isset($bankaccountid) && !empty($bankaccountid) && $saveorbank == 2) {
        //            $dataArr = array(
        //                'clientid' => $clientid,
        //                'accountid' => $bankaccountid,
        //                'txtAmount' => $payedDeptBank,
        //                'textNote' => $comment,
        //                'txtcheckNum' => $checkNo,
        //                'txtUser' => $checkUser,
        //                'checkdate' => $currentDate,
        //                'ddlBank' => $bankid,
        //                    //'premiumid' => '',
        //                    //'premiumDetailId' => '',
        //            );
        //            CURL_IT2($dataArr, 'expensesController.php?do=add');
        //        }


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $clientid = $_POST["clientid"];
        markClientAsNOTInUse($clientid);
    }
    liveBackupComment("-- clientPayedDeptController add end - with modelid =" . $_POST['voucher'] . " -clientdebtchangeId = $clientdebtchangeId");
    return $data_arr;
}

function delete() {
    global $client;
    global $clientDAO;
    global $clientExt;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $clientDeptChangeExt;
    global $SavedailyExt;
    global $today;
    global $premiumDAO;

    liveBackupComment("-- clientPayedDeptController delete - with clientdebtchangeId =" . $_GET['id']);
    //Transaction
    $mytransactions = new Transaction();

    try {
        $voucher = $_GET['id'];
        $action = $_GET['action'];
        $premiumid = $_GET['premium'];


        ########################################################################
        //choose erpDB user has choosen in obygy_app
        //it is reuired by eng.sherif to keep edit info to person who add, not the one who is updating as long as it is not الاستقبال group
        if (isset($_POST["erpDB"]) && !empty($_POST["erpDB"])) {
            if (isset($_POST['obgyGroupId']) && $_POST['obgyGroupId'] == 3) {
                //it is reception الاستقبال// and its id @royal=3
                //use data coming for user who make update
            } else {
                //keep using the same data of user who made bill
                //get save id
                $queryString = ' tablename = "clientPayedDeptController.php" and savedailymodelid = ' . $voucher . ' ';
                $saveDaily = $SavedailyExt->querybyqueryString($queryString);

                $_POST['userid'] = $saveDaily[0]->userid;
                $_POST['saveid'] = $saveDaily[0]->saveid;
                print_r($saveDaily);
                $_SESSION['userid'] = (isset($_POST['userid']) && $_POST['userid'] > 0) ? (int) $_POST['userid'] : 1;
                $_SESSION['saveid'] = (isset($_POST['saveid']) && $_POST['saveid'] > 0) ? (int) $_POST['saveid'] : 1;
            }
        }
        ########################################################################
        $clientdata = $clientDeptChangeDAO->load($voucher);
        if (empty($action)) {
            $action = $clientdata->dailyentryid;
        }
        if ($clientdata->tablename == 'clientPayedDeptController.php') {
            $clientId = $clientdata->clientid;
            //
            $currencyId = $clientdata->currencyId;
            $cFactor = $clientdata->conversionFactor;
            $payedDeptCurr = $clientdata->payedInCurrency;
            $saveConversionFactor = $clientdata->saveConversionFactor;

            $clientdataSP = getClientDataFromClientInUseSP($clientId);
            $clientTabData = $clientDAO->load($clientId);
            //# load client dept change from client table.
            //$clientDebtBefore = $clientdata->clientdebtchangebefore;
            //$clientDebtAfter = $clientdata->clientdebtchangeafter;

            $clientDebtBefore = $clientdataSP->clientdebt;

            $payedDebt = $clientdata->clientdebtchangeamount;

            if ($clientdata->discountearlyRepayment) {
                $clientDebtAfterTotal = $clientDebtBefore + $payedDebt + $clientdata->discountearlyRepayment;
            } else {
                $clientDebtAfterTotal = $clientDebtBefore + $payedDebt;
            }

            $client->clientdebt = $clientDebtAfterTotal;
            $client->userid = $_SESSION['userid'];
            $client->clientid = $clientId;

            $clientExt->updateClientdebt($client);
            markClientAsNOTInUse($clientId);

            $clientDeptChange->del = 1;
            $clientDeptChange->comment = "";
            $clientDeptChange->processname = "الغاء سداد ديون عميل";
            $clientDeptChange->clientdebtchangeafter = $clientDebtAfterTotal;
            $clientDeptChange->clientdebtchangeamount = $payedDebt;
            $clientDeptChange->totalOperationCost = $payedDebt;
            $clientDeptChange->clientdebtchangebefore = $clientDebtBefore;
            $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
            $clientDeptChange->clientdebtchangemodelid = $voucher;
            $clientDeptChange->clientdebtchangetype = 0;
            $clientDeptChange->tablename = "clientPayedDeptController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $clientId;
            $clientDeptChange->dailyentryid = $action;
            $clientDeptChange->discountearlyRepayment = $clientdata->discountearlyRepayment;
            $clientDeptChange->currencyId = $currencyId;
            $clientDeptChange->conversionFactor = $cFactor;
            $clientDeptChange->payedInCurrency = $payedDeptCurr;
            $clientDeptChange->saveConversionFactor = $saveConversionFactor;


            $clientDeptChangeExt->updateDebt($clientDeptChange);

            $clientdebtchangeId = $clientDeptChangeDAO->insert1($clientDeptChange);
            //get save id
            $queryString = ' tablename = "clientPayedDeptController.php" and savedailymodelid = ' . $voucher . ' ';
            $saveDaily = $SavedailyExt->querybyqueryString($queryString);
            $saveid = $saveDaily[0]->saveid;
            //update save's current value
            //get saveVsalue before and saveValue after plus payedDept
            $valueData = getSaveValueAndSubtract($payedDebt, $saveid, $saveConversionFactor);

            //print_r($valueData);
            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, "الغاء سداد ديون عميل", $clientdebtchangeId, $saveValueafter, "clientPayedDeptController.php");
            }
        } else {
            $clientId = $clientdata->clientid;
            //
            $currencyId = $clientdata->currencyId;
            $cFactor = $clientdata->conversionFactor;
            $payedDeptCurr = $clientdata->payedInCurrency;
            $saveConversionFactor = $clientdata->saveConversionFactor;

            $clientdataSP = getClientDataFromClientInUseSP($clientId);
            $clientTabData = $clientDAO->load($clientId);
            //# load client dept change from client table.
            //$clientDebtBefore = $clientdata->clientdebtchangebefore;
            //$clientDebtAfter = $clientdata->clientdebtchangeafter;

            $clientDebtBefore = $clientdataSP->clientdebt;

            $payedDebt = $clientdata->clientdebtchangeamount;

            if ($clientdata->discountearlyRepayment) {
                $clientDebtAfterTotal = $clientDebtBefore + $payedDebt + $clientdata->discountearlyRepayment;
            } else {
                $clientDebtAfterTotal = $clientDebtBefore + $payedDebt;
            }

            $client->clientdebt = $clientDebtAfterTotal;
            $client->userid = $_SESSION['userid'];
            $client->clientid = $clientId;

            $clientExt->updateClientdebt($client);
            markClientAsNOTInUse($clientId);

            $clientDeptChange->del = 1;
            $clientDeptChange->comment = "";
            $clientDeptChange->processname = "الغاء قسط عميل";
            $clientDeptChange->clientdebtchangeafter = $clientDebtAfterTotal;
            $clientDeptChange->clientdebtchangeamount = $payedDebt;
            $clientDeptChange->totalOperationCost = $payedDebt;
            $clientDeptChange->clientdebtchangebefore = $clientDebtBefore;
            $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
            $clientDeptChange->clientdebtchangemodelid = $voucher;
            $clientDeptChange->clientdebtchangetype = 0;
            $clientDeptChange->tablename = "premiumController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $clientId;
            $clientDeptChange->dailyentryid = $action;
            $clientDeptChange->discountearlyRepayment = $clientdata->discountearlyRepayment;
            $clientDeptChange->currencyId = $currencyId;
            $clientDeptChange->conversionFactor = $cFactor;
            $clientDeptChange->payedInCurrency = $payedDeptCurr;
            $clientDeptChange->saveConversionFactor = $saveConversionFactor;


            $clientDeptChangeExt->updateDebt($clientDeptChange);

            $clientdebtchangeId = $clientDeptChangeDAO->insert1($clientDeptChange);
            //get save id
            $queryString = ' tablename = "premiumController.php" and savedailymodelid = ' . $voucher . ' ';
            $saveDaily = $SavedailyExt->querybyqueryString($queryString);
            $saveid = $saveDaily[0]->saveid;
            //update save's current value
            //get saveVsalue before and saveValue after plus payedDept
            $valueData = getSaveValueAndSubtract($payedDebt, $saveid, $saveConversionFactor);

            //print_r($valueData);
            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, "الغاء قسط عميل", $clientdebtchangeId, $saveValueafter, "premiumController.php");
            }

            $premiumData = $premiumDAO->load($premiumid);
            if ($premiumData->rest > 0) {
                $premiumData->payed = 0;
                $premiumData->rest = $premiumData->rest - $payedDebt;
                $premiumDAO->update($premiumData);
            }
        }

        reverseEntryWithItsID($action, 1);
        $mytransactions->commit();
        $flag = 1;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $voucher = $_GET['id'];
        $clientdata = $clientDeptChangeDAO->load1($voucher);
        $clientId = $clientdata->clientid;
        markClientAsNOTInUse($clientid);
        $flag = 0;
    }
    liveBackupComment("-- clientPayedDeptController delete end - with clientdebtchangeId =" . $_GET['id']);
    return $flag;
}

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


    $shownData = $clientDeptChangeExt->queryPayedDeptOnly($startDate, $endDate);
    $paginate->setTotal(count($allColums));

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


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

function showbymodelid($modelid) {
    global $clientDeptChangeExt;
    global $smarty;


    $shownData = $clientDeptChangeExt->showbymodelid($modelid);
    $paginate->setTotal(count($allColums));

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


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

function edit($clientdebtchangeid) {
    global $clientDeptChangeDAO;

    $clientdebtchangeData = $clientDeptChangeDAO->load($clientdebtchangeid);

    return $clientdebtchangeData;
}

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

    //to use the variable out side the funcion
    global $Save;
    global $SaveExt;

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

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

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and subtract from save tbl
function getSaveValueAndSubtract($savevaluechanged, $saveid, $saveConversionFactor = 0) {

    //to use the variable out side the funcion
    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 showx($clientid, $clientdebtchangemodelid, $startDate, $endDate, $bure) {
    global $clientDeptChangeExt;
    global $clientDAO;
    global $clientDeptChangeDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';


    if (isset($clientid) && $clientid != '-1' && $clientid != "-2") {
        $clientnamedata = $clientDAO->load($clientid);
        $message = " اسم العميل " . $clientnamedata->clientname;
        $smarty->assign('message', $message);

        $queryString .= ' clientdebtchange.clientid =' . $clientid . ' AND';
    }
    if (isset($clientid) && $clientid != "-1" && $clientid == "-2") {
        $message = " كل العملاء";
        $smarty->assign('message', $message);
        $queryString .= ' clientdebtchange.clientid > 0 AND';
    }
    if (isset($clientdebtchangemodelid) && $clientdebtchangemodelid != '-1') {
        //$mydataprocess=$clientDeptChangeDAO->load($processid);
        $message = "تقرير  عميل لعمليه   " . $processid;
        $smarty->assign('message', $message);


        $queryString .= ' clientdebtchange.clientdebtchangemodelid = ' . $clientdebtchangemodelid . ' AND';
    }
    if (!empty($startDate) && !empty($endDate)) {


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

        $startDate = $startDate . " 00:00:00";
        $endDate = $endDate . " 23:59:59";

        $queryString .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . '" AND clientdebtchange.clientdebtchangedate <= "' . $endDate . '" AND';
    }
    if ($bure == 1) { //hide deleted
        $queryString .= ' clientdebtchange.del = 0 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->searchforDeptAndSave($queryString);
    $sum;
    foreach ($shownData as $data) {
        if ($data->del != 1) {
            $sum += $data->clientdebtchangeamount;
        }
    }
    $smarty->assign('sum', $sum);


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

function showallajax() {
    global $clientDeptChangeExt;
    global $ProgramsettingDAO;
    global $myUserRecord;
    $userData = $myUserRecord->load($_SESSION['userid']);
    $today = date('Y-m-d');

    $sIndexColumn = "clientdebtchangeid";

    /* DB table to use */
    $sTable = " clientdebtchange
		JOIN client ON (client.clientid  = clientdebtchange.clientid and client.conditions=0)
                JOIN user ON user.userid  = clientdebtchange.userid
                JOIN savedaily on (
                    (savedaily.savedailymodelid = clientdebtchange.clientdebtchangeid AND savedaily.tablename in('premiumController.php','clientPayedDeptController.php') )
                    or
                    ( savedaily.savedailymodelid = clientdebtchange.clientdebtchangemodelid AND savedaily.tablename = 'clientPayedDeptSellBillsController.php' )
                )
                join save on savedaily.saveid =  save.saveid";

    $aColumns = array('clientdebtchangeid', 'paySerialNo', 'clientname', 'clientdebtchangedate', 'clientdebtchangebefore', 'clientdebtchangeamount', 'clientdebtchangeafter', 'employeename', 'savename', 'del', 'clientdebtchange.dailyentryid', 'clientdebtchange.tablename', 'clientdebtchangemodelid', 'paytype');

    // 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] == "clientdebtchangedate") {
                //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'];
    $clientid = (int) $_REQUEST["clientid"];
    $clientdebtchangemodelid = (int) $_REQUEST["clientdebtchangemodelid"];
    $paySerialNo = (int) $_REQUEST["paySerialNo"];
    $bure = (int) $_REQUEST["bure"];
    $onlyReceipt = (int) $_REQUEST["onlyReceipt"];
    $costcenterid = (int) $_REQUEST["costcenterid"];

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

    if (isset($clientid) && $clientid > 0) {
        $queryString .= ' clientdebtchange.clientid =' . $clientid . ' AND';
    } else if (isset($clientid) && $clientid != "-1" && $clientid == "-2") {
        $queryString .= ' clientdebtchange.clientid > 0 AND';
    }
    if (isset($costcenterid) && $costcenterid > 0) {
        $queryString .= ' clientdebtchange.costcenterid =' . $costcenterid . ' AND';
    }
    if (isset($clientdebtchangemodelid) && $clientdebtchangemodelid > 0) {
        $queryString .= ' clientdebtchange.clientdebtchangemodelid = ' . $clientdebtchangemodelid . ' AND';
    }
    if (isset($paySerialNo) && $paySerialNo > 0) {
        $queryString .= ' clientdebtchange.paySerialNo = ' . $paySerialNo . ' AND';
    }

    if ($userData->viewclients == 0) {
        $queryString .= ' clientdebtchange.userid =' . $_SESSION['userid'] . ' AND';
    }
    /* serch with date is done below
     * if (isset($startDate) && !empty($startDate)) {
      $startDate = $startDate . " 00:00:00";
      $queryString .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . '" AND';
      }
      if (isset($endDate) && !empty($endDate)) {
      $endDate = $endDate . " 23:59:59";
      $queryString .= ' clientdebtchange.clientdebtchangedate <= "' . $endDate . '" AND';
      } */
    if ($bure == 1) { //hide deleted
        $queryString .= ' clientdebtchange.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 .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . '" and clientdebtchange.clientdebtchangedate <= "' . $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;
    /* if empty get today stop it
      if ($queryString == "") {
      //display the converted time ##reportsPlusHours
      ################
      $today = date('Y-m-d');
      $yesterday = date("Y-m-d", strtotime('-1 days'));
      if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
      $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
      $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
      $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
      //
      $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
      $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
      } else {
      $endToday = $today . ' 23:59:59';
      $startToday = $today . " 00:00:00";
      //
      $endYesterday = $today . ' 23:59:59';
      $startYesterday = $today . " 00:00:00";
      }
      if (date('H') < $Programsetting->reportsPlusHours) {
      $startDate = $startYesterday;
      $endDate = $endYesterday;
      } else {
      $startDate = $startToday;
      $endDate = $endToday;
      }
      ##############
      if ($sWhere == '') {
      $queryString = ' WHERE';
      } else {
      $queryString = ' AND';
      }
      $queryString .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . '" and clientdebtchange.clientdebtchangedate <=  "' . $endDate . '" ';
      } */
    $sWhere .= $queryString;
    //----------------------------------------------------------------------
    if ($queryString != "") {
        $sWhere .= " AND clientdebtchange.tablename in ('premiumController.php','clientPayedDeptController.php','clientPayedDeptSellBillsController.php')";
        if ($onlyReceipt == 1) { // show where serialNo != 0
            $queryString .= ' clientdebtchange.paySerialNo != 0 AND';
        }
    }

    $sgroup = ' group by clientdebtchangeid ';
    $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sgroup $sOrder $sLimit ";
//    echo $sQuery;
    ////if empty qquery dont go to db
    if ($queryString != "") {
        $rResult = $clientDeptChangeExt->runSelectQuery($sQuery);
        /* Data set length after filtering */
        /* $sQuery = "SELECT COUNT(" . $sIndexColumn . ") as clientdebtchangeid FROM  $sTable "; //$sOrder
          $rResultFilterTotal = $clientDeptChangeExt->runSelectQuery($sQuery);
          foreach ($rResultFilterTotal as $oneis) {
          $countis = $oneis->clientdebtchangeid;
          }
          $iFilteredTotal = $countis; */
        /* Total data set length */
        $sQuery = "SELECT COUNT(distinct " . $sIndexColumn . ") as clientdebtchangeid FROM  $sTable $sWhere";
        //echo $sQuery;
        $rResultTotal = $clientDeptChangeExt->runSelectQuery($sQuery);


        foreach ($rResultTotal as $oneis) {
            $countit = $oneis->clientdebtchangeid;
        }
        //$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;
    }

    if ($_POST['curlpost'] == 1) {
        echo json_encode($rResult);
        exit();
    }


    $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 "clientdebtchangeid":
                    $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 "clientdebtchangedate":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientdebtchangebefore":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientdebtchangeamount":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientdebtchangeafter":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "clientname":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "employeename":
                    $row[] = $aRow->$aColumns[$i];
                    break;
                case "savename":
                    if ($aRow->tablename == 'premiumController.php' || $aRow->tablename == 'clientPayedDeptController.php') {
                        $row[] = $aRow->$aColumns[$i];
                        $row[] = 'تحصيل';
                    } elseif ($aRow->tablename == 'clientPayedDeptSellBillsController.php') {
                        $row[] = $aRow->paytype;
                        $row[] = 'دفعة على فاتورة';
                    }
                    break;
                default:
                    break;
            }
        }
        ////
        $row[] = '<a href="clientPayedDeptController.php?do=edit&id=' . $aRow->clientdebtchangeid . '" target="_blank" type="button" class="btn btn-default btn-lg editicon"> </a>';
        $delBtn = '';
        if ($aRow->del == 0) {
            if ($aRow->tablename == 'premiumController.php' || $aRow->tablename == 'clientPayedDeptController.php') {
                if ($aRow->tablename == 'premiumController.php') {
                    $premium = '&premium=' . $aRow->clientdebtchangemodelid;
                }
                $delBtn = '<a data-go="clientPayedDeptController.php?do=remove&id=' . $aRow->clientdebtchangeid . '&action=' . $aRow->dailyentryid . $premium . '" class="removethis"><input  type="button"  class="btn btn-danger" value="حذف" /> </a>'; //pull-right
            } elseif ($aRow->tablename == 'clientPayedDeptSellBillsController.php') {
                $delBtn = '<a data-id="' . $aRow->clientdebtchangeid . '" data-type="' . $aRow->paytype . '" class="delPayment"><input  type="button"  class="btn btn-danger" value="حذف" /> </a>'; //pull-right
            }
        } else {
            $delBtn = 'محذوف';
        }
        $row[] = $delBtn;
        //        $row[] = '<a target="_blank" href="clientPayedDeptController.php?do=editprint&id=' . $aRow->clientdebtchangeid . '" ><input  type="button"  class="btn btn-success " value="طباعه" /> </a>'; //pull-right
        $row[] = '<a target="_blank" href="clientPayedDeptController.php?do=editprint2&id=' . $aRow->clientdebtchangeid . '" ><input  type="button"  class="btn btn-success" value="طباعه" /> </a>'; //pull-right
        $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->clientdebtchangeamount;
        }
        //('premiumController.php','clientPayedDeptController.php','clientPayedDeptSellBillsController.php')
        $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(clientdebtchangeamount) as clientdebtchangeamount FROM  $sTable $sWhere and del = 0 "; //$sgroup $sOrder $sLimit
        $rResult = $clientDeptChangeExt->runSelectQuery($sQuery);
        $output['totals']["totalRecitsAll"] = (float) $rResult[0]->clientdebtchangeamount; //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 getClientDataFromClientInUseSP($clientid) {
    global $clientExt;
    global $clientDAO;
    if ($clientid == 1) {
        $client_data = $clientDAO->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientExt->callClientInUseSP($clientid);
        while ($client_data->clientdebt == '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 client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientExt->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

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

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 addExpenseType() {
    global $expenseTypeDAO;

    $typeName = 'صرف نسبة التحصيلات';
    $typeId = 0;
    $check = $expenseTypeDAO->queryByExpensestypename($typeName);
    if (count($check) > 0) {
        $typeId = $check[0]->expensestypeid;
    } else {
        $dataArr = array(
            'parent' => '0',
            'name' => $typeName,
        );
        CURL_IT2($dataArr, 'expensesTypeController.php?do=add');
        $check = $expenseTypeDAO->queryByExpensestypename($typeName);
        $typeId = $check[0]->expensestypeid;
    }
    return $typeId;
}

function addExpense($name, $value, $type, $saveid) {
    $dataArr = array(
        'expensesname' => $name,
        'expensevalue' => $value,
        'expensetype' => $type,
        'saveid' => $saveid,
        'paymethod' => 0,
        'Costcenterid' => -1,
        'expensecomment' => '',
        'bankid' => -1,
        'checkNo' => '',
    );
    CURL_IT2($dataArr, 'expensesController.php?do=add');
}

function addEmployeePersonal($empid, $dateTime, $value, $type, $saveid) {
    $dataArr = array(
        'isMandobReward' => 1,
        'empName' => $empid,
        'empValue' => $value,
        'employeepersonneldate' => $dateTime, //date('Y-m-d H:i:s'),
        'type' => $type,
        'Costcenterid' => '-1',
        'netSalary' => '', //not required it is calculated there
        'desc' => '', //"تقفيل يوم : $day",
        'paymethod' => '0',
        'saveid' => $saveid,
        'bankid' => '-1',
        'checkNo' => '',
        'print' => '0',
    );
    $xyz = CURL_IT2($dataArr, 'employeePersonalController.php?do=add');
    print_r($xyz);
}

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 getSuppliers() {
    global $supplierDAO;
    $suppliersData = $supplierDAO->queryByCondition(0);
    return $suppliersData;
}

function addFromExcel() {
    global $clientDAO;

    ## upload file temporarely
    $handle = new upload($_FILES['clientssheet']);
    $excelfileName = uploadfile($handle, "../upload/clientPayedDebt");
    $inputFileName = "../upload/clientPayedDebt/" . $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;
            $clientname = $rowData[$col];
            $col++;
            $clientphone = $rowData[$col];
            $col++;
            $clientcode = $rowData[$col];
            $col++;
            $clientcurrentDebt = $rowData[$col];
            $col++;
            $payedAmount = $rowData[$col];
            $col++;

            if ($payedAmount > 0) {
                $clientData = $clientDAO->queryByClientname($clientname);

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

                $last_clientdebtchangeid = (int) R::getCell('SELECT clientdebtchangeid FROM clientdebtchange order by clientdebtchangeid desc limit 1');
                $_POST['voucher'] = $last_clientdebtchangeid + 1;
                $_POST['oldvoucher'] = $last_clientdebtchangeid + 1;
                $_POST['notPremium'] = 'notPremium';
                $_POST['saveorbankPremium'] = 1;
                // 'clientnegative' => 1,
                // 'currencyId' => 1,
                // 'cFactor' => 1,

                add();
            }
        }
        unlink($inputFileName);
        $mytransactions->commit();
    } catch (Exception $e) {
        $mytransactions->rollback();
        //die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
}
