<?php

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

//global varable
global $showoutside;

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


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

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

//Bankaccount
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/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 :- saveCTRL اضافة وتعديل وعرض الخزن

  OPERTATION in Controller

  1-display add form
  2- add in Save tbl
  3-insert into savedaily tbl
  4-display sucess or error
  5-display show form
  6-edit in Save data

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


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

} else {
    $smarty->display("header.html");
}


//here goes the instances and general variables
//Bank
$myBank = new Bank();
$myBankRecord = new BankMySqlDAO();
$myBankEx = new BankMySqlExtDAO();

//Bankaccount
$myBankaccountRecord = new BankaccountMySqlDAO();

//Breadcrumb
$breadcrumbObject = new Breadcrumb();


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

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

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


    //breadcrumb
    $breadcrumbObject->add('ادارة البنوك><a href="bankController.php?do=show">البنوك</a> > اضافة بنك', 'bankController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);



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

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

    try {
        // here the function that do the action
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

    $bankData = show();
    $smarty->assign("bankData", $bankData);

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

    //breadcrumb
    $breadcrumbObject->add('ادارة البنوك><a href="bankController.php?do=show">البنوك</a> > عرض البنوك', 'bankController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


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


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

    // here the function that do the action

    $bankId = $_GET['bankid'];
    $bankdeleteValid = delete($bankId);
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
        if ($bankdeleteValid[1] == 0) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
        } elseif ($bankdeleteValid[1] == 2) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
        } else {
            $data = array('status' => 2, 'message' => "لا يمكن حذف  هذا البنك الا بعد حذف كل البيانات المرتبطه به", 'message_en' => 'Can not delete this bank until deleting its related data');
        }
        echo json_encode($data);
    } else {
        if ($bankdeleteValid[1] == 0) {
            header("location:?do=sucess");
        } elseif ($bankdeleteValid[1] == 2) {
            $url = "bankController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لقد حدث خطأ اثناء اجراء العملية";
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            $url = "bankController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = "لا يمكن حذف  هذا البنك الا بعد حذف كل البيانات المرتبطه به";
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    }
} elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $bankId = $_GET['bankid'];
    try {
        // here the function that do the action
        returndelete($bankId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deletetemp") {
    include_once("../public/authentication.php");

    $bankId = $_GET['bankid'];
    try {
        // here the function that do the action
        deletetemp($bankId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

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


    //breadcrumb
    $breadcrumbObject->add('ادارة البنوك><a href="bankController.php?do=show">البنوك</a> > تعديل بنك', 'bankController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("bankview/edit.html");
}



//edit  update
elseif ($do == "update") {

    //here the permssion check
    include_once("../public/authentication.php");
    //
    try {
        // here the function that do the action
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
}



//edit  update
elseif ($do == "executeOperation") {

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

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

    $bankData = show();
    $smarty->assign("bankData", $bankData);


    //breadcrumb
    $breadcrumbObject->add('ادارة البنوك><a href="bankController.php?do=show">البنوك</a> > عرض البنوك', 'bankController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


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

    $smarty->assign("customBank", 1);
    $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("customBank", 1);

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


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

} else {
    $smarty->display("footer.html");
}

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

// add in Storerawmaterial tbl
function add() {

    //to use the variable out side the funcion
    global $myBank;
    global $myBankRecord;


    $bankName = $_POST['bankname'];
    $bankDetails = $_POST['bankdetails'];


    //add in bank tbl
    $myBank->bankdate = date("Y-m-d");
    $myBank->bankname = $bankName;
    $myBank->conditions = 0;
    $myBank->userid = $_SESSION["userid"];
    $myBank->webApiId = (int) $_POST['webApiId'];

    $myBankRecord->insert($myBank, $bankDetails);
}

//show
function show() {
    //to use the variable out side the funcion
    global $myBankEx;

    $bankData = $myBankEx->queryWithOrder();

    return $bankData;
}

//show
function delete($bankId) {

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

    //  $bankId = $_GET['bankid'];

    $rowDelData = $myBankRecord->load($bankId);
    try {
        if (!empty($bankId)) {
            $bankaccountData = $myBankaccountRecord->queryByBankid($bankId);
            if (count($bankaccountData) <= 0) {
                $bankdeleteValid = 0;
                $myBankRecord->delete($bankId);
                delTreeElement($rowDelData->bankname);
                $note = "success";
            } else {
                $bankdeleteValid = 1;
                $note = "لا يمكن حذف  هذا البنك";
            }
        } else {
            $bankdeleteValid = 2;
            $note = "حدث خطأ أثناء حذف البنك";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف البنك";
    }


    return array($note, $bankdeleteValid);
}

//deletetemp Store tbl
function deletetemp($bankId) {
    //to use the variable out side the funcion
    global $myBank;
    global $myBankEx;


    try {
        if (!empty($bankId)) {

            $myBank->bankdate = date("Y-m-d");
            $myBank->conditions = 1;
            $myBank->userid = $_SESSION["userid"];
            $myBank->bankid = $bankId;

            $myBankEx->updateConditions($myBank);

            $note = "success";
        } else {
            $note = "حدث خطأ أثناء إخفاء البنك";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء إخفاء البنك";
    }

    return $note;
}

//returndelete Store tbl
function returndelete($bankId) {
    //to use the variable out side the funcion
    global $myBank;
    global $myBankEx;


    try {
        if (!empty($bankId)) {
            $myBank->bankdate = date("Y-m-d");
            $myBank->conditions = 0;
            $myBank->userid = $_SESSION["userid"];
            $myBank->bankid = $bankId;

            $myBankEx->updateConditions($myBank);


            $note = "success";
        } else {
            $note = "حدث خطأ أثناء اظهار البنك";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء اظهار البنك";
    }

    return $note;
}

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

    //get Variable
    $bankId = $_GET['bankid'];

    $loadData = $myBankRecord->load($bankId);

    return $loadData;
}

function update() {
    //to use the variable out side the funcion
    global $myBank;
    global $myBankRecord;
    global $accountsTree;
    global $accountsTreeDAO;

    $bankName = $_POST['bankname'];
    $bankDetails = $_POST['bankdetails'];
    $conditions = $_POST['conditions'];
    $bankId = $_POST['bankid'];
    $bankDate = $_POST['bankdate'];


    //add in bank tbl
    $myBank->bankdate = $bankDate;
    $myBank->bankname = $bankName;
    $myBank->conditions = $conditions;
    $myBank->userid = $_SESSION["userid"];
    $myBank->bankid = $bankId;


    $myBankRecord->update($myBank, $bankDetails);
}

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

    $outputString;

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

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

            //get store name
            $bankData = $myBankRecord->load($bankId);
            $bankName = $bankData->bankname;

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

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

?>