<?php

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


//global varable
global $showoutside;

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



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

//Shippercompanies
require_once('../models/dao/ShippercompaniesDAO.class.php');
require_once('../models/dto/Shippercompanie.class.php');
require_once('../models/mysql/ShippercompaniesMySqlDAO.class.php');
require_once('../models/mysql/ext/ShippercompaniesMySqlExtDAO.class.php');

//Representativecompany
require_once('../models/dao/RepresentativecompanyDAO.class.php');
require_once('../models/dto/Representativecompany.class.php');
require_once('../models/mysql/RepresentativecompanyMySqlDAO.class.php');
require_once('../models/mysql/ext/RepresentativecompanyMySqlExtDAO.class.php');

//Policy
require_once('../models/dao/PolicyDAO.class.php');
require_once('../models/dto/Policy.class.php');
require_once('../models/mysql/PolicyMySqlDAO.class.php');
require_once('../models/mysql/ext/PolicyMySqlExtDAO.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');
//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');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');
//get the do the action
$do = $_GET['do'];

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

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

  Controller Name :- userCTRL

  OPERTATION in Controller

  1-display add form
  2- add in user tble
  3-display sucess or error
  4-display show form
  5-delete from user tbl
  6-edit in user data

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


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



//here goes the instances and general variables
//Shippercompanies
$myShippercompanies = new Shippercompanie();
$myShippercompaniesRecord = new ShippercompaniesMySqlDAO();
$myShippercompaniesEx = new ShippercompaniesMySqlExtDAO();

//Representativecompany
$myRepresentativecompany = new Representativecompany();
$myRepresentativecompanyRecord = new RepresentativecompanyMySqlDAO();

//Policy
$myPolicy = new Policy();
$myPolicyRecord = new PolicyMySqlDAO();
$myPolicyEx = new PolicyMySqlExtDAO();


//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();

//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();

//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

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

//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

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

$programSettingDAO = new ProgramsettingsMySqlDAO();
$Programsettingdata = $programSettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
//handling saveid session
/* if(!isset($_SESSION['saveid']))
  {
  $_SESSION['saveid'] = 1;
  }
 */
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

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


    $shippercompaniesData = loadCompany();
    $smarty->assign("shippercompaniesData", $shippercompaniesData);

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

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

    //here the smarty templates
    $smarty->display("policyview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    $addvalue = add();

    if ($addvalue != 0) {

        header("location:?do=sucess");
    } else {
        $url = "policyController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = " ت اضافه البوليصه لعدم وجود مبلغ كافى بالخزنه";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");


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

    $allSave = $mySaveRecord->queryByConditions(0);
    $smarty->assign("allSave", $allSave);
    //load shippercompanies Data
    $shippercompaniesData = loadCompany();
    $smarty->assign("shippercompaniesData", $shippercompaniesData);

    $companyId = $_REQUEST['companyId'];
    $type = $_REQUEST['type'];

    if (isset($companyId) && $companyId != "" && !isset($type)) {
        $messageData = $myShippercompaniesRecord->load($companyId);
        $message = "شركة الشحن: " . $messageData->companyName;
        $smarty->assign("message", $message);

        showByCompany($companyId);
    } elseif (isset($type) && $type != "" && ($type == 1 || $type == 2) && (!isset($companyId) || $companyId == -1)) {
        if ($type == 1)
            $typ = 'عملاء';
        else
            $typ = 'موردين';

        $message = " النوع: " . $typ;
        $smarty->assign("message", $message);
        showByType($type);
    } elseif (isset($companyId) && $companyId != "" && isset($type) && $type != "" && ($type == 1 || $type == 2)) {
        $messageData = $myShippercompaniesRecord->load($companyId);
        $message = "شركة الشحن: " . $messageData->companyName;
        if ($type == 1)
            $typ = 'عملاء';
        else
            $typ = 'موردين';

        $message .= " - النوع: " . $typ;
        $smarty->assign("message", $message);

        $query = ' and policy.companyId = ' . $companyId . ' and senderType = ' . $type;

        showByQuery($query);
    } else {
        showAll();
    }


    //here the smarty templates
    $smarty->display("policyview/show.html");

    $smarty->assign("customBank", 1);
    $smarty->assign("customCheck", 1);
} elseif ($do == "executeOperation") {

    //here the permssion check
    include_once("../public/authentication.php");



    // here the function that do the action
    executeOperation();



    //load shippercompanies Data
    $shippercompaniesData = loadCompany();
    $smarty->assign("shippercompaniesData", $shippercompaniesData);


    showAll();


    //here the smarty templates
    $smarty->display("policyview/show.html");

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

    $policyId = $_GET['policyId'];

    try {
        // here the function that do the action
        delete($policyId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

    $policyId = $_GET['policyId'];

    $loadData = edit($policyId);
    $smarty->assign("loadData", $loadData);


    $shippercompaniesData = loadCompany();
    $smarty->assign("shippercompaniesData", $shippercompaniesData);

    // if ($loadData->senderType == 1) {
    //     $customerData = getCustomers(); //undeleted suppliers
    //     $smarty->assign("customerData", $customerData);
    // } else {
    //     $suppliersData = getSuppliers(); //undeleted suppliers
    //     $smarty->assign("suppliersData", $suppliersData);
    // }

    $smarty->assign("customsPolicy", 1);
    //here the smarty templates
    $smarty->display("policyview/edit.html");
} elseif ($do == "update") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        update();

        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    //here the permssion check
    include_once("../public/authentication.php");

    $policyId = $_GET['id'];

    $loadData = edit($policyId);
    $smarty->assign("loadData", $loadData);


    $shippercompaniesData = loadCompany();
    $smarty->assign("shippercompaniesData", $shippercompaniesData);


    //here the smarty templates
    $smarty->display("policyview/editprint.html");


    $smarty->assign("customPrint", 1);
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}


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

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

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

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

function getCustomers() {
    global $clientDAO;
    $clientData = $clientDAO->queryByCondition(0);
    return $clientData;
}

function loadCompany() {
    global $myShippercompaniesRecord;

    $shippercompaniesData = $myShippercompaniesRecord->queryByTempdele(0);

    return $shippercompaniesData;
}

function add() {
    global $myPolicy;
    global $myPolicyRecord;

    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $currencyEX;
    global $today;

    //supplier
    global $supplier;
    global $supplierDao;
    global $supplierExt;
    //supplier debt change
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $supplierDeptChangeExt;

    $policyName = $_POST['policyName'];
    $policyNum = $_POST['policyNum'];
    $policyDate = $_POST['policyDate'];
    $policyCost = $_POST['policyCost'];
    $companyId = $_POST['companyId'];
    $policyType = $_POST['policyType'];
    $senderType = $_POST['type'];
    $SenderName = $_POST['SenderName'];
    $SenderId = (int) $_POST['SenderId'];
    $invoicenumber = $_POST['invoicenumber'];
    $affectSave = (int) $_POST['affectSave'];

    $myPolicy->companyId = $companyId;
    $myPolicy->policyCost = $policyCost;
    $myPolicy->policyDate = $policyDate;
    $myPolicy->policyName = $policyName;
    $myPolicy->policyNum = $policyNum;
    $myPolicy->policyType = $policyType;
    $myPolicy->senderType = $senderType;
    $myPolicy->senderName = $SenderName;
    $myPolicy->senderId = $SenderId;
    $myPolicy->affectSave = $affectSave;
    $myPolicy->tempdele = 0;
    $myPolicy->saveId = $_SESSION['saveid'];
    $myPolicy->invoicenumber = $invoicenumber;

    $saveValueafterValid = 1;
    //    if ($policyCost > 0) {
    //        //get save value
    //        $saveValueBefore = getSaveValueBefore($_SESSION['saveid']);
    //
    //
    //
    //
    //        $saveValueafterValid = $saveValueBefore - $policyCost;
    //
    //        if ($saveValueafterValid >= 0) {
    //            $saveValuebeforeValid = 1;
    //        } else {
    //            $saveValuebeforeValid = 0;
    //            return $saveValuebeforeValid;
    //        }
    //    }

    $policyId = $myPolicyRecord->insert($myPolicy);

    //check if payed or not to change save value
    if ($policyCost > 0 && $affectSave == 0) {
        //get saveValue before and saveValue after Plus lPayed
        $saveData = getSaveValueAndMins($_SESSION['saveid'], $policyCost);
        $saveId = $saveData[0];
        $saveValuebefore = $saveData[1];
        $saveValueafter = $saveData[2];

        //update save value after add sellbill
        updateSave($saveId, $saveValueafter);

        //insert into savedaily tbl from save
        insertSavedaily($saveValuebefore, $policyCost, 1, $saveId, "اضافة بوليصة شحن", $policyId, $saveValueafter, "policyController.php");
    }



    if ($senderType == 1) { //Client
        try {
            $clientdataSP = getClientDataFromClientInUseSP($SenderId);
            $debtBefore = $clientdataSP->clientdebt;
            //insert into supplierdeptchange tbl
            $clientDeptChange->comment = '';
            $clientDeptChange->processname = 'إضافة بوليصة شحن';
            $clientDeptChange->clientdebtchangeafter = $debtBefore;
            $clientDeptChange->clientdebtchangeamount = $policyCost;
            $clientDeptChange->totalOperationCost = 0;
            $clientDeptChange->clientdebtchangebefore = $debtBefore;
            $clientDeptChange->clientdebtchangedate = date("Y-m-d H:i:s");
            $clientDeptChange->clientdebtchangemodelid = $policyId;
            $clientDeptChange->clientdebtchangetype = 0;
            $clientDeptChange->tablename = "policyController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $SenderId;
            $clientDeptChange->dailyentryid = 0;
            //Insert
            $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);
            markClientAsNOTInUse($SenderId);
        } catch (Exception $ex) {
            markClientAsNOTInUse($SenderId);
        }
    } elseif ($senderType == 2) { //Supplier
        try {
            $supplierdata = getSupplierDataFromSupplierInUseSP($SenderId);
            $debtBefore = $supplierdata->suppliercurrentDebt;
            $supplierdebtchangemodelid = $policyId;

            //insert into supplierdeptchange tbl
            $supplierDeptChange->comment = '';
            $supplierDeptChange->processname = "إضافة بوليصة شحن";
            $supplierDeptChange->supplierdebtchangeafter = $debtBefore;
            $supplierDeptChange->supplierdebtchangeamount = 0;
            $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
            $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s");
            $supplierDeptChange->supplierdebtchangemodelid = $supplierdebtchangemodelid;
            $supplierDeptChange->supplierdebtchangetype = 0;
            $supplierDeptChange->tablename = "policyController.php";
            $supplierDeptChange->userid = $_SESSION['userid'];
            $supplierDeptChange->supplierid = $SenderId;
            $supplierDeptChange->dailyentryid = 0;

            //Insert
            $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);

            markSupplierAsNOTInUse($SenderId);
        } catch (Exception $ex) {
            markSupplierAsNOTInUse($SenderId);
        }
    }

    return 1;
}

// show the form
function showAll() {
    global $myPolicyEx;
    global $myPolicy;

    global $smarty;

    $policyData = $myPolicyEx->queryWithOrder();

    $smarty->assign('policyData', $policyData);
}

// show the form
function showByCompany($companyId) {
    global $myPolicyEx;

    global $smarty;

    $policyData = $myPolicyEx->queryWithCompanyId($companyId);

    //    print_r($policyData);

    $smarty->assign('policyData', $policyData);
}

// show the form
function showByType($type) {
    global $myPolicyEx;
    global $smarty;

    $policyData = $myPolicyEx->queryWithType($type);

    //    print_r($policyData);

    $smarty->assign('policyData', $policyData);
}

function showByQuery($query) {
    global $myPolicyEx;
    global $smarty;

    $policyData = $myPolicyEx->queryWithQuery($query);

    //    print_r($policyData);

    $smarty->assign('policyData', $policyData);
}

//finaly deleted from user tbl
function delete($policyId) {
    //to use the variable out side the funcion
    global $myPolicy;
    global $myPolicyRecord;
    global $myPolicyEx;



    try {

        if (isset($policyId) && $policyId != "") {


            $policyData = $myPolicyRecord->load($policyId);

            $policyCost = $policyData->policyCost;
            $saveId = $policyData->saveId;


            if ($policyCost > 0) {
                //get saveValue before and saveValue after Plus lPayed
                $saveData = getSaveValueAndPlus($saveId, $policyCost);
                $saveId = $saveData[0];
                $saveValuebefore = $saveData[1];
                $saveValueafter = $saveData[2];

                //update save value after add sellbill
                updateSave($saveId, $saveValueafter);

                //insert into savedaily tbl from save
                insertSavedaily($saveValuebefore, $policyCost, 0, $saveId, "حذف بوليصة شحن", $policyId, $saveValueafter, "policyController.php");
            }


            //delete from  Policy tbl
            $myPolicy->tempdele = 1;
            $myPolicy->policyId = $policyId;

            $myPolicyEx->updateTempdele($myPolicy);

            $note = "success";
        } else {
            $note = "حدث خطأ أثناء حذف البوليصة";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف البوليصة";
    }

    return $note;
}

// edit in table
function edit($policyId) {
    //to use the variable out side the funcion
    global $myPolicyRecord;

    //load  Policy data
    $loadData = $myPolicyRecord->load($policyId);

    return $loadData;
}

// update table
function update() {
    //to use the variable out side the funcion
    global $myPolicy;
    global $myPolicyRecord;


    $policyName = $_POST['policyName'];
    $policyNum = $_POST['policyNum'];
    $policyDate = $_POST['policyDate'];
    $policyCost = $_POST['policyCost'];
    $companyId = $_POST['companyId'];
    $policyType = $_POST['policyType'];
    $SenderName = $_POST['SenderName'];
    $SenderId = (int) $_POST['SenderId'];
    $tempdele = $_POST['tempdele'];
    $policyId = $_POST['policyId'];
    $saveId = $_POST['saveId'];
    $senderType = $_POST['type'];
    $invoicenumber = $_POST['invoicenumber'];
    $affectSave = $_POST['affectSave'];


    $myPolicy->companyId = $companyId;
    $myPolicy->policyCost = $policyCost;
    $myPolicy->policyDate = $policyDate;
    $myPolicy->policyName = $policyName;
    $myPolicy->policyNum = $policyNum;
    $myPolicy->policyType = $policyType;
    $myPolicy->senderName = $SenderName;
    $myPolicy->senderId = $SenderId;
    $myPolicy->tempdele = $tempdele;
    $myPolicy->policyId = $policyId;
    $myPolicy->saveId = $saveId;
    $myPolicy->senderType = $senderType;
    $myPolicy->invoicenumber = $invoicenumber;
    $myPolicy->affectSave = $affectSave;

    $myPolicyRecord->update($myPolicy);
}

function executeOperation() {
    //to use the variable out side the funcion
    global $myPolicyRecord;
    global $smarty;

    $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $policyId) {

            //get store name
            $policyData = $myPolicyRecord->load($policyId);
            $policyName = $policyData->policyName;

            if ($operationType == '3') {
                //tempdelete
                $note = delete($policyId);
                if ($note != "success") {
                    $outputString .= $policyName . ": " . $note . "<br/>";
                } else {
                    $outputString .= $policyName . ": تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

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

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update in Save tbl
function updateSave($saveid, $savevalueafter) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

    //update initialvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;

    $mySaveEx->updateSaveValue($mySave);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

    //insert in Savedaily tbl
    $mySavedaily->savedailydate = date("Y-m-d H:i:s");
    $mySavedaily->userid = $_SESSION['userid'];
    $mySavedaily->savedailysavebefore = $savedailysavebefore;
    $mySavedaily->savedailychangeamount = $savedailychangeamount;
    $mySavedaily->savedailychangetype = $savedailychangetype;
    $mySavedaily->saveid = $saveid;
    $mySavedaily->processname = $processname;
    $mySavedaily->savedailymodelid = $savedailymodelid;
    $mySavedaily->savedailysaveafter = $savedailysaveafter;
    $mySavedaily->tablename = $tablename;

    $mySavedailyRecord->insert($mySavedaily);
}

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