<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
include("../public/include_dao.php");
//Partnertransferbetween
require_once('../models/dao/PartnertransferbetweenDAO.class.php');
require_once('../models/dto/Partnertransferbetween.class.php');
require_once('../models/mysql/PartnertransferbetweenMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnertransferbetweenMySqlExtDAO.class.php');
//Partnerwithdrawal
require_once('../models/dao/PartnerwithdrawalDAO.class.php');
require_once('../models/dto/Partnerwithdrawal.class.php');
require_once('../models/mysql/PartnerwithdrawalMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerwithdrawalMySqlExtDAO.class.php');
//Partner
require_once('../models/dao/PartnerDAO.class.php');
require_once('../models/dto/Partner.class.php');
require_once('../models/mysql/PartnerMySqlDAO.class.php');
require_once('../models/mysql/ext/PartnerMySqlExtDAO.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');

require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');

require_once('../models/dao/AccountmovementDAO.class.php');
require_once('../models/dto/Accountmovement.class.php');
require_once('../models/mysql/AccountmovementMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountmovementMySqlExtDAO.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');

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 :- transfermoneyCTRL التحويل بين الخزن

  OPERTATION in Controller

  1-display add form
  2- add in transfermoney tble
  3-update savefrom value (-)
  4-insert into savedaily tbl
  5-update saveto value (+)
  6-insert into savedaily tbl
  7-display sucess or error
  8-display show and delete
  9-tempdelete from Expenses tbl
  10-returndelete save value (+)

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


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


//here goes the instances and general variables

$myPartnertransferbetween = new Partnertransferbetween();
$myPartnertransferbetweenRecord = new PartnertransferbetweenMySqlDAO();
$myPartnertransferbetweenEx = new PartnertransferbetweenMySqlExtDAO();
//Partnerwithdrawal
$myPartnerwithdrawal = new Partnerwithdrawal();
$myPartnerwithdrawalRecord = new PartnerwithdrawalMySqlDAO();
$myPartnerwithdrawalEx = new PartnerwithdrawalMySqlExtDAO();
//Partner
//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();



//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();

//Partner
$myPartner = new Partner();
$myPartnerRecord = new PartnerMySqlDAO();
$myPartnerEx = new PartnerMySqlExtDAO();

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


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

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

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


$account = new Bankaccount();
$accountDAO = new BankaccountMySqlDAO;
$accountExtDAO = new BankaccountMySqlExtDAO;

$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;

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

//User
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

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

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

$userData = $myUserRecord->load($_SESSION['userid']);
$smarty->assign("userData", $userData);
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    $partnerData = loadPartner();
    $smarty->assign("partnerData", $partnerData);

    $allSave = $mySaveRecord->queryAll();
    $smarty->assign("allSave", $allSave);
    //$bank = $bankExtDAO->queryAllExt();
    $bank = $bankDAO->queryAll();
    $smarty->assign("bank", $bank);

    $saveData = loadSaveBySesssionId();
    $smarty->assign("saveData", $saveData);



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

    //here the permssion check
    include_once("../public/authentication.php");
    //add();
    // here the function that do the action
    $saveValuebeforeValid = add();
    if ($saveValuebeforeValid == 1) {
        header("location:?do=sucess");
    } else {
        $url = "partnerwithdrawalController.php";
        $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);

    $partnerData = loadPartner();
    $smarty->assign("partnerData", $partnerData);

    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    $bank = $bankDAO->queryAll();
    $smarty->assign("bank", $bank);

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $partnerId = $_REQUEST['partnerid'];
    $saveId = $_REQUEST['saveid'];
    $partenrwithdrawaltype = $_POST['partenrwithdrawaltype'];
    $partenrwithdrawalid = (int) $_REQUEST['id'];

    $bankid = $_REQUEST['bankid'];
    $bankaccountid = (int) $_REQUEST['bankaccountid'];

    $queryString = '';
    $message = '';
    if (isset($partenrwithdrawalid) && $partenrwithdrawalid > 0) {
        $message .= " [رقم العملية: " . $partenrwithdrawalid . " ] ";
        $queryString .= ' and partnerwithdrawal.partnerwithdrawalid =' . $partenrwithdrawalid . ' ';
    }
    if (isset($partnerId) && $partnerId != "-1") {
        $messageData = $myPartnerRecord->load($partnerId);
        $message .= " [إسم الشريك: " . $messageData->partnername . " ] ";
        $queryString .= ' and partnerwithdrawal.partnerid =' . $partnerId . ' ';
    }
    if (isset($saveId) && $saveId != "-1") {
        $message .= " [بحث عن طريق خزنة] ";
        $queryString .= ' and  partnerwithdrawal.saveid =' . $saveId . '  ';
    }
    if (isset($bankid) && $bankid != "-1") {
        $messageData = $bankDAO->load($bankid);
        $message .= " [إسم البنك : " . $messageData->bankname . "] ";
        $queryString .= ' and partnerwithdrawal.bankid =' . $bankid . ' ';
    }
    if (isset($bankaccountid) && $bankaccountid != "-1" && $bankaccountid > 0) {
        $messageData = $accountDAO->load($bankaccountid);
        $message .= " [إسم الحساب البنكى : " . $messageData->accountname . "] ";
        $queryString .= ' and partnerwithdrawal.bankaccountid =' . $bankaccountid . ' ';
    }
    if (isset($partenrwithdrawaltype) && $partenrwithdrawaltype != '2') {
        if ($partenrwithdrawaltype == '1') {
            $message .= "[ بحث عن طريق سحب ]";
        } else {
            $message .= "[ بحث عن طريق ايداع ]";
        }
        $queryString .= ' and partnerwithdrawal.partenrwithdrawaltype =' . $partenrwithdrawaltype . ' ';
    }

    if (isset($startDate) && $startDate != "") {
        $message .= " [من تاريخ : " . $startDate . " ]";
        $queryString .= ' and  partnerwithdrawal.partnerwithdrawaldate >= "' . $startDate . '" ';
    }
    if (isset($endDate) && $endDate != "") {
        $message .= " [الى تاريخ : " . $endDate . " ]";
        $queryString .= ' and  partnerwithdrawal.partnerwithdrawaldate <= "' . $endDate . '" ';
    }


    if ($queryString == '') {//no search get today
        $startDate = $endDate = date('Y-m-d');
        $message .= " [من تاريخ : " . $startDate . " ]";
        $queryString .= ' and  partnerwithdrawal.partnerwithdrawaldate >= "' . $startDate . '" ';
        $message .= " [الى تاريخ : " . $endDate . " ]";
        $queryString .= ' and  partnerwithdrawal.partnerwithdrawaldate <= "' . $endDate . '" ';
    }
    $smarty->assign("message", $message);
    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryStringSearch2($queryString);


    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        if ($mypartnerwithdrawalData->partenrwithdrawaltype == 0) {
            $totalone += $mypartnerwithdrawalData->partnerwithdrawalvalue;
        } else {
            $totaltwo += $mypartnerwithdrawalData->partnerwithdrawalvalue;
        }
    }
    $totalall = $totalone - $totaltwo;



    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);

    $queryString2 = " ";
    if (isset($startDate) && !empty($startDate) && isset($endDate) && !empty($endDate)) {
        $queryString2 .= ' and  partnertransferbetween.partnerdate  >= "' . $startDate . '" and partnertransferbetween.partnerdate <= "' . $endDate . '" ';
    }

    if ($partnerId > 0) {
        $queryString2 .= ' AND (partnertransferbetween.partneridfrom = ' . $partnerId . '
        or partnertransferbetween.partneridto = ' . $partnerId . ')';
    }




    if ($queryString2 != " ") {
        $partnertransferbetweenData = $myPartnertransferbetweenEx->queryStringSearch($queryString2);
        if ($partnerId > 0) {
            foreach ($partnertransferbetweenData as $partnertransferbetween) {
                if ($partnertransferbetween->partneridto == $partnerId) {
                    $totalall -= $partnertransferbetween->partnervalue;
                } else {
                    $totalall += $partnertransferbetween->partnervalue;
                }
            }
        } else {
            foreach ($partnertransferbetweenData as $partnertransferbetween) {
                $totalall -= $partnertransferbetween->partnervalue;
            }
        }
        $totalalls = $totalall;
        $smarty->assign('totalall', $totalalls);
        $smarty->assign('partnertransferbetweenData', $partnertransferbetweenData);
    }


    $smarty->display("partnerwithdrawalview/show.html");
    $smarty->assign("customCheck", 1);
}
//returndelete
elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $partnerwithdrawalId = $_GET['partnerwithdrawalid'];

    // here the function that do the action
    $saveValuebeforeValid = returndelete($partnerwithdrawalId);
    if ($saveValuebeforeValid[1] == 1) {
        header("location:?do=sucess");
    } elseif ($saveValuebeforeValid[1] == 2) {
        $url = "partnerwithdrawalController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $url = "partnerwithdrawalController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى للمسحوبات";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}
//tempdelete
elseif ($do == "tempdelete") {
    include_once("../public/authentication.php");

    $partnerwithdrawalId = $_GET['partnerwithdrawalid'];

    // here the function that do the action
    $saveValuebeforeValid = tempdelete($partnerwithdrawalId);
    if ($saveValuebeforeValid[1] == 1) {
        header("location:?do=sucess");
    } elseif ($saveValuebeforeValid[1] == 2) {
        $url = "partnerwithdrawalController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}
//edit  transfer
elseif ($do == "editprint") {
    include_once("../public/authentication.php");

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

    $smarty->display("partnerwithdrawalview/editprint.html");
    $smarty->assign("customPrint", 1);
}
//edit  transfer
elseif ($do == "edit") {
    include_once("../public/authentication.php");

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

    $partnerData = loadPartner();
    $smarty->assign("partnerData", $partnerData);

    //$saveData = loadSaveBySesssionId();
    $saveData = $mySaveRecord->load($loadData->saveid);
    $smarty->assign("saveData", $saveData);

    $bankAccount = $accountExtDAO->loadBankAccount($loadData->bankaccountid);
    $smarty->assign("bankAccount", $bankAccount);

    $smarty->display("partnerwithdrawalview/edit.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    //update();
    //here the function that do the action
    $saveValuebeforeValid = update();
    if ($saveValuebeforeValid == 1) {
        header("location:?do=sucess");
    } else {
        $url = "partnerwithdrawalController.php";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى للمسحوبات";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
}
//edit  update
elseif ($do == "executeOperation") {
    include_once("../public/authentication.php");

    executeOperation();

    $partnerData = loadPartner();
    $smarty->assign("partnerData", $partnerData);

    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    showAll();

    $smarty->display("partnerwithdrawalview/show.html");
    $smarty->assign("customCheck", 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);
$smarty->assign("customPartnerwithdrawal", 1);
$smarty->assign("customAssets", 1);

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

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

//select all Partner data
function loadPartner() {
    //to use the variable out side the funcion
    global $myPartnerRecord;

    //load all Partner data
    $partnerData = $myPartnerRecord->queryByConditions(0);

    return $partnerData;
}

//load save data By SaveId
function loadSaveBySesssionId() {
    global $mySaveRecord;


    //load  save data
    $saveData = $mySaveRecord->load($_SESSION['saveid']);


    return $saveData;
}

//load save data
function loadSave() {
    global $mySaveRecord;

    //load  save data
    $saveData = $mySaveRecord->queryByConditions(0);

    return $saveData;
}

// add in Partnerwithdrawal tbl
function add() {
    //to use the variable out side the funcion
    global $myPartnerwithdrawal;
    global $myPartnerwithdrawalRecord;

    //save
    global $mySave;
    global $mySaveRecord;
    //bank
    global $bank;
    global $bankDAO;
    global $accountDAO;

    //partner
    global $myPartner;
    global $myPartnerRecord;

    //tree
    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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



    global $userData;


    $partnerId = $_POST['partnerid'];
    $savecurrentValue = $_POST['savecurrentvalue'];
    $partnerwithdrawalValue = $_POST['partnerwithdrawalvalue'];
    $partenrwithdrawaltype = $_POST['partenrwithdrawaltype'];
    $comment = $_POST['comment'];
    $paymethod = (int) $_POST["paymethod"];
    if ($userData->searchinonesave == 0) {
        $saveid = (int) $_POST["saveid"];
    } else {
        $saveid = (int) $_SESSION['saveid'];
    }



    $saveValuebeforeValid = 1;
    /////////////////check save value before withdrawal//////////////////////

    if ($paymethod == 0 && $partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
        //get save value
        //$saveValueBefore = getSaveValueBefore($_SESSION['saveid']);
        $saveValueBefore = getSaveValueBefore($saveid);


        $saveValueafterValid = $saveValueBefore - $partnerwithdrawalValue;
        if ($saveValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
            return $saveValuebeforeValid;
        }
    }



    $dataPartner = $myPartnerRecord->load($partnerId);

    //add in Partnerwithdrawal tbl
    $myPartnerwithdrawal->conditions = 0;
    $myPartnerwithdrawal->partnerid = $partnerId;
    $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
    $myPartnerwithdrawal->partenrwithdrawaltype = $partenrwithdrawaltype;
    $myPartnerwithdrawal->partnerwithdrawalvalue = $partnerwithdrawalValue;
    $myPartnerwithdrawal->partnerbefore = $dataPartner->partnermoney;
    $myPartnerwithdrawal->userid = $_SESSION["userid"];
    $myPartnerwithdrawal->comment = $comment;
    $myPartnerwithdrawal->dailyentryid = 0;
    if ($partenrwithdrawaltype == 1) {
        $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney - $partnerwithdrawalValue;
        R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerId . "' ");
    } else {
        $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney + $partnerwithdrawalValue;
        R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerId . "' ");
    }


    if ($paymethod == 1) {
        ##bank
        $bankid = $_POST["bankid"];
        $bankaccountid = $_POST["bankaccountid"];
        $checkNo = $_POST["checkNo"];
        $myPartnerwithdrawal->saveid = 0;
        $myPartnerwithdrawal->bankid = $bankid;
        $myPartnerwithdrawal->bankaccountid = $bankaccountid;
        $myPartnerwithdrawal->checknum = $checkNo;
    } else {
        ##save
        $myPartnerwithdrawal->saveid = $saveid;
        $myPartnerwithdrawal->bankid = 0;
        $myPartnerwithdrawal->bankaccountid = 0;
        $myPartnerwithdrawal->checknum = '';
    }

    $partnerwithdrawalId = $myPartnerwithdrawalRecord->insert($myPartnerwithdrawal);

    echo $partenrwithdrawaltype;

    ///affect
    $treeIdBankAccount = 0;
    if ($paymethod == 0) {
        if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
            //get saveFromValue before and saveFromValue after mins transfermoneyValue
            $saveData = getSaveValueAndMins($saveid, $partnerwithdrawalValue);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

            //update saveFrom value after add transfer
            updateSave($saveId, $saveValueafter);

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 1, $saveId, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
        } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
            //get saveFromValue before and saveFromValue after mins transfermoneyValue
            $saveData = getSaveValueAndPlus($saveid, $partnerwithdrawalValue);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];


            //update saveFrom value after add transfer
            updateSave($saveId, $saveValueafter);

            //insert into savedaily tbl from savefrom
            insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 0, $saveId, "اضافة ايداع شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
        }
    } elseif ($paymethod == 1) {
        $dataBankAccount = $accountDAO->load($bankaccountid);
        //tree account
        $treeIdBankAccount = $dataBankAccount->treeId;




        $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;



        if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
            //mins transfermoneyValue
            //decrease account value and write in history
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $partnerwithdrawalValue;
            $accountDAO->update($dataBankAccount);
            insertAccountmovement($accValOld, $partnerwithdrawalValue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
        } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
            //plus transfermoneyValue
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $partnerwithdrawalValue;
            $accountDAO->update($dataBankAccount);
            insertAccountmovement($accValOld, $partnerwithdrawalValue, 0, $dataBankAccount->accountbeginingbalance, "اضافة ايداع شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
        }
    }


    /// daily entry
    //////////////// start partner data

    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $partnerwithdrawalValue;

    $dataPartner = $myPartnerRecord->load($partnerId);

    $idTreePartner = $dataPartner->treeId;





    //end  partner data
    //
    //////////////// start save data

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $partnerwithdrawalValue;
    //save session
    //$saveid = $_SESSION['saveid'];
    $saveid = $saveid;
    $dataSave = $mySaveRecord->load($saveid);

    $idTreeSave = $dataSave->treeId;
    //
    $treeIdBankAccount = $treeIdBankAccount;


    //end  partner data

    if ($partenrwithdrawaltype == 0) {

        $dailyEntry->entryComment = 'تم عمل ايداع للشريك ' . $dataPartner->partnername;
        $dailyEntryCreditor->accountstreeid = $idTreePartner;
        $dailyEntryDebtor->accountstreeid = $idTreeSave;
        if ($paymethod == 1) {
            $dailyEntryDebtor->accountstreeid = $treeIdBankAccount;
        }
    } else {
        $dailyEntry->entryComment = 'تم عمل سحب للشريك ' . $dataPartner->partnername;

        $dailyEntryCreditor->accountstreeid = $idTreeSave;
        if ($paymethod == 1) {
            $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;
        }
        $dailyEntryDebtor->accountstreeid = $idTreePartner;
    }
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

    $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $partnerwithdrawalId, 'partnerwithdrawalController.php?do=show&id=' . $partnerwithdrawalId);
    $did = $returnedData[1];

    $rowData = $myPartnerwithdrawalRecord->load($partnerwithdrawalId);


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

    $myPartnerwithdrawalRecord->update($rowData);

//// load Ras L Maaal

    $rasLMalData = $accountsTreeDAO->load(121);

    if ($rasLMalData->theValue < $partnerwithdrawalValue && $partenrwithdrawaltype == 0) {
        $accountsTree = $accountsTreeDAO->load($idTreePartner);
        $accountsTree->theValue += $partnerwithdrawalValue;

        editTreeElement($accountsTree);
    } elseif ($rasLMalData->theValue < $partnerwithdrawalValue && $partenrwithdrawaltype == 1) {
        $accountsTree = $accountsTreeDAO->load($idTreePartner);
        $accountsTree->theValue += (abs($partnerwithdrawalValue) * -1);

        editTreeElement($accountsTree);
    }

    return $saveValuebeforeValid;
}

//show
function showAll() {
    global $myPartnerwithdrawalEx;
    global $smarty;

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithOrder();
    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

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

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithDate($startDate, $endDate);

    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

function showByOneDate($condition, $date) {
    global $myPartnerwithdrawalEx;
    global $smarty;

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithOneDateOnly($condition, $date);

    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

//show
function showByPartnerId($partnerid) {
    //to use the variable out side the funcion
    global $myPartnerwithdrawalEx;
    global $smarty;

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithPartnerId($partnerid);

    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

//show
function showBySaveId($saveiid) {
    //to use the variable out side the funcion
    global $myPartnerwithdrawalEx;
    global $smarty;

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithSaveId($saveiid);
    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

function showByPartenrwithdrawalType($partnertype) {
    //to use the variable out side the funcion
    global $myPartnerwithdrawalEx;
    global $smarty;

    $partnerwithdrawalData = $myPartnerwithdrawalEx->queryWithPartnerType($partnertype);
    $total = 0;
    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        $total = $total + $mypartnerwithdrawalData->partnerwithdrawalvalue;
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

function tempdelete($partnerwithdrawalId) {
    //to use the variable out side the funcion
    global $myPartnerwithdrawal;
    global $myPartnerwithdrawalRecord;
    global $myPartnerwithdrawalEx;
    global $myPartnerRecord;
    global $accountDAO;
    global $accountsTreeDAO;
    $dailyentryid = $_GET['action'];
    try {

        //get partnerwithdrawaldate by partnerwithdrawalId
        $partnerwithdrawalData = $myPartnerwithdrawalRecord->load($partnerwithdrawalId);
        $partnerwithdrawalValue = $partnerwithdrawalData->partnerwithdrawalvalue;
        $partenrwithdrawaltype = $partnerwithdrawalData->partenrwithdrawaltype;
        $saveId = $partnerwithdrawalData->saveid;
        $bankaccountid = $partnerwithdrawalData->bankaccountid;
        if ($saveId > 0) {
            $paymethod = 0;
        } else {
            $paymethod = 1;
        }


        if ($partnerwithdrawalData->conditions == 0) {
            $saveValuebeforeValid = 1;

            $myPartnerwithdrawal->conditions = 1;
            $myPartnerwithdrawal->userid = $_SESSION['userid'];
            $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
            $myPartnerwithdrawal->partnerwithdrawalid = $partnerwithdrawalId;
            $dataPartner = $myPartnerRecord->load($partnerwithdrawalData->partnerid);
            $myPartnerwithdrawal->partnerbefore = $dataPartner->partnermoney;
            if ($partnerwithdrawalData->partenrwithdrawaltype == 1) {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney + $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerwithdrawalData->partnerid . "' ");
            } else {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney - $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerwithdrawalData->partnerid . "' ");
            }

            $myPartnerwithdrawalEx->updateConditions($myPartnerwithdrawal);
            if ($paymethod == 0) {
                if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {

                    //get saveValue before and saveValue after Plus partnerwithdrawalValue
                    $saveData = getSaveValueAndPlus($saveId, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update saveFrom value after transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from saveFrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 0, $saveId, "حذف مسحوبات شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {

                    //get saveValue before and saveValue after Plus partnerwithdrawalValue
                    $saveData = getSaveValueAndMins($saveId, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update saveFrom value after transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from saveFrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 1, $saveId, "حذف ايداع شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                }
            } elseif ($paymethod == 1) {
                $dataBankAccount = $accountDAO->load($bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;

                if ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
                    //mins transfermoneyValue
                    //decrease account value and write in history
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 1, $dataBankAccount->accountbeginingbalance, "حذف ايداع شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                    //plus transfermoneyValue
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 0, $dataBankAccount->accountbeginingbalance, "حذف مسحوبات شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                }
            }
        }
        reverseEntryWithItsID($dailyentryid);
        $note = "success";
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف المسحوبات";
        $saveValuebeforeValid = 2;
    }


    return array($note, $saveValuebeforeValid);
}

function returndelete($partnerwithdrawalId) {

    //to use the variable out side the funcion
    global $myPartnerwithdrawal;
    global $myPartnerwithdrawalRecord;
    global $myPartnerwithdrawalEx;

    global $myPartner;
    global $myPartnerEx;
    global $myPartnerRecord;

    global $accountsTreeDAO;
    global $accountsTree;


    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

    //save
    global $mySave;
    global $mySaveRecord;

    //bank
    global $bank;
    global $bankDAO;
    global $accountDAO;

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

    $dailyentryid = $_GET['action'];


    $singlePartnerwithdrawal = $myPartnerwithdrawalEx->loadPartnerwithdrawalById2($partnerwithdrawalId);

    try {
        if ($singlePartnerwithdrawal->conditions == 1) {

            //get partnerwithdrawaldate by partnerwithdrawalId
            $partnerwithdrawalData = $myPartnerwithdrawalRecord->load($partnerwithdrawalId);
            $partnerwithdrawalValue = $partnerwithdrawalData->partnerwithdrawalvalue;
            $partenrwithdrawaltype = $partnerwithdrawalData->partenrwithdrawaltype;
            $saveId = $saveid = $partnerwithdrawalData->saveid;
            $bankaccountid = $partnerwithdrawalData->bankaccountid;
            if ($saveId > 0) {
                $paymethod = 0;
            } else {
                $paymethod = 1;
            }



            $saveValuebeforeValid = 1;
            /////////////////check save value before withdrawal//////////////////////

            if ($paymethod == 0 && $partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                //get save value
                $saveValueBefore = getSaveValueBefore($saveid);


                $saveValueafterValid = $saveValueBefore - $partnerwithdrawalValue;
                if ($saveValueafterValid >= 0) {
                    $saveValuebeforeValid = 1;
                } else {
                    $saveValuebeforeValid = 0;
                    return $saveValuebeforeValid;
                }
            }



            $myPartnerwithdrawal->conditions = 0;
            $myPartnerwithdrawal->userid = $_SESSION['userid'];
            $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
            $myPartnerwithdrawal->partnerwithdrawalid = $partnerwithdrawalId;

            $myPartnerwithdrawalEx->updateConditions($myPartnerwithdrawal);



            ///affect
            $treeIdBankAccount = 0;
            if ($paymethod == 0) {
                if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                    //get saveFromValue before and saveFromValue after mins transfermoneyValue
                    $saveData = getSaveValueAndMins($saveid, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 1, $saveId, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
                    //get saveFromValue before and saveFromValue after mins transfermoneyValue
                    $saveData = getSaveValueAndPlus($saveid, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];


                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 0, $saveId, "اضافة ايداع شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                }
            } elseif ($paymethod == 1) {
                $dataBankAccount = $accountDAO->load($bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;




                $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;



                if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                    //mins transfermoneyValue
                    //decrease account value and write in history
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
                    //plus transfermoneyValue
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 0, $dataBankAccount->accountbeginingbalance, "اضافة ايداع شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                }
            }
            //////////////////////////////////////////
            /// daily entry
            $loadDailyEntry = $dailyEntryDAO->load($dailyentryid);

            $dailyEntry->dComment = 'هذا هوا ال Id للشريك' . $partnerId;

            //////////////// start partner data

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $loadDailyEntry->totalcreditor;

            $dataPartnerwithdraw = $myPartnerwithdrawalRecord->load($partnerwithdrawalId);
            $datapartner = $myPartnerRecord->load($dataPartnerwithdraw->partnerid);
            $idTreePartner = $datapartner->treeId;
            $dailyEntryDebtor->accountstreeid = $idTreePartner;



            //end  partner data
            //
            //////////////// start save data

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $partnerwithdrawalValue;
            //save session
            //$saveid = $_SESSION['saveid'];
            $saveid = $saveid;
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            //
            $treeIdBankAccount = $treeIdBankAccount;


            //end  partner data

            if ($partenrwithdrawaltype == 0) {

                //$dailyEntry->entryComment = 'تم عمل ايداع للشريك ' . $dataPartner->partnername;
                $dailyEntryCreditor->accountstreeid = $idTreePartner;
                $dailyEntryDebtor->accountstreeid = $idTreeSave;
                if ($paymethod == 1) {
                    $dailyEntryDebtor->accountstreeid = $treeIdBankAccount;
                }
            } else {
                //$dailyEntry->entryComment = 'تم عمل سحب للشريك ' . $dataPartner->partnername;

                $dailyEntryCreditor->accountstreeid = $idTreeSave;
                if ($paymethod == 1) {
                    $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;
                }
                $dailyEntryDebtor->accountstreeid = $idTreePartner;
            }


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


            insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $partnerwithdrawalId, 'partnerwithdrawalController.php?do=show&id=' . $partnerwithdrawalId);
        }
        $note = "success";
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء اعادة المسحوبات";
        $saveValuebeforeValid = 2;
    }


    return array($note, $saveValuebeforeValid);
}

//edit from Partnerwithdrawal tbl
function editprint() {
    //to use the variable out side the funcion
    global $myPartnerwithdrawalEx;

    $partnerwithdrawalId = $_GET['id'];

    $loadData = $myPartnerwithdrawalEx->loadPartnerwithdrawalById2($partnerwithdrawalId);

    return $loadData;
}

//edit from Partnerwithdrawal tbl
function edit() {
    global $myPartnerwithdrawalEx;

    $partnerwithdrawalId = $_GET['partnerwithdrawalid'];

    $loadData = $myPartnerwithdrawalEx->loadPartnerwithdrawalById2($partnerwithdrawalId);
    return $loadData;
}

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

    $outputString = "";

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

    $choosedItemArr = $_POST['choosedItem'];



    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $partnerwithdrawalId) {

            if ($operationType == '1') {
                //tempdelete
                $note = tempdelete($partnerwithdrawalId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString = "تمت العملية بنجاح";
                }
            } elseif ($operationType == "2") {

                //returndelete
                $note = returndelete($partnerwithdrawalId);
                if ($note[0] != "success") {
                    $outputString .= $note[0] . "<br/>";
                } else {
                    $outputString = "تمت العملية بنجاح";
                }
            }
        }

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

// update data in Partnerwithdrawal tbl
function update() {
    //to use the variable out side the funcion
    global $myPartnerwithdrawal;
    global $myPartnerwithdrawalRecord;
    global $myPartnerwithdrawalEx;

    //save
    global $mySave;
    global $mySaveRecord;
    //bank
    global $bank;
    global $bankDAO;
    global $accountDAO;
    //partner
    global $myPartner;
    global $myPartnerRecord;

    //tree
    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    global $userData;

    $partnerId = $_POST['partnerid'];
    $partnerwithdrawalValue = $_POST['partnerwithdrawalvalue'];
    $partnerwithdrawalId = $_POST['partnerwithdrawalid'];
    $partnerwithdrawalDate = $_POST['partnerwithdrawaldate'];
    $partenrwithdrawaltype = $_POST['partenrwithdrawaltype'];
    $conditions = $_POST['conditions'];
    //$saveId = $_POST['saveid'];
    $comment = $_POST['comment'];
    $partnertype = $_POST['partnertype'];
    $partnervalue = $_POST['partnervalue'];
    $dailyentryid = $_POST['dailyentryid'];

    $paymethod = (int) $_POST["paymethod"];
    if ($userData->searchinonesave == 0) {
        $saveid = (int) $_POST["saveid"];
    } else {
        $saveid = (int) $_SESSION['saveid'];
    }
    //  print_r('aaaaaaaaaaaaaaaaaaaaa' . $dailyentryid);

    $myPartnerwithdrawal = $myPartnerwithdrawalRecord->load($partnerwithdrawalId);
    $bankid = $myPartnerwithdrawal->bankid;
    $bankaccountid = $myPartnerwithdrawal->bankaccountid;
    $partnervalueOld = $myPartnerwithdrawal->partnerwithdrawalvalue;
    $saveValuebeforeValid = 1;
    /////////////////check save value before withdrawal//////////////////////

    if ($paymethod == 0 && $partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
        //get save value
        //$saveValueBefore = getSaveValueBefore($_SESSION['saveid']);
        $saveValueBefore = getSaveValueBefore($saveid);


        $saveValueafterValid = $saveValueBefore - $partnerwithdrawalValue;
        if ($saveValueafterValid >= 0) {
            $saveValuebeforeValid = 1;
        } else {
            $saveValuebeforeValid = 0;
            return $saveValuebeforeValid;
        }
    }
    if ($paymethod == 0) {
        if ($partnertype == 0 && $partnervalueOld > 0) {
            $saveData = getSaveValueAndMins($saveid, $partnervalueOld);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];


            //update saveFrom value after add transfer
            updateSave($saveId, $saveValueafter);
            insertSavedaily($saveValuebefore, $partnervalueOld, 1, $saveId, "تعديل شريك", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
        } elseif ($partnertype == 1 && $partnervalueOld > 0) {
            $saveData = getSaveValueAndPlus($saveid, $partnervalueOld);
            $saveId = $saveData[0];
            $saveValuebefore = $saveData[1];
            $saveValueafter = $saveData[2];

            //update saveFrom value after add transfer
            updateSave($saveId, $saveValueafter);
            insertSavedaily($saveValuebefore, $partnervalueOld, 0, $saveId, "تعديل شريك", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
        }
    } elseif ($paymethod == 1) {
        $dataBankAccount = $accountDAO->load($bankaccountid);
        //tree account
        $treeIdBankAccount = $dataBankAccount->treeId;

        if ($partnertype == 0 && $partnervalueOld > 0) {
            //mins transfermoneyValue
            //decrease account value and write in history
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $partnervalueOld;
            $accountDAO->update($dataBankAccount);
            insertAccountmovement($accValOld, $partnervalueOld, 1, $dataBankAccount->accountbeginingbalance, "تعديل شريك", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
        } elseif ($partnertype == 1 && $partnervalueOld > 0) {
            //plus transfermoneyValue
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $partnervalueOld;
            $accountDAO->update($dataBankAccount);
            insertAccountmovement($accValOld, $partnervalueOld, 0, $dataBankAccount->accountbeginingbalance, "تعديل شريك", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
        }
    }
    try {
        if (isset($partnerId) && $partnerId > 0) {




            if ($myPartnerwithdrawal->partenrwithdrawaltype == 1) {
                // $myPartnerwithdrawal->partnerbefore = $myPartnerwithdrawal->partnerbefore + $myPartnerwithdrawal->partnerwithdrawalvalue;
                $myPartnerwithdrawal->partnerafter = $myPartnerwithdrawal->partnerafter + $myPartnerwithdrawal->partnerwithdrawalvalue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $myPartnerwithdrawal->partnerwithdrawalvalue . "  WHERE partnerid = '" . $myPartnerwithdrawal->partnerid . "' ");
            } else {
                // $myPartnerwithdrawal->partnerbefore = $myPartnerwithdrawal->partnerbefore - $myPartnerwithdrawal->partnerwithdrawalvalue;
                $myPartnerwithdrawal->partnerafter = $myPartnerwithdrawal->partnerafter - $myPartnerwithdrawal->partnerwithdrawalvalue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $myPartnerwithdrawal->partnerwithdrawalvalue . "  WHERE partnerid = '" . $myPartnerwithdrawal->partnerid . "' ");
            }
            $myPartnerwithdrawal->conditions = 1;
            $myPartnerwithdrawal->userid = $_SESSION['userid'];
            $myPartnerwithdrawal->partnerwithdrawaldate = date("Y-m-d");
            $myPartnerwithdrawal->partnerwithdrawalid = $partnerwithdrawalId;

            $flag = reverseEntryWithItsID($myPartnerwithdrawal->dailyentryid);
            $myPartnerwithdrawalEx->updateConditions($myPartnerwithdrawal);

            $dataPartner = $myPartnerRecord->load($partnerId);





            //insert new partnerwithdrawal
            //save and bank data coming with load
            $myPartnerwithdrawal->conditions = $conditions;
            $myPartnerwithdrawal->partnerid = $partnerId;
            $myPartnerwithdrawal->partnerwithdrawaldate = $partnerwithdrawalDate;
            $myPartnerwithdrawal->partnerwithdrawalvalue = $partnerwithdrawalValue;
            $myPartnerwithdrawal->partnerbefore = $dataPartner->partnermoney;
            $myPartnerwithdrawal->saveid = $saveid;
            $myPartnerwithdrawal->userid = $_SESSION["userid"];
            $myPartnerwithdrawal->partenrwithdrawaltype = $partenrwithdrawaltype;
            $myPartnerwithdrawal->comment = $comment;
            $myPartnerwithdrawal->dailyentryid = $dailyentryid;
            if ($partenrwithdrawaltype == 1) {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney - $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney - " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerId . "' ");
            } else {
                $myPartnerwithdrawal->partnerafter = $dataPartner->partnermoney + $partnerwithdrawalValue;
                R::exec("UPDATE `partner` SET `partnermoney`= partnermoney + " . $partnerwithdrawalValue . "  WHERE partnerid = '" . $partnerId . "' ");
            }
            $partnerwithdrawalId = $myPartnerwithdrawalRecord->insert($myPartnerwithdrawal);

            ///affect
            $treeIdBankAccount = 0;
            if ($paymethod == 0) {
                if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                    //get saveFromValue before and saveFromValue after mins transfermoneyValue
                    $saveData = getSaveValueAndMins($saveid, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];

                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 1, $saveId, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
                    //get saveFromValue before and saveFromValue after mins transfermoneyValue
                    $saveData = getSaveValueAndPlus($saveid, $partnerwithdrawalValue);
                    $saveId = $saveData[0];
                    $saveValuebefore = $saveData[1];
                    $saveValueafter = $saveData[2];


                    //update saveFrom value after add transfer
                    updateSave($saveId, $saveValueafter);

                    //insert into savedaily tbl from savefrom
                    insertSavedaily($saveValuebefore, $partnerwithdrawalValue, 0, $saveId, "اضافة ايداع شركاء", $partnerwithdrawalId, $saveValueafter, "partnerwithdrawalController.php");
                }
            } elseif ($paymethod == 1) {
                $dataBankAccount = $accountDAO->load($bankaccountid);
                //tree account
                $treeIdBankAccount = $dataBankAccount->treeId;




                $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;



                if ($partenrwithdrawaltype == 1 && $partnerwithdrawalValue > 0) {
                    //mins transfermoneyValue
                    //decrease account value and write in history
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 1, $dataBankAccount->accountbeginingbalance, "اضافة مسحوبات شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                } elseif ($partenrwithdrawaltype == 0 && $partnerwithdrawalValue > 0) {
                    //plus transfermoneyValue
                    $accValOld = $dataBankAccount->accountbeginingbalance;
                    $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $partnerwithdrawalValue;
                    $accountDAO->update($dataBankAccount);
                    insertAccountmovement($accValOld, $partnerwithdrawalValue, 0, $dataBankAccount->accountbeginingbalance, "اضافة ايداع شركاء", $partnerwithdrawalId, $dataBankAccount->accountid, $dataBankAccount->bankid, "partnerwithdrawalController.php");
                }
            }




            $dailyEntry = new stdClass();
            $dailyEntry->entryComment = 'تم تعديل مسحوبات/ايداعات الشريك';

            //////////////// start partner data

            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $partnerwithdrawalValue;

            $dataPartner = $myPartnerRecord->load($partnerId);

            $idTreePartner = $dataPartner->treeId;




            //end  partner data
            //
            //////////////// start save data

            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $partnerwithdrawalValue;
            //save session
            //$saveid = $_SESSION['saveid'];
            $saveid = $saveid;
            $dataSave = $mySaveRecord->load($saveid);

            $idTreeSave = $dataSave->treeId;
            //
            $treeIdBankAccount = $treeIdBankAccount;


            //end  partner data

            if ($partenrwithdrawaltype == 0) {
                $dailyEntryCreditor->accountstreeid = $idTreePartner;
                $dailyEntryDebtor->accountstreeid = $idTreeSave;
                if ($paymethod == 1) {
                    $dailyEntryDebtor->accountstreeid = $treeIdBankAccount;
                }
            } else {
                $dailyEntryCreditor->accountstreeid = $idTreeSave;
                if ($paymethod == 1) {
                    $dailyEntryCreditor->accountstreeid = $treeIdBankAccount;
                }
                $dailyEntryDebtor->accountstreeid = $idTreePartner;
            }
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $partnerwithdrawalId, 'partnerwithdrawalController.php?do=show&id=' . $partnerwithdrawalId);
            $did = $returnedData[1];

            $myPartnerwithdrawal->dailyentryid = $did;
            $myPartnerwithdrawalRecord->update($myPartnerwithdrawal);
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء اعادة المسحوبات";
        $saveValuebeforeValid = 2;
    }


    return $saveValuebeforeValid;
}

// 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 $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($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 $mySaveEx;

    $saveData = $mySaveEx->loadForUpdateEx($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);
}

// insertAccountmovement of bank
function insertAccountmovement($accountbefore, $accountamount, $accountmovementtype, $accountafter, $processname, $accountmovementmodelid, $accountid, $bankid, $tablename) {

    //to use the variable out side the funcion
    global $accountMove;
    global $accountMoveDAO;


    //insert in Accountmovement tbl
    $accountMove->accountid = $accountid;
    $accountMove->accountmovementafter = $accountafter;
    $accountMove->accountmovementamount = $accountamount;
    $accountMove->accountmovementbefore = $accountbefore;
    $accountMove->accountmovementdate = date("Y-m-d");
    $accountMove->accountmovementmodelid = $accountmovementmodelid;
    $accountMove->accountmovementtype = $accountmovementtype;
    $accountMove->bankid = $bankid;
    $accountMove->processname = $processname;
    $accountMove->tablename = $tablename;
    $accountMove->userid = $_SESSION['userid'];

    $accountMoveDAO->insert($accountMove);
}

function search($saveId, $partnerId, $partenrwithdrawaltype, $startDate, $endDate) {
    global $myPartnerwithdrawalEx;
    global $mySaveRecord;
    global $myPartnerwithdrawalRecord;
    global $myPartnerRecord;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($saveId) && $saveId != '-1') {
        $mysavedata = $mySaveRecord->load($saveId);
        $message = "   مسحوبات الشركاء من الخزنه   " . $mysavedata->savename;
        $smarty->assign('message', $message);

        //$sumValue=sumCreditById($saveid);
        //$queryString .= 'partnerwithdrawal.saveid = '.$saveId.' AND';
        $queryString .= ' partnerwithdrawal.saveid = ' . $saveId . ' AND';
    }

    if (isset($partnerId) && $partnerId != '-1') {
        $mysavedataprocess = $myPartnerRecord->load($partnerId);
        $message = "  مسحوبات الشريك" . $mysavedataprocess->partnername;
        $smarty->assign('message', $message);


        $queryString .= ' partnerwithdrawal.partnerid = ' . $partnerId . ' AND';
    }

    if (isset($partenrwithdrawaltype)) {
        //$mysavedataprocess=$myPartnerRecord->load($partnerId);
        //$message="تقرير يوميه  عمليه  للشريك ".$mysavedataprocess->partnername;
        //$smarty->assign('message',$message);

        if ($partenrwithdrawaltype == 0 || $partenrwithdrawaltype == 1) {
            $queryString .= ' partnerwithdrawal.partenrwithdrawaltype = ' . $partenrwithdrawaltype . ' AND';
        }
    }
    if (!empty($startDate) && !empty($endDate)) {


        $message = " تقرير مسحوبات الشريك من تاريخ " . $startDate . "  الى تاريخ" . $endDate;
        $smarty->assign('message', $message);



        //  $queryString .= 'partnerwithdrawal.partnerwithdrawaldate "'.$startDate.'" AND "'.$endDate.'" AND';
        $queryString .= ' partnerwithdrawal.partnerwithdrawaldate >= "' . $startDate . '" AND partnerwithdrawal.partnerwithdrawaldate <= "' . $endDate . '" AND';
        //$sumValue=sumCredit();
        //print_r($sumValue);
    }

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

    $partnerwithdrawalData = $myPartnerwithdrawalEx->search($queryString);

    $total = 0;

    foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
        //get sum for today
        if ($mypartnerwithdrawalData->partenrwithdrawaltype == 0) {//plus
            if ($mypartnerwithdrawalData->partnerwithdrawalvalue > 0) {
                $total1 += $mypartnerwithdrawalData->partnerwithdrawalvalue;
                $total = round(($total1 * 2)) / 2;
            } else {
                $total1 -= $mypartnerwithdrawalData->partnerwithdrawalvalue;
                $total = round(($total1 * 2)) / 2;
            }
        } else if ($mypartnerwithdrawalData->partenrwithdrawaltype == 1) {//minus
            if ($mypartnerwithdrawalData->partnerwithdrawalvalue > 0) {
                $total1 -= $mypartnerwithdrawalData->partnerwithdrawalvalue;
                $total = round(($total1 * 2)) / 2;
            } else {
                $total1 += $mypartnerwithdrawalData->partnerwithdrawalvalue;
                $total = round(($total1 * 2)) / 2;
            }
        }
    }
    $smarty->assign('total', $total);
    $smarty->assign('partnerwithdrawalData', $partnerwithdrawalData);
}

?>