<?php

// get the config file
include_once("../public/config.php");
//Transaction
include_once("../models/sql/Transaction.class.php");
//here the db files that include in the file
include("../public/include_dao.php");
//
include("affectplugins.php");

//Accountstree
require_once('../models/dao/AccountstreeDAO.class.php');
require_once('../models/dto/Accountstree.class.php');
require_once('../models/mysql/AccountstreeMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountstreeMySqlExtDAO.class.php');
//Dailyentry
require_once('../models/dao/DailyentryDAO.class.php');
require_once('../models/dto/Dailyentry.class.php');
require_once('../models/mysql/DailyentryMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentryMySqlExtDAO.class.php');
//Dailyentrycreditor
require_once('../models/dao/DailyentrycreditorDAO.class.php');
require_once('../models/dto/Dailyentrycreditor.class.php');
require_once('../models/mysql/DailyentrycreditorMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentrycreditorMySqlExtDAO.class.php');
//Dailyentrydebtor
require_once('../models/dao/DailyentrydebtorDAO.class.php');
require_once('../models/dto/Dailyentrydebtor.class.php');
require_once('../models/mysql/DailyentrydebtorMySqlDAO.class.php');
require_once('../models/mysql/ext/DailyentrydebtorMySqlExtDAO.class.php');

########################affect programs plugins
//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');

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

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

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

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

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


//here goes the instances and general variables
//Transaction
$transactions = new Transaction();

//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();
########################affect programs plugins
//check and use the condetion that suite this action
if ($do == "add") {
    try {
        $maxRelated = add();
        $transactions->commit();
        echo "1," . $maxRelated;
    } catch (Exception $e) {
        $transactions->rollback();
        echo "-1," . $maxRelated;
        echo $e;
    }
} elseif ($do == "drawtable") {
    $startDate = date('Y-m-d');
    $endDate = date('Y-m-d');

    DrawTable($startDate, $endDate);
}

//******************    Functions    ************************//
function add() {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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

    global $accountsTreeDAO;
    $maxRelatedno = 0;

    $branchid_entry = (int) filter_input(INPUT_POST, 'branchid_entry');
    $dDateTime = filter_input(INPUT_POST, 'dDateTime');
    $entryComment = filter_input(INPUT_POST, 'entryComment');

    $noOfEntries = filter_input(INPUT_POST, 'noOfEntries');

    $maxRelated = $dailyEntryEX->getMaxRelated();
    if (count($maxRelated) < 1 || empty($maxRelated->related)) {
        $maxRelatedno = 1;
    } else {
        $maxRelatedno = $maxRelated->related + 1;
    }

    for ($j = 1; $j <= $noOfEntries; $j++) {
        $totalFrom = filter_input(INPUT_POST, 'totalValueFrom_hidden' . $j);
        $totalTo = filter_input(INPUT_POST, 'totalValueTo_hidden' . $j);

        if (!empty($totalFrom) && !empty($totalTo) && $totalFrom == $totalTo && $totalFrom > 0) {
            $dailyEntry->totalcreditor = $totalTo; //الى دائن
            $dailyEntry->totaldebtor = $totalFrom; // من مدين
            $dailyEntry->branchid = $branchid_entry;
            $dailyEntry->dDateTime = $dDateTime;
            $dailyEntry->thedate = date('Y-m-d');
            $dailyEntry->userid = $_SESSION['userid'];
            $dailyEntry->condition = 0;
            $dailyEntry->reverseofid = 0;
            $dailyEntry->entryComment = $entryComment;

            $dailyEntry->fromFlag = 0;


            $dailyEntry->related = $maxRelatedno;
            $dailyEntryId = $dailyEntryDAO->insert($dailyEntry);

            $itr = filter_input(INPUT_POST, 'itr' . $j);
            //1-from// من مدين
            for ($i = 1; $i <= $itr; $i++) {
                $valueFrom = filter_input(INPUT_POST, 'valueFrom' . $j . '-' . $i);
                $valueTo = filter_input(INPUT_POST, 'valueTo' . $j . '-' . $i);
                $parent = filter_input(INPUT_POST, 'E_parent' . $j . '-' . $i);
                $comment = filter_input(INPUT_POST, 'comment' . $j . '-' . $i);
                $costcenterid = filter_input(INPUT_POST, 'costcenterid' . $j . '-' . $i);
                if (!empty($parent) && (!empty($valueTo) || !empty($valueFrom))) {
                    if (!empty($valueFrom)) {
                        //1-from// من مدين
                        $dailyEntryDebtor->accountstreeid = $parent;
                        $dailyEntryDebtor->value = $valueFrom;
                        $dailyEntryDebtor->dailyentryid = $dailyEntryId;
                        $dailyEntryDebtor->dComment = $comment;
                        $dailyEntryDebtor->costcenterid = $costcenterid;
                        //
                        $dailyEntryDebtorDAO->insert($dailyEntryDebtor);
                        $operation = affectAccount($dailyEntryDebtor, 0);
                        $whatIsIt = whatIsIt($parent);
                        $element = $accountsTreeDAO->load($parent);
                        affectPlugin($whatIsIt, $valueFrom, $dailyEntryId, $operation, $element->name, "قيد يومية", "dailyentry.php", 0, $parent, 0, $dailyEntry, array(), array());
                    }
                    if (!empty($valueTo)) {
                        //2-to//الى دائن
                        $dailyEntryCreditor->accountstreeid = $parent;
                        $dailyEntryCreditor->value = $valueTo;
                        $dailyEntryCreditor->dailyentryid = $dailyEntryId;
                        $dailyEntryCreditor->dComment = $comment;
                        $dailyEntryCreditor->costcenterid = $costcenterid;

                        $dailyEntryCreditorDAO->insert($dailyEntryCreditor);
                        //
                        $operation = affectAccount($dailyEntryCreditor, 1);
                        //
                        $whatIsIt = whatIsIt($parent);
                        $element = $accountsTreeDAO->load($parent);
                        affectPlugin($whatIsIt, $valueTo, $dailyEntryId, $operation, $element->name, "قيد يومية", "dailyentry.php", 0, $parent, 1, $dailyEntry, array(), array());
                    }
                }
            }
        }
    }
    return $maxRelatedno;
}

function affectAccount($CreditorOrDebtorObj, $type) {

    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $accountsTree = $accountsTreeDAO->load($CreditorOrDebtorObj->accountstreeid);
    $operation = whatToDo($accountsTree->itemtype, 'positive', $type);
    if ($operation == 'increase') {
        $accountsTree->theValue += $CreditorOrDebtorObj->value;
    }
    if ($operation == 'decrease') {
        $accountsTree->theValue -= $CreditorOrDebtorObj->value;
    }

    $accountsTreeDAO->update($accountsTree);

    //affect parents
    //affectParents($accountsTree->parent, $operation, $CreditorOrDebtorObj->value);
    //parents are the sum of children

    return $operation;
}

function whatToDo($accountType, $numSign, $type) {
    $operation;
    if ($numSign == 'positive') {

        if ($type == 0) {//مدين // من
            switch ($accountType) {
                case 0:
                case 3:
                case 5:
                    $operation = 'increase';
                    break;
                case 1:
                case 2:
                case 4:
                    $operation = 'decrease';
                    break;
                default:
                    break;
            }
        } elseif ($type == 1) {//دائن // الى
            switch ($accountType) {
                case 0:
                case 3:
                case 5:
                    $operation = 'decrease';

                    break;
                case 1:
                case 2:
                case 4:
                    $operation = 'increase';
                    break;
                default:
                    break;
            }
        }
    }
    return $operation;
}

function affectParents($parent, $operation, $value) {
    global $accountsTreeDAO;
    global $accountsTreeEX;

    if (!empty($parent)) {
        // retrieve all children of $parent
        $result = $accountsTreeDAO->load($parent);

        if (count($result) > 0) {
            if ($operation == 'increase') {
                $result->theValue += $value;
            }
            if ($operation == 'decrease') {
                $result->theValue -= $value;
            }
            $accountsTreeDAO->update($result);

            if ($result->parent != 0) {
                affectParents($result->parent, $operation, $value);
            }
        }
    }
}

function DrawTable($startDate, $endDate) {
    global $smarty;
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;
    global $dailyEntryEX;

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

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


    $queryString = ' and dailyentry.thedate >= "' . $startDate . '" and dailyentry.thedate <= "' . $endDate . '" ';

    $allDailyEntery = array();
    $allDailyEnteryCreditor = $dailyEntryEX->queryAllEXCreditor($queryString);

    $prviosId = -1;
    foreach ($allDailyEnteryCreditor as $dataCreditor) {
        if ($dataCreditor->id == $prviosId) {
            $dataCreditor->id = '';
        } else {
            $prviosId = $dataCreditor->id;
            $dataCreditor->id = '';
            //put debtor data first
            $allDailyEnteryDebtor = $dailyEntryEX->queryAllEXDebtor($dataCreditor->dailyentryid, $queryString);
            $i = 0;
            foreach ($allDailyEnteryDebtor as $dataDebtor) {
                if ($i != 0) {
                    $dataDebtor->id = "";
                }

                array_push($allDailyEntery, $dataDebtor);
                $i++;
            }
        }
        //put creditor data finaly
        array_push($allDailyEntery, $dataCreditor);
    }
    /* $allDailyEntery = $dailyEntryDAO->queryAll();
      if(count($allDailyEntery)>0)
      {
      foreach($allDailyEntery as $dailyEntry)
      {
      $dailyEntry->from = $dailyEntryDebtorEX->queryByDailyentryidEX($dailyEntry->id);
      $dailyEntry->to = $dailyEntryCreditorEX->queryByDailyentryidEX($dailyEntry->id);
      }
      } */
    /* print_r('<pre>');
      print_r($allDailyEntery);
      print_r('</pre>'); */
    $smarty->assign("allDailyEntery", $allDailyEntery);
    $smarty->assign("allDailyEnteryCount", count($allDailyEntery));

    $smarty->display("dailyentrymanyview/table.html");
}

?>