<?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
// GOES HERE ....................
include("../public/include_dao.php");

//Transferbtweenbankaccount
require_once('../models/dao/TransferbtweenbankaccountDAO.class.php');
require_once('../models/dto/Transferbtweenbankaccount.class.php');
require_once('../models/mysql/TransferbtweenbankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/TransferbtweenbankaccountMySqlExtDAO.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');

//Breadcrumb
require_once("../library/breadcrumb.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

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


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


//here goes the instances and general variables
//Transferbtweenbankaccount
$transferBtweenBankAccounts = new Transferbtweenbankaccount();
$transferBtweenBankAccountsDAO = new TransferbtweenbankaccountMySqlDAO();
$transferBtweenBankAccountsEX = new TransferbtweenbankaccountMySqlExtDAO();

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

//here goes the instances and general variables
//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountRecord = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();

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

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


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


//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

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


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

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

    // here the function that do the action
    add();
    header("location:?do=sucess");
} elseif ($do == "show") {

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



    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    if ((!isset($startDate) || $startDate != "") && (!isset($endDate) || $endDate != "")) {
        $startDate = $endDate = date('Y-m-d');
    }



    $message = '';
    $queryString = " and transferbtweenbankaccount.conditions = 0 ";
    if (isset($startDate) && $startDate != "") {
        $message = " عرض تحويلات الخزن من:" . $startDate . '';
        $queryString .= " and date(transferbtweenbankaccount.transferdate) >= '" . $startDate . "' ";
    }
    if (isset($endDate) && $endDate != "") {
        $message .= " عرض تحويلات الخزن الى:" . $endDate . '';
        $queryString .= " and date(transferbtweenbankaccount.transferdate) <= '" . $endDate . "' ";
    }

    $transferData = $transferBtweenBankAccountsEX->queryAllEX($queryString);

    $smarty->assign('message', $message);
    $smarty->assign('transferData', $transferData);


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

    $smarty->display("transferbtweenbankaccountsview/show.html");

    $smarty->assign("customCheck", 1);
}

//edit  transfer
elseif ($do == "details") {

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

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


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

    $smarty->assign("customPrint", 1);
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        $id = $_GET['id'];
        delete($id);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}
//edit  transfer
elseif ($do == "edit") {

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

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

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

//    $accountFrom = $myBankaccountRecord->load($loadData->accountidfrom);
//    $smarty->assign("accountFrom", $accountFrom);
//    $accountTo = $myBankaccountRecord->load($loadData->accountidto);
//    $smarty->assign("accountTo", $accountTo);

    $smarty->display("transferbtweenbankaccountsview/edit.html");
} elseif ($do == "update") {

    include_once("../public/authentication.php");
    try {
        $id = $_POST['id'];
        delete($id);
        add();
        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");
}



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

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

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

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

// add in Transfermoney tbl
function add() {

    //to use the variable out side the funcion
    global $transferBtweenBankAccounts;
    global $transferBtweenBankAccountsDAO;
    global $myBankaccountRecord;


    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    //Transaction
    $transactions = new Transaction();

    $ddlBankfrom = (int) $_POST['ddlBankfrom'];
    $accountidfrom = (int) $_POST['accountidfrom'];
    $ddlBankto = (int) $_POST['ddlBankto'];
    $accountidto = (int) $_POST['accountidto'];
    $transfervalue = (float) $_POST['transfervalue'];
    $comment = $_POST['comment'];



    //add in Transfermoney tbl
    $transferBtweenBankAccounts->bankidfrom = $ddlBankfrom;
    $transferBtweenBankAccounts->bankidto = $ddlBankto;
    $transferBtweenBankAccounts->accountidfrom = $accountidfrom;
    $transferBtweenBankAccounts->accountidto = $accountidto;
    $transferBtweenBankAccounts->transfervalue = $transfervalue;
    $transferBtweenBankAccounts->transferdate = date("Y-m-d H:i:s");
    $transferBtweenBankAccounts->userid = $_SESSION["userid"];
    $transferBtweenBankAccounts->conditions = 0;
    $transferBtweenBankAccounts->dailyentryid = 0;
    $transferBtweenBankAccounts->comment = $comment;


    try {
        if ($transfervalue > 0) {
            $transferId = $transferBtweenBankAccountsDAO->insert($transferBtweenBankAccounts);
            /////////////1- bank from
            $dataBankAccount = $myBankaccountRecord->load($accountidfrom);
            //tree account
            $treeIdBankAccount = $dataBankAccount->treeId;
            $fromTreeId = $treeIdBankAccount;

            //decrease account value and write in history
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $transfervalue;
            $myBankaccountRecord->update($dataBankAccount);
            insertAccountmovement($accValOld, $transfervalue, 1, $dataBankAccount->accountbeginingbalance, "تحويل بين البنوك", $transferId, $dataBankAccount->accountid, $dataBankAccount->bankid, "transferBtweenBankAccounts.php");

            /////////////2- bank to
            $dataBankAccount = $myBankaccountRecord->load($accountidto);
            //tree account
            $treeIdBankAccount = $dataBankAccount->treeId;
            $toTreeId = $treeIdBankAccount;

            //decrease account value and write in history
            $accValOld = $dataBankAccount->accountbeginingbalance;
            $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $transfervalue;
            $myBankaccountRecord->update($dataBankAccount);
            insertAccountmovement($accValOld, $transfervalue, 0, $dataBankAccount->accountbeginingbalance, "تحويل بين البنوك", $transferId, $dataBankAccount->accountid, $dataBankAccount->bankid, "transferBtweenBankAccounts.php");

            //////////////////
            /////////// daily entry
            $dailyEntry->entryComment = 'اضافة تحويل بين البنوك ';
            // start creditor
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->accountstreeid = $fromTreeId;
            $dailyEntryCreditor->value = $transfervalue;

            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            // end creditor
            // start debtor
            $dailyEntryDebtor->accountstreeid = $toTreeId;
            $dailyEntryDebtor->value = $transfervalue;
            $dailyEntryDebtorArray = array();

            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $did = $returnedData[1];
            $rowData = $transferBtweenBankAccountsDAO->load($transferId);
            $rowData->dailyentryid = $did;
            $transferBtweenBankAccountsDAO->update($rowData);
        }
        $transactions->commit();
    } catch (Exception $ex) {
        $transactions->rollback();
    }

    // end debtor
    //return $saveValuebeforeValid;
}

//edit from transfer tbl
function edit() {
    //to use the variable out side the funcion
    global $transferBtweenBankAccountsEX;

    $id = (int) $_GET['id'];

    $loadData = $transferData = $transferBtweenBankAccountsEX->loadEX(" and id= $id ");

    return $loadData;
}

function delete($id) {

    //to use the variable out side the funcion
    global $transferBtweenBankAccounts;
    global $transferBtweenBankAccountsDAO;
    global $myBankaccountRecord;


    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    //Transaction
    $transactions = new Transaction();
    $rowDataold = $transferBtweenBankAccountsDAO->load($id);
    $rowDataold->conditions = 1;
    $transferBtweenBankAccountsDAO->update($rowDataold);


    $ddlBankfrom = $rowDataold->bankidfrom;
    $accountidfrom = $rowDataold->accountidfrom;
    $ddlBankto = $rowDataold->bankidto;
    $accountidto = $rowDataold->accountidto;
    $transfervalue = $rowDataold->transfervalue;

    try {

        $transferId = $id;
        /////////////1- bank from
        $dataBankAccount = $myBankaccountRecord->load($accountidfrom);


        //decrease account value and write in history
        $accValOld = $dataBankAccount->accountbeginingbalance;
        $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance + $transfervalue;
        $myBankaccountRecord->update($dataBankAccount);
        insertAccountmovement($accValOld, $transfervalue, 0, $dataBankAccount->accountbeginingbalance, "حذف تحويل بين البنوك", $transferId, $dataBankAccount->accountid, $dataBankAccount->bankid, "transferBtweenBankAccounts.php");

        /////////////2- bank to
        $dataBankAccount = $myBankaccountRecord->load($accountidto);

        //decrease account value and write in history
        $accValOld = $dataBankAccount->accountbeginingbalance;
        $dataBankAccount->accountbeginingbalance = $dataBankAccount->accountbeginingbalance - $transfervalue;
        $myBankaccountRecord->update($dataBankAccount);
        insertAccountmovement($accValOld, $transfervalue, 1, $dataBankAccount->accountbeginingbalance, "حذف تحويل بين البنوك", $transferId, $dataBankAccount->accountid, $dataBankAccount->bankid, "transferBtweenBankAccounts.php");

        if ($rowDataold->dailyentryid > 0) {
            reverseEntryWithItsID($rowDataold->dailyentryid, 1);
        }

        $transactions->commit();
    } catch (Exception $ex) {
        $transactions->rollback();
    }

    // end debtor
    return $saveValuebeforeValid;
}

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

    //to use the variable out side the funcion
    global $myAccountmovement;
    global $myAccountmovementRecord;


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

    $myAccountmovementRecord->insert($myAccountmovement);
}

?>