<?php

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

// get the config file
include_once("../public/config.php");
include_once("initiateStaticSessionCommingWithCurl.php");
include_once("dailyentryfun.php");

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

//Income
require_once('../models/dao/IncomeDAO.class.php');
require_once('../models/dto/Income.class.php');
require_once('../models/mysql/IncomeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncomeMySqlExtDAO.class.php');
//Incometype
require_once('../models/dao/IncometypeDAO.class.php');
require_once('../models/dto/Incometype.class.php');
require_once('../models/mysql/IncometypeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncometypeMySqlExtDAO.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');
//lang

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

//get the do the action
$do = $_GET['do'];

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

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */
$userID = $_SESSION['userid'];

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

} else {
    $smarty->display("header.html");
}
//here goes the instances and general variables
$incomeType = new Incometype();
$IncometypeDAO = new IncometypeMySqlDAO();
$IncometypeEX = new IncometypeMySqlExtDAO();
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();
$incomeDAO = new IncomeMySqlDAO();

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

//check and use the condetion that suite this action
//getTheTrueValue(151, 0);
if (empty($do)) {
    $allParents = $IncometypeDAO->queryByConditions(0);
    $smarty->assign("allParents", $allParents);
    $smarty->display("incomeTypeview/add.html");
} elseif ($do == "add") {
    //$flag = $_GET['flag'];
    try {
        $checkInsert = add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
                echo $checkInsert[1];

        } else {
            if ($checkInsert[0] == '0') {
                header("location:?do=sucess");
            } else {
                $smarty->assign('msg', ' نوع الايراد تم ادخاله من قبل');
                $smarty->display("incomeTypeview/add.html");
            }
        }
        /* if(!empty($flag) && $flag == "addexpense")
          {
          header("location:expensesController.php");
          }
          else
          {
          header("location:?do=sucess");
          } */
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {
    $incomedata = $IncometypeDAO->queryByConditions(0);
    $smarty->assign("incomedata", $incomedata);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("incomeTypeview/show.html");
} elseif ($do == "editprint") {
    $id = $_GET["id"];
    $incomeType = $IncometypeDAO->load($id);

    $allParents = $IncometypeDAO->queryByConditions(0);
    $smarty->assign("allParents", $allParents);

    $smarty->assign("incomeType", $incomeType);
    $smarty->display("incomeTypeview/editprint.html");
} elseif ($do == "edit") {
    $id = $_GET["id"];
    $incomeType = $IncometypeDAO->load($id);

    $allParents = $IncometypeDAO->queryByConditions(0);
    $smarty->assign("allParents", $allParents);
    $smarty->assign("incomeType", $incomeType);
    $smarty->assign("id", $id);

    $smarty->display("incomeTypeview/edit.html");
} elseif ($_GET['do'] == "update") {
    try {
        update();

        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($_GET['do'] == "delete") {
    try {
        $note = delete();
        if ($note != "success") {
            $smarty->assign('msgnote', $note);
//            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}
$smarty->assign("expensesScripts", 1);

$smarty->assign("customValidation", 1);
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

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

function getIncomeTypeParents() {
    global $IncometypeEX;

    $allParents = $IncometypeEX->getParents();
    return $allParents;
}

function add() {
    global $incomeType;
    global $IncometypeDAO;
    global $IncometypeEX;
    global $accountsTree;
    global $accountsTreeDAO;

    $userId = $_SESSION['userid'];
    $name = $_POST['name'];
    $descripe = $_POST['descripe'];
    $parentid = $_POST['parent'];
    $defaultValue = $_POST["defaultValue"];

    $id = 0;
    $checkIsert = '';
    if (empty($descripe)) {
        $descripe = '';
    }
    if (empty($defaultValue)) {
        $defaultValue = 0;
    }

    $getData = $IncometypeDAO->queryByIncomeTypeName($name);
    if (!empty($getData)) {
        $checkIsert = '1';
    } else {
        $incomeType->incomeTypeName = $name;
        $incomeType->incomeTypeDetails = $descripe;
        $incomeType->conditions = 0;
        $incomeType->incomeTypeDate = date("Y-m-d");
        $incomeType->userid = $userId;
        $incomeType->parent = $parentid;
        //print_r($incomeType->parent.'ddddddddddd<br/>');
        $incomeType->defaultValue = $defaultValue;

        if (!empty($name)) {
            $id = $IncometypeDAO->insert($incomeType);
            if ($parentid == 0) {
                $treeId = addTreeElement($name, 151, 2, 0, 0, '', 0, 0);
            } else {
                $oldData2 = $IncometypeDAO->load($parentid);
                $treeId2 = $oldData2->treeId;
                $treeId = addTreeElement($name, $treeId2, 2, 0, 0, '', 0, 0);
            }

            $incomeType->treeId = $treeId;
            $IncometypeDAO->update($incometype);
        }
        $checkIsert = '0';
    }
    return array($checkIsert, $id);
}

function update() {
    global $incomeType;
    global $IncometypeDAO;
    global $IncometypeEX;
    global $accountsTree;
    global $accountsTreeDAO;

    $userId = $_SESSION['userid'];
    $name = $_POST['name'];
    $descripe = $_POST['descripe'];
    $parentid = $_POST['parent'];
    $defaultValue = $_POST["defaultValue"];
    $id = $_POST["incomeTypeId"];
    if (empty($descripe)) {
        $descripe = '';
    }
    if (empty($defaultValue)) {
        $defaultValue = 0;
    }

    $incomeType->incomeTypeId = $id;
    $incomeType->incomeTypeName = $name;
    $incomeType->incomeTypeDetails = $descripe;
    $incomeType->conditions = 0;
    $incomeType->incomeTypeDate = date("Y-m-d");
    $incomeType->userid = $userId;
    $incomeType->parent = $parentid;
    //print_r($incomeType->parent.'ddddddddddd<br/>');
    $incomeType->defaultValue = $defaultValue;


    if (!empty($name)) {
        $oldData = $IncometypeDAO->load($id);
        $treeId = $oldData->treeId;

        $getRow = $accountsTreeDAO->load($treeId);

        if ($parentid == 0) {

            $getRow->name = $name;
            $getRow->id = $treeId;
            $getRow->parent = 151;
            $getRow->customName = $name;

            editTreeElement($getRow);
        } else {
            $oldData2 = $IncometypeDAO->load($parentid);
            $treeId2 = $oldData2->treeId;
            $parentName = $oldData2->incomeTypeName;

            $getRow->name = $name;
            $getRow->id = $treeId;
            $getRow->parent = $treeId2;
            $getRow->customName = $name;

            editTreeElement($getRow);
        }

        $IncometypeDAO->update($incomeType);
    }
}

function delete() {
    global $incomeType;
    global $IncometypeDAO;
    global $IncometypeEX;

    global $incomeDAO;
    global $smarty;

    $userID = $_SESSION['userid'];
    $incometypeid = $_GET['id'];


    //1- check if there are any expenses associated with this category
    $incomedata = $incomeDAO->queryByIncomeTypeId($incometypeid);

    //2- check if there are any child category for this parent category
    $childCategories = $IncometypeDAO->queryByParent($incometypeid);
    if (count($incomedata) > 0 || count($childCategories) > 0) {
        $url = "incomeTypeController.php?do=show";
        $smarty->assign('urldirect', $url);
        if ($_SESSION['erp_lang'] == 'ar') {
            $note = "لا يمكن حذف هذا النوع لانه مرتبط ببيانات اخرى";
        } else {
            $note = "This type cannot be deleted because it is associated with other data";
        }

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $incomeType = $IncometypeDAO->load($incometypeid);
        $incomeType->incomeTypeId = $incometypeid;
        $incomeType->incomeTypeDate = date("Y-m-d");
        $incomeType->userid = $userID;
        $incomeType->conditions = 1;
        $IncometypeDAO->update($incomeType);

        delTreeElementById($incomeType->treeId);

        header("location:?do=sucess");
    }
}

//to dynamicaly add elements of tree as income type
//so , we also need to stop adding tree element at add() during the use of this function
//hint: copied from accountstree ajax
function getTheTrueValue($parentTree, $parentIncome) {
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $result = $accountsTreeEX->queryByParentExt($parentTree);
    foreach ($result as $type) {
        $_POST['name'] = $type->name;
        $_POST['descripe'] = 'انواع افتراضية';
        $_POST['parent'] = $parentIncome;
        $_POST["defaultValue"] = 0;
        $incomeId = add();
        getTheTrueValue($type->id, $incomeId);
    }
}

?>