<?php

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

//global varable
global $showoutside;

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

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");
//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');

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

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

  Controller Name :- saveCTRL اضافة وتعديل وعرض الخزن

  OPERTATION in Controller

  1-

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


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

//here goes the instances and general variables
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();


$Programsetting = $ProgramsettingDAO->load(1);
$smarty->assign("userId", $_SESSION['userid']);
//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
//    $expenseTypeLastLeaf = R::getAll('select expensestype.expensestypeid, expensestype.expensestypename
//            from expensestype
//            left join expensestype child on expensestype.expensestypeid = child.parent
//            where expensestype.conditions=0 and child.expensestypeid is Null');
    $startDate = $_POST['from'];
    $endDate = $_POST['to'];
    $expensetypeid = (int) $_POST['expensetypeid'];
    if (empty($startDate) && !empty($endDate))
        $startDate = date('Y-m-d');
    if (empty($endDate) && !empty($startDate))
        $endDate = date('Y-m-d');
    if (empty($startDate) && empty($endDate)) {
        $startDate = $endDate = $today = date('Y-m-d');
        $yesterday = date("Y-m-d", strtotime('-1 days'));
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $endToday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            $startToday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($today)));
            //
            $endYesterday = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
            $startYesterday = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($yesterday)));
        } else {
            $endToday = $today . ' 23:59:59';
            $startToday = $today . " 00:00:00";
            //
            $endYesterday = $today . ' 23:59:59';
            $startYesterday = $today . " 00:00:00";
        }
        if (date('H') < $Programsetting->reportsPlusHours) {
            $startDate = $startYesterday;
            $endDate = $endYesterday;
        } else {
            $startDate = $startToday;
            $endDate = $endToday;
        }
    } else {
        $startDate = $startDate . ' 00:00:00';
        $endDate = $endDate . ' 23:59:59';
    }
    $message = "من تاريخ:$startDate  الى تاريخ:$endDate";
    $smarty->assign('message', $message);
    $smarty->assign('expenseTypeLastLeaf', $expenseTypeLastLeaf);

    $rightArr = array();
    $leftArr = array();
    $netSaveVal = 0;
    $netBankVal = 0;

    ## 1 right //رصيد سابق بالبنوك
    $BanksFirstPeriodVal = 0;
    foreach (R::getAll('select accountid from bankaccount where conditions=0') as $value) {
        $BanksFirstPeriodVal += (float) R::getCell('select accountmovementbefore from accountmovement where accountmovementmodelid=' . $value['accountid'] . ' and accountmovementdate<"' . $startDate . '" order by accountmovementid desc limit 1');
    }
    $obj = new stdClass();
    $obj->name = 'رصيد سابق بالبنوك';
    $obj->val = (float) $BanksFirstPeriodVal;
    array_push($rightArr, $obj);
    $netBankVal += $obj->val;
    ## 2 right //رصيد سابق بالخزينه الشركه
    $saveFirstPeriodVal = 0;
    foreach (R::getAll('select saveid from save where conditions=0') as $value) {
        $saveFirstPeriodVal += (float) R::getCell('select savedailysavebefore from savedaily where saveid=' . $value['saveid'] . ' and savedailydate<"' . $startDate . '" order by savedailyid desc limit 1');
    }
    $obj = new stdClass();
    $obj->name = 'رصيد سابق بالخزينه';
    $obj->val = (float) $saveFirstPeriodVal;
    array_push($rightArr, $obj);
    $netSaveVal += $obj->val;
    ## 3 right //تحصيلات اليوم نقدا//نقدى من الفاتوره
    $billPaymentVal = R::getCell('select sum(sellbilltotalpayed) from sellbill where conditions=0 and sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <=  "' . $endDate . '"');
    $obj = new stdClass();
    $obj->name = 'تحصيلات اليوم نقدا';
    $obj->val = (float) $billPaymentVal;
    array_push($rightArr, $obj);
    $netSaveVal += $obj->val;
    ## 4 right //تحصيلات اليوم اجل//تحصيل او شيكات مؤجله عميل بس كله على خزنه
    $clientPayedDept = R::getCell('select sum(clientdebtchangeamount)
        from clientdebtchange
        JOIN savedaily on (
            (savedaily.savedailymodelid = clientdebtchange.clientdebtchangeid AND savedaily.tablename in("premiumController.php","clientPayedDeptController.php") )
            or
            ( savedaily.savedailymodelid = clientdebtchange.clientdebtchangemodelid AND savedaily.tablename = "clientPayedDeptSellBillsController.php" )
        )
        where clientdebtchangedate >= "' . $startDate . '" and clientdebtchangedate <=  "' . $endDate . '" ');
    $datedCheckedSaveClient = R::getCell('select sum(checkValue) from datedchecked
        where addType = 0 and done=1
        and datedCheckedID in (select savedailymodelid from savedaily where tablename="datedCheckedController.php"  and savedailydate >= "' . $startDate . '" and savedailydate <=  "' . $endDate . '")');
    $obj = new stdClass();
    $obj->name = 'تحصيلات اليوم اجل';
    $obj->val = $clientPayedDept + $datedCheckedSaveClient;
    array_push($rightArr, $obj);
    $netSaveVal += $obj->val;
    ## 5 right //تحصيلات العملاء عن طريق البنوك//تحصيل شيكات مؤجله و شيكات ايداع بس كله على بنك
    $checkdepositVal = R::getCell('select sum(checkdepositamount) from checkdeposit where conditions=0 and checkdepositdate >= "' . $startDate . '" and checkdepositdate <=  "' . $endDate . '"');
    $datedCheckedBankClient = R::getCell('select sum(checkValue) from datedchecked
        where addType = 0 and done=1
        and datedCheckedID in (select accountmovementmodelid from accountmovement where tablename="datedCheckedController.php" and accountmovementdate >= "' . $startDate . '" and accountmovementdate <=  "' . $endDate . '")');
    $obj = new stdClass();
    $obj->name = 'تحصيلات العملاء عن طريق البنوك';
    $obj->val = $checkdepositVal + $datedCheckedBankClient;
    array_push($rightArr, $obj);
    $netBankVal += $obj->val;

    /*     * -------------- *       */
    ## 1 left //مدفوعات الى الموردين من خزينه الشركه//دفعات من الخزنه و شيكات مؤجله موردين تم تسديدها على خزنة
    $supplierPayedDept = R::getCell('select sum(supplierdebtchangeamount)
        from supplierdebtchange
        JOIN savedaily on (savedaily.savedailymodelid = supplierdebtchange.supplierdebtchangeid and savedaily.tablename="supplierPayedDeptController.php")
        where supplierdebtchangedate >= "' . $startDate . '" and supplierdebtchangedate <=  "' . $endDate . '" ');
    $datedCheckedSaveSupplier = R::getCell('select sum(checkValue) from datedchecked
        where addType = 1 and done=1
        and datedCheckedID in (select savedailymodelid from savedaily where tablename="datedCheckedController.php"  and savedailydate >= "' . $startDate . '" and savedailydate <=  "' . $endDate . '")');
    $obj = new stdClass();
    $obj->name = 'مدفوعات الى الموردين من خزينه الشركه';
    $obj->val = $supplierPayedDept + $datedCheckedSaveSupplier;
    array_push($leftArr, $obj);
    $netSaveVal -= $obj->val;
    ## 2 left //مدفوعات الى الموردين عن طريق البنوك//دفعات على الموردين عن طريق البنك و شيكات مؤجله موردين تم تسديدها على بنك و المسحوبات اللى فيها مورد
    $checkwithdrawalamountVal = R::getCell('select sum(checkwithdrawalamount) from checkwithdrawal where conditions=0 and checkwithdrawaldate >= "' . $startDate . '" and checkwithdrawaldate <=  "' . $endDate . '"');
    $datedCheckedBankSupplier = R::getCell('select sum(checkValue) from datedchecked
        where addType = 1 and done=1
        and datedCheckedID in (select accountmovementmodelid from accountmovement where tablename="datedCheckedController.php" and accountmovementdate >= "' . $startDate . '" and accountmovementdate <=  "' . $endDate . '")');
    $obj = new stdClass();
    $obj->name = 'مدفوعات الى الموردين عن طريق البنوك';
    $obj->val = $checkwithdrawalamountVal + $datedCheckedBankSupplier;
    array_push($leftArr, $obj);
    $netBankVal -= $obj->val;
    ## 3 to n left//كل المصروفات على نوع مصروف اللى مختاره
    $expenses = R::getAll('select expensesname,expensesValue from expenses where expensestypeid=' . $expensetypeid);
    foreach ($expenses as $value) {
        $obj = new stdClass();
        $obj->name = $value['expensesname'];
        $obj->val = (float) $value['expensesValue'];
        array_push($leftArr, $obj);
        $netSaveVal -= $obj->val;
    }
    ## 4 left //مصروفات الخزنه
    $saveOutMoney = R::getCell('select sum(savedailychangeamount) from  (
            select savedailychangeamount,savedailychangetype from savedaily where 1 and savedailydate >= "' . $startDate . '" and savedailydate <=  "' . $endDate . '"
            GROUP BY savedailymodelid,tablename
            HAVING COUNT(*) = 1
      ) as ttt  where savedailychangetype=1 ');
    $obj = new stdClass();
    $obj->name = 'مصروفات الخزن';
    $obj->val = (float) $saveOutMoney;
    array_push($leftArr, $obj);
    $netSaveVal -= $obj->val;
    ## 5 left //مصروفات البنك
    $bankOutMoney = R::getCell('select sum(accountmovementamount) from  (
            select accountmovementamount,accountmovementtype from accountmovement where 1 and accountmovementdate >= "' . $startDate . '" and accountmovementdate <=  "' . $endDate . '"
            GROUP BY accountmovementmodelid,tablename
            HAVING COUNT(*) = 1
      ) as ttt  where accountmovementtype=1 ');
    $obj = new stdClass();
    $obj->name = 'مصروفات البنك';
    $obj->val = (float) $bankOutMoney;
    array_push($leftArr, $obj);
    $netSaveVal -= $obj->val;
    ## 7 left //تحويلات من خزينة الشركه الى البنك
    $cashtransferSaveToBank = R::getCell('select sum(cashtransferamount) from cashtransfer where type=2 and conditions=0 and cashtransferdate >= "' . $startDate . '" and cashtransferdate <=  "' . $endDate . '"');
    $cashtransferBankToSave = R::getCell('select sum(cashtransferamount) from cashtransfer where type=1 and conditions=0 and cashtransferdate >= "' . $startDate . '" and cashtransferdate <=  "' . $endDate . '"');
    $cashTransferNet = $cashtransferSaveToBank - $cashtransferBankToSave;
    $obj = new stdClass();
    $obj->name = 'تحويلات من خزينة الشركه الى البنك';
    $obj->val = (float) $cashTransferNet;
    array_push($leftArr, $obj);
    $netSaveVal -= $obj->val;
    $netBankVal += $obj->val;


    $smarty->assign('netSaveVal', $netSaveVal);
    $smarty->assign('netBankVal', $netBankVal);
    ## make equal count for left and right
    $countRight = count($rightArr);
    $countLeft = count($leftArr);
    $diff = abs($countRight - $countLeft);
    if ($countRight > $countLeft) {
        for ($i = 1; $i < $diff; $i++) {
            $obj = new stdClass();
            $obj->name = '';
            $obj->val = '';
            array_push($leftArr, $obj);
        }
    } else {
        for ($i = 1; $i < $diff; $i++) {
            $obj = new stdClass();
            $obj->name = '';
            $obj->val = '';
            array_push($rightArr, $obj);
        }
    }

    $smarty->assign('rightArr', $rightArr);
    $smarty->assign('leftArr', $leftArr);
    $smarty->assign('count', count($leftArr)); //now they have same count
    #####################
    ##net sales
    $totalSellVal = R::getCell('select sum(sellbillaftertotalbill) from sellbill where conditions=0 and sellbill.sellbilldate >= "' . $startDate . '" and sellbill.sellbilldate <=  "' . $endDate . '"');
    $totalRetSellVal = R::getCell('select sum(returnsellbillaftertotalbill) from returnsellbill where conditions=0 and returnsellbill.returnsellbilldate >= "' . $startDate . '" and returnsellbill.returnsellbilldate <=  "' . $endDate . '"');
    $smarty->assign('netSales', ($totalSellVal - $totalRetSellVal));
    //here the smarty templates
    $smarty->display("mirrorReportOnCashAndBanksView/show.html");
}


$smarty->assign("customValidation", 1);
//here the global templates
$smarty->display("footer.html");
/* ===============================
  function in this CONTROLLER
  ================================ */