<?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 = $Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);
if ($do == "show" || empty($do)) {

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

    // here the function that do the action
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);


    ##search parameters
    $clientId = (int) $_REQUEST['client'];
    $showWhat = (int) $_REQUEST['showWhat'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];
    if (empty($from) && empty($to)) {
        $from = $to = date('Y-m-d');
    }

    $message = '';
    $querySrtingBuy = '';
    $querySrtingRetBuy = '';
    $queryStringPayments = '';
    $queryStringDebtChange = '';
    if ($clientId > 0) {
        $clientData = $clientDAO->load($clientId);
        $message .= "عميل:$clientData->clientname  ";
        $querySrtingBuy .= " and buybill.client = $clientId ";
        $querySrtingRetBuy .= " and returnbuybill.client = $clientId ";
        $queryStringPayments .= " and clientdebtchange.clientid = $clientId ";
        $queryStringDebtChange .= " and clientdebtchange.clientid = $clientId ";


        if (!empty($from)) {
            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
                $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
            } else {
                $from = $from . " 00:00:00";
            }
            $message .= " من:$from ";
            $querySrtingBuy .= " and buybill.buybilldate >= '" . $from . "' ";
            $querySrtingRetBuy .= " and returnbuybill.returnbuybilldate >= '" . $from . "' ";
            $queryStringPayments .= ' and clientdebtchange.clientdebtchangedate >= "' . $from . '" ';
            $queryStringPayments .= ' and savedaily.savedailydate >= "' . $from . '" ';
            $queryStringDebtChange .= ' and clientdebtchange.clientdebtchangedate >= "' . $from . '" ';
        }
        if (!empty($to)) {
            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
                $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            } else {
                $to = $to . ' 23:59:59';
            }
            $message .= " الى:$to ";
            $querySrtingBuy .= " and buybill.buybilldate <= '" . $to . "' ";
            $querySrtingRetBuy .= " and returnbuybill.returnbuybilldate <= '" . $to . "' ";
            $queryStringPayments .= ' and clientdebtchange.clientdebtchangedate <= "' . $to . '" ';
            $queryStringPayments .= ' and savedaily.savedailydate <= "' . $to . '" ';
            $queryStringDebtChange .= ' and clientdebtchange.clientdebtchangedate <= "' . $to . '" ';
        }


        ########################################################################
        ##now get data
        ########################################################################
        $buyBillData = R::getAll('select buybillid,buybilldate,buybillaftertotalbill from buybill where conditions=0 ' . $querySrtingBuy);
        $retBuyBillData = R::getAll('select returnbuybillid,returnbuybilldate,returnbuybillaftertotalbill from returnbuybill where conditions=0 ' . $querySrtingRetBuy);
        ##bill details
        /* list($billIDs) = [[]];
          foreach ($buyBillData as $value) {
          $billIDs[] = $value['buybillid'];
          }
          $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
          $buyBillDetail = R::getAll('SELECT *
          FROM buybilldetail
          where buybillid in(' . implode(',', $billIDs) . ')'); //-- order by buybilldetail.buybilldetailproductid
          list($productIDsArr, $productUnitIDsArr, $productCatIdsArr) = [[], [], []];
          foreach ($buyBillDetail as $value) {
          $productIDsArr[] = (int) $value['buybilldetailproductid'];
          $productUnitIDsArr[] = (int) $value['productunitid'];
          }
          $productIDsArr = !empty($productIDsArr) ? array_unique($productIDsArr) : [0];
          $productUnitIDsArr = !empty($productUnitIDsArr) ? array_unique($productUnitIDsArr) : [0];
          $productIdsArrAll = array_merge($productIdsArrAll, $productIDsArr);
          //2- products
          $productDataArr = R::getAll('select productId,product.productName as productName,product.productCatId,logo,productBuyPrice,lastbuyprice,meanbuyprice,lastbuyprice_withDiscount,meanbuyprice_withDiscount,overAllAveragePrice,lastbuyprice_withTax,meanbuyprice_withTax
          from product where productId in(' . implode(',', $productIDsArr) . ') ');
          $productDataArr = customArrayIndexOne($productDataArr, 'productId');
          foreach ($productDataArr as $value) {
          $productCatIdsArr[] = $value['productCatId'];
          }
          $productCatIdsArr = !empty($productCatIdsArr) ? array_unique($productCatIdsArr) : [0];
          //3- cat,units
          $productCatDataArr = R::getAll('select productCatId,productCatName from productcat where productCatId in(' . implode(',', $productCatIdsArr) . ') ');
          $productCatDataArr = customArrayIndexOne($productCatDataArr, 'productCatId');
          $productUnitDataArr = R::getAll('select productunitid,unit.unitId as unitid,unit.unitName as unitName
          from productunit
          join unit on unit.unitId = productunit.unitid
          where productunitid in(' . implode(',', $productUnitIDsArr) . ') ');
          $productUnitDataArr = customArrayIndexOne($productUnitDataArr, 'productunitid');
          foreach ($buyBillDetail as $value) {
          $value['productName'] = $productDataArr[$value['buybilldetailproductid']]['productName'];
          $catid = $productDataArr[$value['buybilldetailproductid']]['productCatId'];
          $value['productCatName'] = $productCatDataArr[$catid]['productCatName'];
          $value['unitName'] = $productUnitDataArr[$value['productunitid']]['unitName'];
          }
          $buyBillDetail = customArrayIndexMany($buyBillDetail, 'buybillid');
          $smarty->assign('buyBillDetail', $buyBillDetail);
          ############################################################################
          ##فاتورة مردود المشتريات
          list($billIDs) = [[]];
          foreach ($retBuyBillData as $value) {
          $billIDs[] = $value['returnbuybillid'];
          }
          $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
          //1- bill details
          $buyBillDetail = R::getAll('SELECT *
          FROM returnbuybilldetail
          where returnbuybillid in(' . implode(',', $billIDs) . ')'); //-- order by buybilldetail.buybilldetailproductid
          $buyBillDataTemp = array();
          list($productIDsArr, $productUnitIDsArr, $productCatIdsArr) = [[], [], []];
          foreach ($buyBillDetail as $value) {
          $productIDsArr[] = (int) $value['returnbuybilldetailproductid'];
          $productUnitIDsArr[] = (int) $value['productunitid'];
          }
          $productIDsArr = !empty($productIDsArr) ? array_unique($productIDsArr) : [0];
          $productUnitIDsArr = !empty($productUnitIDsArr) ? array_unique($productUnitIDsArr) : [0];
          $productIdsArrAll = array_merge($productIdsArrAll, $productIDsArr);
          //2- products
          $productDataArr = R::getAll('select productId,product.productName as productName,product.productCatId,logo,productBuyPrice,lastbuyprice,meanbuyprice,lastbuyprice_withDiscount,meanbuyprice_withDiscount,overAllAveragePrice,lastbuyprice_withTax,meanbuyprice_withTax
          from product where productId in(' . implode(',', $productIDsArr) . ') ');
          $productDataArr = customArrayIndexOne($productDataArr, 'productId');
          foreach ($productDataArr as $value) {
          $productCatIdsArr[] = $value['productCatId'];
          }
          $productCatIdsArr = !empty($productCatIdsArr) ? array_unique($productCatIdsArr) : [0];
          //3- cat,units
          $productCatDataArr = R::getAll('select productCatId,productCatName from productcat where productCatId in(' . implode(',', $productCatIdsArr) . ') ');
          $productCatDataArr = customArrayIndexOne($productCatDataArr, 'productCatId');
          $productUnitDataArr = R::getAll('select productunitid,unit.unitId as unitid,unit.unitName as unitName
          from productunit
          join unit on unit.unitId = productunit.unitid
          where productunitid in(' . implode(',', $productUnitIDsArr) . ') ');
          $productUnitDataArr = customArrayIndexOne($productUnitDataArr, 'productunitid');
          $buyBillDataTemp = array();

          foreach ($buyBillDetail as $value) {

          $value['productName'] = $productDataArr[$value['returnbuybilldetailproductid']]['productName'];
          $catid = $productDataArr[$value['returnbuybilldetailproductid']]['productCatId'];
          $value['productCatName'] = $productCatDataArr[$catid]['productCatName'];
          $value['unitName'] = $productUnitDataArr[$value['productunitid']]['unitName'];
          }
          $buyBillDetail = customArrayIndexMany($buyBillDetail, 'returnbuybillid');
          $smarty->assign('retBuyBillDetail', $buyBillDetail);
         */
        if ($showWhat == 0) {//payments only//from clientPayedDeptController.php?do=showallajax
            $paymentData = R::getAll("select clientdebtchangeid,paySerialNo,clientdebtchangedate,clientdebtchangebefore,clientdebtchangeamount,clientdebtchangeafter,clientdebtchangetype,del,clientdebtchange.dailyentryid,clientdebtchange.tablename,clientdebtchangemodelid,paytype
                    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' )
                )" . $queryStringPayments);
        } else if ($showWhat == 1) {//all moves //from clientReportsController.php?do=show
            $clientDebtChangeData = R::getAll('SELECT clientdebtchange.* , CONCAT(`tablename`,`clientdebtchangemodelid`,clientdebtchangeamount,`clientdebtchangetype`) AS finalstring
		FROM clientdebtchange
                where 1
		 ' . $queryStringDebtChange . '
		order by clientdebtchangedate desc');
            $ii = 0;
            //select all data from storemovement
            $startvalue = 0;
            $startbefore = 0;
            $startafter = 0;
            $clientDebtChange = $clientDebtChangeData;
            $clientDebtChangeData = array();
//            if ($bure == "1") {
            foreach ($clientDebtChange as $mov) {
                $mov['processname'] = str_replace("(معدله)", "", $mov['processname']);
                if ($ii == 0) {
                    $startvalue = $mov['clientdebtchangeamount'];
                    $mov['clientdebtchangeamount'] = $startvalue;
                    $startbefore = $mov['clientdebtchangebefore'];
                    $mov['clientdebtchangebefore'] = $startbefore;
                    $startafter = $mov['clientdebtchangeafter'];
                    $mov['clientdebtchangeafter'] = $startafter;
                } else {
                    $startvalue = $mov['clientdebtchangeamount'];
                    $mov['clientdebtchangeafter'] = $startbefore;
                    if ($mov['clientdebtchangetype'] == "1") {
                        $mov['clientdebtchangebefore'] = $startbefore + $startvalue;
                        $startbefore = $startbefore + $startvalue;
                    } else {
                        $mov['clientdebtchangebefore'] = $startbefore - $startvalue;
                        $startbefore = $startbefore - $startvalue;
                    }
                }
                $ii++;
                array_push($clientDebtChangeData, $mov);
            }
//            }
        }
    }
    $smarty->assign('message', $message);
    $smarty->assign('showWhat', $showWhat);
    $smarty->assign('buyBillData', $buyBillData);
    $smarty->assign('retBuyBillData', $retBuyBillData);
    $smarty->assign('paymentData', $paymentData);
    $smarty->assign('clientDebtChangeData', $clientDebtChangeData);





    //here the smarty templates
    $smarty->display("clientbuysview/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
  ================================ */
?>