<?php

///***************************** تحويل نقدي ********************///
//the global file operation
include("../public/impOpreation.php");
include_once("dailyentryfun.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
include("../public/include_dao.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');
//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');
//Cashtransfer
require_once('../models/dao/CashtransferDAO.class.php');
require_once('../models/dto/Cashtransfer.class.php');
require_once('../models/mysql/CashtransferMySqlDAO.class.php');
require_once('../models/mysql/ext/CashtransferMySqlExtDAO.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 :- assetsCTRL

  OPERTATION in Controller

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

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

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

//here goes the instances and general variables
$account = new Bankaccount();
$accountDAO = new BankaccountMySqlDAO;
$accountExt = new BankaccountMySqlExtDAO;

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

$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExt = new BankMySqlExtDAO;
//Accountmovement
$accountMoveDAO = new AccountmovementMySqlDAO;
$accountMove = new Accountmovement;
//Save
$save = new Save();
$savesDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();
//Cashtransfer
$cashTransfer = new Cashtransfer();
$cashTransferDAO = new CashtransferMySqlDAO();
$cashTransferExt = new CashtransferMySqlExtDAO();

$accountsTreeDAO = new AccountstreeMySqlDAO();

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

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

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

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

    $savesData = getSaves();
    $smarty->assign("savesData", $savesData);

    $smarty->display("cashTransferview/add.html");
    $smarty->assign('customdepositcheck', 1);
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");


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

    $savesData = getSaves();
    $smarty->assign("savesData", $savesData);
    $smarty->assign("customPrint", 1);

    edit();
} elseif ($do == "show") {
    include_once("../public/authentication.php");

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

    $savesData = getSaves();
    $smarty->assign("savesData", $savesData);

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

    show();

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

    $smarty->assign("customCheck", 1);
} elseif ($_GET['do'] == "executeOperation") {
    include_once("../public/authentication.php");

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

    $savesData = getSaves();
    $smarty->assign("savesData", $savesData);

    try {
        execute();
        show();
        $smarty->display("cashTransferview/show.html");
        $smarty->assign("customCheck", 1);
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($do == "delete") {
    include_once("../public/authentication.php");

    try {
        $id = $_REQUEST["id"];

        $note = delete($id);
        if ($note !== "sucess") {
            $url = "assetTypeController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = $note;
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        // header("location:?do=error");
    }
} elseif ($do == "details") {
    include_once("../public/authentication.php");

    $cashTransferData = $cashTransferExt->loadExt($_GET['id']);
    $smarty->assign('cashTransferData', $cashTransferData);

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

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

$smarty->assign('customValidation', 1);
//here the global templates
$smarty->display("footer.html");

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

function getSaves() {
    global $savesDAO;

    $savesData = $savesDAO->queryByConditions(0);
    return $savesData;
}

function add() {
    global $saveDaily;
    global $saveDailyDAO;
    global $save;
    global $savesDAO;
    global $saveExt;
    global $cashTransfer;
    global $cashTransferDAO;
    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $accountExt;
    global $account;
    global $accountsTreeDAO;
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;


    //Transaction
    $cashTransactions = new Transaction();



    try {
        $transfer = $_POST["transfer"];
        $saveId = $_POST['save'];
        $accountid = $_POST["accountid"];
        $accountnumber = $_POST["accountnumberDis"];
        $accountbeginingbalance = $_POST["accountbeginingbalance"];
        $amount = $_POST["txtAmount"];
        $note = $_POST["textNote"];
        $number = $_POST["txtcheckNum"];
        $user = $_POST["txtUser"];
        $date = date("Y-m-d");
        $ddlBank = $_POST["ddlBank"];
        if ($transfer == 1) { //سحب شيك
            $type = 1;
            $processname = "تحويل نقدي من البنك إلى الخزنة";
            $savedailychangetype = 0;
            $accountmovementtype = 1;
        } else if ($transfer == 2) {//إيداع شيك
            $type = 2;
            $processname = "تحويل نقدي من الخزنة إلى البنك";
            $savedailychangetype = 1;
            $accountmovementtype = 0;
        }

        $cashTransfer->accountbeforevalue = $accountbeginingbalance;
        $cashTransfer->bankaccountid = $accountid;
        $cashTransfer->cashtransferamount = $amount;
        $cashTransfer->cashtransferdate = $date;
        $cashTransfer->cashtransfernote = $note;
        $cashTransfer->cashtransfernumber = $number;
        $cashTransfer->cashtransferuser = $user;
        $cashTransfer->conditions = 0;
        $cashTransfer->saveid = $saveId;
        $cashTransfer->type = $type;
        $cashTransfer->userid = $_SESSION['userid'];
        $cashTransfer->dailyentryid = 0;

        $cashTransferId = $cashTransferDAO->insert($cashTransfer);

        if ($cashTransferId != null) {
            $savesData = $saveExt->loadForUpdateEx($saveId);
            $saveBefore = $savesData->savecurrentvalue;
            if ($transfer == 1) { //سحب شيك
                $saveAfter = ($savesData->savecurrentvalue + $amount);
            } else if ($transfer == 2) {//إيداع شيك
                $saveAfter = ($savesData->savecurrentvalue - $amount);
            }

            $save->savecurrentvalue = $saveAfter;
            $save->saveid = $saveId;
            $save->userid = $_SESSION['userid'];

            $saveExt->updateSaveValue($save);

            //insert into savedaily
            $saveDaily->processname = $processname;
            $saveDaily->savedailychangetype = $savedailychangetype;
            $saveDaily->savedailychangeamount = $amount;
            $saveDaily->savedailydate = date("Y-m-d H:i:s");
            $saveDaily->savedailymodelid = $cashTransferId;
            $saveDaily->savedailysaveafter = $saveAfter;
            $saveDaily->savedailysavebefore = $saveBefore;
            $saveDaily->saveid = $saveId;
            $saveDaily->tablename = "cashTransferController.php";
            $saveDaily->userid = $_SESSION['userid'];

            $saveDailyDAO->insert($saveDaily);

            //update bank account balance
            $accoundatat = $accountDAO->load($accountid);
            $accountBefore = $accoundatat->accountbeginingbalance;

            if ($accountmovementtype == 1) {
                $account->accountbeginingbalance = $accountBefore - $amount;

                $accountmovementafter = $accountBefore - $amount;
            } elseif ($accountmovementtype == 0) {
                $account->accountbeginingbalance = $accountBefore + $amount;
                $accountmovementafter = $accountBefore + $amount;
            }

            $account->accountdate = $date;
            $account->accountid = $accountid;

            //update
            $accountExt->updateacount($account);

            //Insert in accountmovement table
            $accountMove->accountmovementbefore = $accountBefore;
            $accountMove->accountid = $accountid;
            $accountMove->bankid = $ddlBank;
            $accountMove->accountmovementamount = $amount;
            $accountMove->accountmovementafter = $accountmovementafter;
            $accountMove->accountmovementtype = $accountmovementtype;
            $accountMove->processname = $processname;
            $accountMove->tablename = "cashTransferController.php";
            $accountMove->accountmovementmodelid = $cashTransferId;
            $accountMove->accountmovementdate = $date;
            $accountMove->userid = $_SESSION['userid'];

            //Insert
            $accountMoveDAO->insert($accountMove);
        }

        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();

        $baccountData = $accountDAO->load($accountid);
        $accountTreeId = $baccountData->treeId;

        $saveData = $savesDAO->load($saveId);
        $saveTreeId = $saveData->treeId;
        if ($transfer == 1) {//من البنك إلى الخزنة  ----- المدين : الخزنة ------- الدائن : البنك
            $dailyEntryDebtor->accountstreeid = $saveTreeId;
            $dailyEntryCreditor->accountstreeid = $accountTreeId;
        } else {
            $dailyEntryDebtor->accountstreeid = $accountTreeId;
            $dailyEntryCreditor->accountstreeid = $saveTreeId;
        }

        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntry->entryComment = $processname;

        //يتم التعامل مع البنك ام الحسابات فى هذا البنك؟
        $dailyEntryDebtor->value = $amount;
        //$dailyEntryDebtor->accountstreeid = 14;

        $dailyEntryCreditor->value = $amount;
        //$dailyEntryCreditor->accountstreeid = 14;

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

        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);

        $did = $returnedData[1];

        $rowData = $cashTransferDAO->load($cashTransferId);

        $cashTransfer->accountbeforevalue = $rowData->accountbeforevalue;
        $cashTransfer->bankaccountid = $rowData->bankaccountid;
        $cashTransfer->cashtransferamount = $rowData->cashtransferamount;
        $cashTransfer->cashtransferdate = $rowData->cashtransferdate;
        $cashTransfer->cashtransfernote = $rowData->cashtransfernote;
        $cashTransfer->cashtransfernumber = $rowData->cashtransfernumber;
        $cashTransfer->cashtransferuser = $rowData->cashtransferuser;
        $cashTransfer->conditions = $rowData->conditions;
        $cashTransfer->saveid = $rowData->saveid;
        $cashTransfer->type = $rowData->type;
        $cashTransfer->userid = $rowData->userid;
        $cashTransfer->dailyentryid = $did;

        $cashTransferDAO->update($cashTransfer);

        $cashTransactions->commit();

        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $cashTransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }
}

function edit() {
    global $cashTransferDAO;
    global $cashTransferExt;
    global $savesDAO;
    global $smarty;

    $cashTransferId = $_GET["id"];

    if (isset($cashTransferId)) {
        $showData = $cashTransferExt->loadExt($cashTransferId);
        $smarty->assign("showData", $showData);
        $smarty->display("cashTransferview/editprint.html");
    }
}

function show() {
    global $cashTransferExt;
    global $cashTransferExt;
    global $savesDAO;
    global $smarty;

    $saveid = $_REQUEST["saveid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];

    if (isset($to) && $to != "" && isset($from) && $from != "") {
        $message = "عرض التحويلات النقدية من تاريخ : " . $from . "  الى تاريخ  " . $to;
        $smarty->assign('message', $message);

        $shownData = $cashTransferExt->queryCashTransferBydate($from, $to);
        // assign your db results to the template
        $smarty->assign('shownData', $shownData);
    } elseif (isset($saveid) && $saveid != "-1") {
        $saveData = $savesDAO->load($saveid);

        $message = "عرض التحويلات النقدية من وإلى الخزنة : " . $saveData->savename;
        $smarty->assign('message', $message);

        $shownData = $cashTransferExt->queryCashTransferBySaveId($saveid);
        $smarty->assign('shownData', $shownData);
    } else {
        $message = "عرض التحويلات النقدية من تاريخ : " . date("Y-m-d") . "  الى تاريخ :   " . date("Y-m-d");
        $smarty->assign('message', $message);

        $shownData = $cashTransferExt->queryCashTransferBydate(date("Y-m-d"), date("Y-m-d"));
        $smarty->assign('shownData', $shownData);
    }
}

function delete($id) {
    global $saveDaily;
    global $saveDailyDAO;
    global $save;
    global $savesDAO;
    global $saveExt;
    global $cashTransfer;
    global $cashTransferExt;
    global $cashTransferDAO;
    global $accountMove;
    global $accountMoveDAO;
    global $accountDAO;
    global $accountExt;
    global $account;

    //Transaction
    $cashTransactions = new Transaction();
    try {
        $cashTransferId = $id;

        $dailyentryid = $_GET['action'];

        $checkdata = $cashTransferDAO->load($cashTransferId);
        $accountid = $checkdata->bankaccountid;
        $amount = $checkdata->cashtransferamount;
        $type = $checkdata->type;
        //////////////////////////
        $saveId = $checkdata->saveid;

        $savedata = $saveExt->loadForUpdateEx($saveId);
        $saveBefore = $savedata->savecurrentvalue;

        if ($type == 1) {
            $saveAfter = ($savedata->savecurrentvalue - $amount);
            $savedailychangetype = 1;
            $processname = "إلغاء تحويل نقدي من البنك إلى الخزنة";
        } else if ($type == 2) {
            $saveAfter = ($savedata->savecurrentvalue + $amount);
            $savedailychangetype = 0;
            $processname = "إلغاء تحويل نقدي من الخزنة إلى البنك";
        }
        $save->savecurrentvalue = $saveAfter;
        $save->saveid = $saveId;
        $save->userid = $_SESSION['userid'];

        $saveExt->updateSaveValue($save);

        //insert into savedaily
        $saveDaily->processname = $processname;
        $saveDaily->savedailychangetype = $savedailychangetype;
        $saveDaily->savedailychangeamount = $amount;
        $saveDaily->savedailydate = date("Y-m-d H:i:s");
        $saveDaily->savedailymodelid = $cashTransferId;
        $saveDaily->savedailysaveafter = $saveAfter;
        $saveDaily->savedailysavebefore = $saveBefore;
        $saveDaily->saveid = $saveId;
        $saveDaily->tablename = "cashTransferController.php";
        $saveDaily->userid = $_SESSION['userid'];

        $saveDailyDAO->insert($saveDaily);


        ///////////////////////////

        $cashTransfer->userid = $_SESSION['userid'];
        $cashTransfer->conditions = 1;
        $cashTransfer->cashtransferid = $cashTransferId;

        $cashTransferExt->updateConditions($cashTransfer);


        $accountid = $checkdata->bankaccountid;
        $cashtransferamount = $checkdata->cashtransferamount;

        $accountdata = $accountDAO->load($accountid);
        $accountBefore = $accountdata->accountbeginingbalance;
        $bankid = $accountdata->bankid;
        if ($type == 1) {
            $accountAfter = $accountBefore + $cashtransferamount;
            $accountmovementtype = 0;
        } else if ($type == 2) {
            $accountAfter = $accountBefore - $cashtransferamount;
            $accountmovementtype = 1;
        }
        $account->accountbeginingbalance = $accountAfter;

        $account->accountid = $accountid;

        //update
        $accountExt->updateacount($account);


        //-------------------
        //Insert in accountmovement table
        $accountMove->accountmovementbefore = $accountBefore;
        $accountMove->accountid = $accountid;
        $accountMove->bankid = $bankid;
        $accountMove->accountmovementamount = $cashtransferamount;
        $accountMove->accountmovementafter = $accountAfter;
        $accountMove->accountmovementtype = $accountmovementtype;
        $accountMove->processname = $processname;
        $accountMove->tablename = "cashTransferController.php";
        $accountMove->accountmovementmodelid = $cashTransferId;

        $accountMove->accountmovementdate = date("Y-m-d");

        $accountMove->userid = $_SESSION['userid'];
        //Insert

        $accountMoveDAO->insert($accountMove);
        reverseEntryWithItsID($dailyentryid, 1);
        $cashTransactions->commit();
        return "sucess";
    } catch (Exception $ex) {
        $cashTransactions->rollback();
        return "لم تتم العمليه بنجاح";
    }
}

function execute() {
    global $cashTransferDAO;

    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];

    $dailyentryid = $_POST['dailyentryid'];

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

            $checkdata = $cashTransferDAO->load($checkId);
            //print_r($assetdata);

            $cashtransfernumber = $checkdata->cashtransfernumber;
            $conditions = $checkdata->conditions;

            if ($operationType == '1' && $conditions == 0) {//tempdelete
                try {
                    $note = delete($checkId);
                    if ($note != "sucess") {
                        //get product category name

                        if (count($assetscatid) > 0) {
                            reverseEntryWithItsID($dailyentryid);
                            $outputString .= $cashtransfernumber . ": " . $note . "<br/>";
                        }
                    } else {
                        reverseEntryWithItsID($dailyentryid);

                        $outputString .= $cashtransfernumber . ": تمت العملية بنجاح <br/>";
                    }
                } catch (Exception $e) {

                }
            } else {
                $outputString .= $cashtransfernumber . ": لا يمكن الغاء هذا الشيك لانه ملغى سابقا<br/>";
            }


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

        //print_r($outputString);
    }
}

?>