<?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");


//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.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');

//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');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');


//Returnsellbill
require_once('../models/dao/ReturnsellbillDAO.class.php');
require_once('../models/dto/Returnsellbill.class.php');
require_once('../models/mysql/ReturnsellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbillMySqlExtDAO.class.php');

//Sellbillandrutern
require_once('../models/dao/SellbillandruternDAO.class.php');
require_once('../models/dto/Sellbillandrutern.class.php');
require_once('../models/mysql/SellbillandruternMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillandruternMySqlExtDAO.class.php');

//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');


//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');

//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');

//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');

// EmployeepersonnelDAO
require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.class.php');

require_once('../models/dao/EmployeepersonnelDAO.class.php');
require_once('../models/dto/Employeepersonnel.class.php');
require_once('../models/mysql/EmployeepersonnelMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeepersonnelMySqlExtDAO.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 :- SavedailyCTRL تقرير يومية الخزينة

  OPERTATION in Controller

  1-load save data
  2-display show form
  3-display details form for save
  4-display details for operation in savedaily

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


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


//here goes the instances and general variables
//Expenses
$ExpenseDAO = new ExpensesMySqlDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();

//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();

//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();

$myPartnerwithdrawalEx = new PartnerwithdrawalMySqlExtDAO();
//Sellbill
$sellBillDAO = new SellbillMySqlDAO();
$sellBillExt = new SellbillMySqlExtDAO();

$empDao = new EmployeeMySqlDAO();
$emp = new Employee();
$empEX = new EmployeeMySqlExtDAO();

$EmployeepersonnelDAO = new EmployeepersonnelMySqlDAO();
$Employeepersonnel = new Employeepersonnel();
$EmployeepersonnelEX = new EmployeepersonnelMySqlExtDAO();

//Returnsellbill
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillExt = new ReturnsellbillMySqlExtDAO();
//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
//$buyBillDAO->load();
$buyBillExt = new BuybillMySqlExtDAO();

//return bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();


//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();

$mySaveRecord = new SaveMySqlDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

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

//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();
//Breadcrumb
$breadcrumbObject = new Breadcrumb();

$usergroupID = $_SESSION['usergroupid'];


$usergroupdata = $UsergroupDAO->load($usergroupID);
$smarty->assign("savedailydate", $usergroupdata->savedailydate);



$smarty->assign("searchinonesave", $_SESSION['searchinonesave']);
//print_r($usergroupdata);
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//check and use the condetion that suite this action
$Programsetting = $ProgramsettingDAO->load(1);
if ($do == "show" || empty($do)) {

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


    // here the function that do the action
    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

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


    $saveId = $_REQUEST['saveid'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];

    /////////////////////////////////////////nooooooooooooooooooooor//////////////////////////////////////////////
    if (!empty($startDate) && !empty($endDate)) {
        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
            $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
            $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
        } else {
            $endDate = $endDate . ' 23:59:59';
            $startDate = $startDate . " 00:00:00";
        }

        $mysavedata = $mySaveRecord->load($saveId);

        $message = "تقرير يوميه  " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);



        search($saveId, $startDate, $endDate);

        // $sumValue=sumCreditById($saveId);
    } elseif (isset($saveId) && $saveId != '-1' && empty($startDate) && empty($endDate)) {
        $mysavedata = $mySaveRecord->load($saveId);

        $message = "تقرير يوميه  " . $mysavedata->savename;
        $smarty->assign('message', $message);



        search($saveId);
    } else {
        $saveId = $_SESSION['saveid'];
        //$startDate = date("Y-m-d");
        //$endDate = date("Y-m-d");
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        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
            $endDate = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($endDate)));
            $startDate = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($startDate)));
        } else {
            $endDate = $endDate . ' 23:59:59';
            $startDate = $startDate . " 00:00:00";
        }

        $mysavedata = $mySaveRecord->load($saveId);

        $message = "تقرير يوميه  " . $mysavedata->savename . "  من  " . $startDate . "  الى  " . $endDate;
        $smarty->assign('message', $message);


        search($saveId, $startDate, $endDate);

        // $sumValue=sumCreditById($saveId);
    }

    //breadcrumb
    $breadcrumbObject->add('الادارة><a href="cashflowsController.php">التقارير</a> >تقرير يوميه يوم', 'cashflowsController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);



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

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

    //here the smarty templates

    $smarty->display("error.html");
}






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

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

//select all save data
function loadSave() {

    //to use the variable out side the funcion
    global $mySaveRecord;

    //load all save data
    $saveData = $mySaveRecord->queryByConditions(0);

    return $saveData;
}

///////////////////////select process////////////
function loadprocess() {
    global $mySavedailyEx;

    $allprocess = $mySavedailyEx->queryAllPROCESS();
    return $allprocess;
}

///////////////////////save currentvalue////////////////////////////////////
function sumCredit() {
    global $mySaveRecord;

    //select all data from save tbl
    $saveData = $mySaveRecord->queryByConditions(0);

    //get the sum of value
    $sumValue = 0;
    foreach ($saveData as $save) {
        $savecurrentValue = $save->savecurrentvalue;


        $sumValue += $savecurrentValue;
    }

    return $sumValue;
}

function sumCreditById($id) {
    //to use the variable out side the funcion
    global $mySaveRecord;

    //load data from save tbl by id
    $saveData = $mySaveRecord->load($id);


    //get the sum of value in save
    $savecurrentValue = $saveData->savecurrentvalue;
    $sumValue = $savecurrentValue;

    return $sumValue;
}

//load savedaily detail
function showDetail() {
    //to use the variable out side the funcion
    global $mySavedailyEx;

    //get variable
    $savedailyid = $_GET['savedailyid'];

    //load savedaily data by id
    $savedailyDetail = $mySavedailyEx->queryAllBysavedailyid($savedailyid);

    return $savedailyDetail;
}

///////////////////////////////////////////////nooooooooooooooor///////////////////////////
function search($saveId, $startDate, $endDate) {
    global $mySavedailyRecord;
    global $mySavedailyEx;
    global $mySaveRecord;
    global $clientDAO;
    global $supplierDAO;
    global $supplierExt;
    global $clientDeptChangeExt;

    global $buyAndReturnBillExt;
    global $buyBillExt;
    global $returnBuyBillExt;


    global $sellBillExt;
    global $returnSellBillExt;
    global $mySellbillandruternEx;
    global $myPartnerwithdrawalEx;
    global $ExpenseDAO;
    global $billsEX;
    global $billsReturnEX;
    global $billsReturnDAO;
    global $smarty;
    global $queryString;
    global $empDao;
    global $EmployeepersonnelDAO;




    $bure = $_POST["bure"];

    $queryString = ' WHERE';

    if (isset($saveId) && $saveId != '-1') {
        $mysavedata = $mySaveRecord->load($saveId);
        $message = "تقرير يوميه   " . $mysavedata->savename;
        $smarty->assign('message', $message);

        $sumValue = sumCreditById($saveId);
        $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
    } else {

        $sumValue = sumCredit();
    }



    if (!empty($startDate) && !empty($endDate)) {

        /*  $date = strtotime($endDate);
          $date = strtotime("+1 day", $date);
          $afteroneday=date('Y-m-d', $date);
          $savedailyData2=$mySavedailyEx->searchInAdsindex22($endDate);
         */
        $message = "تقرير يوميه للخزينه من  " . $startDate . "  الى " . $endDate;
        $smarty->assign('message', $message);

        $queryString .= ' savedaily.savedailydate >= "' . $startDate . '" AND savedaily.savedailydate <= "' . $endDate . '" AND';
        //	$sumValue=sumCredit();
        //print_r($sumValue);
    }


    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString = ' ';
        }
        //print("<br>queryString: " . $queryString . "<br>");
    }

    $savedailyData = $mySavedailyEx->searchInAdsindex11($queryString);

    //	print_r($savedailyData2);
    $changeAmountSum = 0;
    $changeAmountSumpluse = 0;
    $changeAmountminse = 0;

    foreach ($savedailyData as $data) {
        if ($data->tablename == 'bills.php' || $data->tablename == 'billsreturn.php') {
            $data->link = '' . $data->tablename . '?do=details&id=' . $data->savedailymodelid;
        } else {
            $data->link = '' . $data->tablename . '?do=editprint&id=' . $data->savedailymodelid;
        }
        //get sum for today
        if ($data->savedailychangetype == 0) {//plus
            if ($data->savedailychangeamount > 0) {
                $changeAmountSum += $data->savedailychangeamount;
                $changeAmountSumpluse += $data->savedailychangeamount;
            } else {
                $changeAmountSum -= $data->savedailychangeamount;
                $changeAmountSumpluse += $data->savedailychangeamount;
            }
        } else if ($data->savedailychangetype == 1) {//minus
            if ($data->savedailychangeamount > 0) {
                $changeAmountSum -= $data->savedailychangeamount;
                $changeAmountminse += $data->savedailychangeamount;
            } else {
                $changeAmountSum += $data->savedailychangeamount;
                $changeAmountminse -= $data->savedailychangeamount;
//                $changeAmountminse += $data->savedailychangeamount;
            }
        }



        //define table names to redirect to the right file
        $tablename = $data->tablename;

        //print_r($tablename.'<br>');


        if ($tablename == "supplierPayedDeptController.php" || $tablename == "supplierDeficitController.php" || $tablename == "supplierDeficitController.php") {
            $supplierData = $supplierExt->loadSupplierBySupplierdebtchangeId($data->savedailymodelid); //supplierdebtchangeid
            if (count($supplierData) > 0) {
                $data->personName = $supplierData->suppliername;
            }
        } elseif ($tablename == "clientPayedDeptController.php" || $tablename == "clientDeficitController.php") {
            $clientData = $clientDeptChangeExt->getClientName($data->savedailymodelid); //clientdebtchangeid
            if (count($clientData) > 0) {
                $data->personName = $clientData->clientname;
            }
        } elseif ($tablename == "returnsellbillController.php") {


            $clientData = $returnSellBillExt->loadReturnsellbillById($data->savedailymodelid); //clientdebtchangeid
            if (count($clientData) > 0) {
                $data->personName = $clientData->clientname;
            }
        } elseif ($tablename == "sellbillController.php") {


            $clientData = $sellBillExt->loadSellBillById($data->savedailymodelid); //clientdebtchangeid
            if (count($clientData) > 0) {
                $data->personName = $clientData->clientname;
            }
        } elseif ($tablename == "sellbillandruternController.php") {


            $clientData = $mySellbillandruternEx->loadSellbillandruternById($data->savedailymodelid); //clientdebtchangeid
            if (count($clientData) > 0) {
                $data->personName = $clientData->clientname;
            }
        } elseif ($tablename == "partnerwithdrawalController.php") {


            $clientData = $myPartnerwithdrawalEx->loadPartnerwithdrawalById($data->savedailymodelid);
            if (count($clientData) > 0) {
                $data->personName = $clientData->partnername;
            }
        } elseif ($tablename == "expensesController.php") {


            $clientData = $ExpenseDAO->load($data->savedailymodelid);
            if (count($clientData) > 0) {
                $data->personName = $clientData->expensesname;
            }
        } elseif ($tablename == "buyBillController.php") {
            $supplierData = $buyBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
            if (count($supplierData) > 0) {
                $data->personName = $supplierData->suppliername;
            }
        } elseif ($tablename == "buyAndReturnBillController.php") {
            $supplierData = $buyAndReturnBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
            if (count($supplierData) > 0) {
                $data->personName = $supplierData->suppliername;
            }
        } elseif ($tablename == "returnBuyBillController.php") {
            $supplierData = $returnBuyBillExt->loadExt($data->savedailymodelid); //supplierdebtchangeid
            if (count($supplierData) > 0) {
                $data->personName = $supplierData->suppliername;
            }
        } elseif ($tablename == "bills.php") {
            $billsData = $billsEX->loadExt($data->savedailymodelid); //clientdebtchangeid
            if (count($billsData) > 0) {
                $data->personName = $billsData->clientname;
            }
        } elseif ($tablename == "billsreturn.php") {
            $billsreturnData = $billsReturnDAO->load($data->savedailymodelid); //clientdebtchangeid
            $billsData = $billsEX->loadExt($billsreturnData->billid);

            if (count($billsData) > 0) {
                $data->personName = $billsData->clientname;
            }
        } elseif ($tablename == "employeePersonalController.php") {

            $employeepersonnelData = $EmployeepersonnelDAO->load($data->savedailymodelid); //clientdebtchangeid
            $empData = $empDao->load($employeepersonnelData->employeeid);

            if (count($empData) > 0) {
                $data->personName = $empData->employeeName;
            }
        } else {
            $data->personName = 0;
        }
    }
    /* 	if($bure=="1" )
      {

      $smarty->assign('burex', $bure);
      foreach($savedailyData as $data)
      {


      $finalstring=$data->finalstring;

      //	print_r($finalstring.'<br>');
      $type=$data->savedailychangetype;
      $savedailyid=$data->savedailyid;



      if($type == 1)
      {

      $otherfinal=substr_replace($finalstring ,'0',-1);

      foreach($savedailyData as $xx)
      {

      if($xx->finalstring == $otherfinal)
      {



      $xx->savedailyid = -1;
      $data->savedailyid = -1;
      }

      }

      }


      }


      }



      $ii = 0;
      //select all data from storemovement
      $startvalue =0 ;
      $startbefore=0 ;
      $startafter=0 ;
      foreach($savedailyData as $mov)
      {

      if($mov->savedailyid > 0 ){
      //if($bure=="1" && $mov->savedailyid > 0 ){


      if($ii==0)
      {

      $startvalue =$mov->savedailychangeamount;
      $mov->savedailychangeamount=$startvalue;
      $startbefore=$mov->savedailysavebefore;
      $mov->savedailysavebefore=$startbefore;
      $startafter=$mov->savedailysaveafter;
      $mov->savedailysaveafter=$startafter;
      }
      else
      {

      $startvalue = $mov->savedailychangeamount;
      $mov->savedailysaveafter	=$startbefore;

      if($mov->savedailychangetype=="1"){

      //print_r('in if<br>');
      $mov->savedailysavebefore	=$startbefore + $startvalue;
      $startbefore = $startbefore + $startvalue;
      }
      else
      {
      //print_r('in else if<br>');
      //print_r('startafter'.$startbefore .'<br>');
      //print_r('startvalue'.$startbefore .'<br>');

      //	print_r($startafter - $startvalue .'<br>');
      $mov->savedailysavebefore	=$startbefore - $startvalue;
      $startbefore = $startbefore - $startvalue;
      }


      //new product name with all path


      }





      $ii++;
      }

      }


     */
    $smarty->assign('savedailyData', $savedailyData);
    $smarty->assign('changeAmountSumpluse', $changeAmountSumpluse);
    $smarty->assign('changeAmountminse', $changeAmountminse);
    $smarty->assign('changeAmountSum', $changeAmountSum);
    $smarty->assign('sumValue', $sumValue);
}

?>