<?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");
include_once("noticefunctions.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');


//Notics
require_once('../models/dao/NoticsDAO.class.php');
require_once('../models/dto/Notic.class.php');
require_once('../models/mysql/NoticsMySqlDAO.class.php');
require_once('../models/mysql/ext/NoticsMySqlExtDAO.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
//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();


//Notics
$Notics = new Notic();
$NoticsDAO = new NoticsMySqlDAO();
$NoticsExt = new NoticsMySqlExtDAO();


//user
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();
########################affect programs plugins
//check and use the condetion that suite this action
if ($do == "add") {
    //Transaction
    $transactions = new Transaction();
    try {
        $dailyEntryId = add();
        $transactions->commit();
        echo "1," . $dailyEntryId;
    } catch (Exception $e) {
        $transactions->rollback();
        echo "-1," . $dailyEntryId;
        //echo $e;
    }
} elseif ($do == "drawtable") {
    $startDate = date('Y-m-d');
    $endDate = date('Y-m-d');

    DrawTable($startDate, $endDate);
} elseif ($do == "getdatetimenow") {
    echo date('Y-m-d H:i:s');
} elseif ($do == "getlayingorder") {
    getlayingOrder();
} elseif ($do == "getgeneralledger") {
    getgeneralledger();
} elseif ($do == "getassistantledger") {
    getassistantledger();
} elseif ($do == "getaccountstreeexcept") {
    getaccountstreeexcept();
} elseif ($do == "cashheader") {
    $mymenu = $_POST["mymenu"];
    $cashedheaderSize = filesize('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html');
    if ($cashedheaderSize < 1024) {//1024 menas 1 KB//it is needed in usergroup admin as it creates small dummy data in cash header//also this check is in html
        $file = fopen("../temp__cashedheader/cashedheader_" . $_SESSION['dbname'] . "_" . $_SESSION['userid'] . ".html", "w");
        $mymenu = str_replace('\"', '"', $mymenu, $count);
        fwrite($file, $mymenu);
        fclose($file);
    }
} elseif ($do == "getnoticecount") {

    $allnotics = $NoticsDAO->queryAll();
    $sum = 0;
    foreach ($allnotics as $data) {
        $productno = $data->productno;
        $productnotsellno = $data->productnotsellno;
        $kempilano = $data->kempilano;
        $clientcheckno = $data->clientcheckno;
        $suppliercheckno = $data->suppliercheckno;

        $sum = $productno + $productnotsellno + $kempilano + $clientcheckno + $suppliercheckno;
    }

    $sum2 = calcNotice() + getProductRequestNotice() + getToWorkshopOrderNotice() + getOtherRequestsNotice() + getPremiumToday();
    $total = $sum + $sum2;
    echo $total;
} elseif ($do == "setopeningbalance") {
    $accountid = (int) $_POST['id'];
    $valuedebt = (float) $_POST['valueFrom'];
    $valuecredit = (float) $_POST['valueTo'];

    if ($accountid > 0) {
        $accountData = $accountsTreeDAO->load($accountid);
        if ($accountData->accountNature == 0) {//debt
            $accountData->theValue = $valuedebt - $valuecredit;
        } elseif ($accountData->accountNature == 1) {//credit
            $accountData->theValue = $valuecredit - $valuedebt;
        }
        $accountsTreeDAO->update($accountData);
        echo 1;
    }
} elseif ($do == "cksession") {
    $sessionUserId = (int) $_POST["sui"];

    if (isset($_SESSION['userid']) && !empty($_SESSION['userid']) && !empty($sessionUserId) && $_SESSION['userid'] == $sessionUserId) {
        //session is ok
        echo 1;
    } else {
        //session Ended
        $myUserEx->removeUserIp($sessionUserId);
        echo -1;
    }
}

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

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

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

    global $accountsTreeDAO;


    $itr = filter_input(INPUT_POST, 'itr');
    $isOpeningEntry = (int) filter_input(INPUT_POST, 'isOpeningEntry');

    $totalFrom = filter_input(INPUT_POST, 'totalValueFrom_hidden');
    $totalTo = filter_input(INPUT_POST, 'totalValueTo_hidden');

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



    $dailyEntry->totalcreditor = $totalTo; //الى دائن
    $dailyEntry->totaldebtor = $totalFrom; // من مدين
    $dailyEntry->branchid = $branchid_entry;
    $dailyEntry->isopeningentry = $isOpeningEntry;
    $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 = 0;

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

    #collect $AllDailyEntryDebtor,$AllDailyEntryCreditor
    $AllDailyEntryDebtor = $AllDailyEntryCreditor = array();
    //1-from// من مدين
    for ($i = 1; $i <= $itr; $i++) {
        $valueFrom = filter_input(INPUT_POST, 'valueFrom' . $i);
        $valueTo = filter_input(INPUT_POST, 'valueTo' . $i);
        $parent = filter_input(INPUT_POST, 'E_parent' . $i);
        $comment = filter_input(INPUT_POST, 'comment' . $i);
        $costcenterid = -1; //filter_input(INPUT_POST, 'costcenterid' . $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;
                array_push($AllDailyEntryDebtor, $dailyEntryDebtor);
            }
            if (!empty($valueTo)) {
                //2-to//الى دائن
                $dailyEntryCreditor->accountstreeid = $parent;
                $dailyEntryCreditor->value = $valueTo;
                $dailyEntryCreditor->dailyentryid = $dailyEntryId;
                $dailyEntryCreditor->dComment = $comment;
                $dailyEntryCreditor->costcenterid = $costcenterid;

                array_push($AllDailyEntryCreditor, $dailyEntryCreditor);
            }
        }
    }
    //1-from// من مدين
    for ($i = 1; $i <= $itr; $i++) {
        $valueFrom = filter_input(INPUT_POST, 'valueFrom' . $i);
        $valueTo = filter_input(INPUT_POST, 'valueTo' . $i);
        $parent = filter_input(INPUT_POST, 'E_parent' . $i);
        $comment = filter_input(INPUT_POST, 'comment' . $i);
        $costcenterid = -1; //filter_input(INPUT_POST, 'costcenterid' . $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", $dailyEntryDebtor->costcenterid, $parent, 0, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
            }
            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", $dailyEntryCreditor->costcenterid, $parent, 1, $dailyEntry, $AllDailyEntryDebtor, $AllDailyEntryCreditor);
            }
        }
    }

    return $dailyEntryId;
}

function add_old() {
    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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


    $fromCount = filter_input(INPUT_POST, 'fromCount');
    $toCount = filter_input(INPUT_POST, 'toCount');

    $totalFrom = filter_input(INPUT_POST, 'totalValueFrom_hidden');
    $totalTo = filter_input(INPUT_POST, 'totalValueTo_hidden');

    $dDateTime = filter_input(INPUT_POST, 'dDateTime');
    $costcenterid = filter_input(INPUT_POST, 'costcenterid');
    $entryComment = filter_input(INPUT_POST, 'entryComment');



    $dailyEntry->totalcreditor = $totalTo; //الى دائن
    $dailyEntry->totaldebtor = $totalFrom; // من مدين
    $dailyEntry->dDateTime = $dDateTime;
    $dailyEntry->thedate = date('Y-m-d');
    $dailyEntry->userid = $_SESSION['userid'];
    $dailyEntry->condition = 0;
    $dailyEntry->reverseofid = 0;
    $dailyEntry->costcenterid = $costcenterid;
    $dailyEntry->entryComment = $entryComment;
    $dailyEntry->fromFlag = 0;
    $dailyEntryId = $dailyEntryDAO->insert($dailyEntry);

    //1-from// من مدين
    for ($i = 1; $i <= $fromCount; $i++) {
        $value = filter_input(INPUT_POST, 'valueFrom' . $i);
        $parent = filter_input(INPUT_POST, 'parentFrom' . $i);
        if (!empty($parent) && !empty($value)) {
            $dailyEntryDebtor->accountstreeid = $parent;
            $dailyEntryDebtor->value = $value;
            $dailyEntryDebtor->dailyentryid = $dailyEntryId;

            $comment = filter_input(INPUT_POST, 'commentFrom' . $i);
            $dailyEntryDebtor->dComment = $comment;

            $dailyEntryDebtorDAO->insert($dailyEntryDebtor);
            affectAccount($dailyEntryDebtor, 0);
        }
    }

    //2-to//الى دائن
    for ($i = 1; $i <= $toCount; $i++) {
        $value = filter_input(INPUT_POST, 'valueTo' . $i);
        $parent = filter_input(INPUT_POST, 'parentTo' . $i);

        if (!empty($parent) && !empty($value)) {
            $dailyEntryCreditor->accountstreeid = $parent;
            $dailyEntryCreditor->value = $value;
            $dailyEntryCreditor->dailyentryid = $dailyEntryId;

            $comment = filter_input(INPUT_POST, 'commentTo' . $i);
            $dailyEntryCreditor->dComment = $comment;

            $dailyEntryCreditorDAO->insert($dailyEntryCreditor);
            affectAccount($dailyEntryCreditor, 1);
        }
    }
}

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("dailyentryview/table.html");
}

function getlayingOrder() {
    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //to search for
    $limit = intval($_GET['page_limit']);
    //$storeid = $_REQUEST["storeid"];

    $allData = $accountsTreeEX->getlayingOrder($name);

    if (count($allData) > 0) {
        foreach ($allData as $myData) {
            $row_array['id'] = $myData->id;
            $row_array['text'] = $myData->layingOrder . ' ' . $myData->name;
            array_push($return_arr, $row_array);
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function getaccountstreeexcept() {
    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //to search for
    $limit = intval($_GET['page_limit']);
    $ids = $_GET["ids"];
    $myid = $_GET["myid"];

    //commented to allow that account used many times in the same entry
    /* /*$ids = rtrim($ids, ",");
      $idsQueryString = '';
      if (isset($ids) && !empty($ids)) {
      $idsQueryString.=' and (t.id not in (' . $ids . ') ';
      if (isset($myid) && !empty($myid)) {
      $idsQueryString.=' or id = ' . $myid . ' ) ';
      } else {
      $idsQueryString.= ' ) ';
      }
      } */
    $idsQueryString = '';
    $allData = $accountsTreeEX->getlayingOrder4($name, $idsQueryString); //getlayingOrder2

    if (count($allData) > 0) {
        foreach ($allData as $myData) {
            //$childData = $accountsTreeDAO->queryByParent($myData->id);
            //if ($myData->itemtype2 == 1 || count($childData) < 1) {
            $row_array['id'] = $myData->id;
            $row_array['text'] = $myData->layingOrder . ' ' . $myData->parentName . '/' . $myData->customName;
            array_push($return_arr, $row_array);
            //}
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function getgeneralledger() {
    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //to search for
    $limit = intval($_GET['page_limit']);

    $allData = $accountsTreeEX->getlayingOrder3($name);

    if (count($allData) > 0) {
        foreach ($allData as $myData) {
            //check for expenses for this category
            //$childData = $accountsTreeDAO->queryByParent($myData->id);
            //if (count($childData) > 0 && $myData->itemtype2 == 0) {
            if ($myData->itemtype2 == 0) {
                $row_array['id'] = $myData->id;
                $row_array['text'] = $myData->layingOrder . ' ' . $myData->customName;
                array_push($return_arr, $row_array);
            }
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

function getassistantledger() {
    global $accountsTree;
    global $accountsTreeDAO;
    global $accountsTreeEX;

    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //to search for
    $limit = intval($_GET['page_limit']);

    $allData = $accountsTreeEX->getlayingOrder3($name);

    if (count($allData) > 0) {
        foreach ($allData as $myData) {
            //check for expenses for this category
            //$childData = $accountsTreeDAO->queryByParent($myData->id);
            //if (count($childData) > 0 && $myData->itemtype2 == 0) {
            if ($myData->itemtype2 == 0) {
                //do nothing
            } else {
                $row_array['id'] = $myData->id;
                $row_array['text'] = $myData->layingOrder . ' ' . $myData->parentName . '/' . $myData->customName;
                array_push($return_arr, $row_array);
            }
        }
    }

    //echo $return_arr;
    echo json_encode($return_arr);
}

?>