<?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
include("../public/include_dao.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');
//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');
//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.class.php');
//Returnsellbilldetail
require_once('../models/dao/ReturnsellbilldetailDAO.class.php');
require_once('../models/dto/Returnsellbilldetail.class.php');
require_once('../models/mysql/ReturnsellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnsellbilldetailMySqlExtDAO.class.php');
//Sellandruternbilldetail
require_once('../models/dao/SellandruternbilldetailDAO.class.php');
require_once('../models/dto/Sellandruternbilldetail.class.php');
require_once('../models/mysql/SellandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellandruternbilldetailMySqlExtDAO.class.php');
//Expenses
require_once('../models/dao/ExpensesDAO.class.php');
require_once('../models/dto/Expense.class.php');
require_once('../models/mysql/ExpensesMySqlDAO.class.php');
require_once('../models/mysql/ext/ExpensesMySqlExtDAO.class.php');

//Income
require_once('../models/dao/IncomeDAO.class.php');
require_once('../models/dto/Income.class.php');
require_once('../models/mysql/IncomeMySqlDAO.class.php');
require_once('../models/mysql/ext/IncomeMySqlExtDAO.class.php');

//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');

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

//Salaryreport
require_once('../models/dao/SalaryreportDAO.class.php');
require_once('../models/dto/Salaryreport.class.php');
require_once('../models/mysql/SalaryreportMySqlDAO.class.php');
require_once('../models/mysql/ext/SalaryreportMySqlExtDAO.class.php');



//Bill
require_once('../models/dao/BillsDAO.class.php');
require_once('../models/dto/Bill.class.php');
require_once('../models/mysql/BillsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsMySqlExtDAO.class.php');
//Billsreturn
require_once('../models/dao/BillsreturnDAO.class.php');
require_once('../models/dto/Billsreturn.class.php');
require_once('../models/mysql/BillsreturnMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsreturnMySqlExtDAO.class.php');

//Billsproduct
require_once('../models/dao/BillsproductsDAO.class.php');
require_once('../models/dto/Billsproduct.class.php');
require_once('../models/mysql/BillsproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsproductsMySqlExtDAO.class.php');

require_once('../models/dao/RestaurantrawdestructionDAO.class.php');
require_once('../models/dto/Restaurantrawdestruction.class.php');
require_once('../models/mysql/RestaurantrawdestructionMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantrawdestructionMySqlExtDAO.class.php');
//Lastbillidspricesupdated
require_once('../models/dao/LastbillidspricesupdatedDAO.class.php');
require_once('../models/dto/Lastbillidspricesupdated.class.php');
require_once('../models/mysql/LastbillidspricesupdatedMySqlDAO.class.php');
require_once('../models/mysql/ext/LastbillidspricesupdatedMySqlExtDAO.class.php');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.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');

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

//#Billsreturnproduct
require_once('../models/mysql/ext/BillsreturnproductsMySqlExtDAO.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 :- profitreportCTRL تقرير يومية الخزينة

  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
//Sellbill
$mySellbillEx = new SellbillMySqlExtDAO();
//Returnsellbill
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();
//Sellbillandrutern
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
$sellBillAndRutern = new Sellbillandrutern();
//Sellbilldetail
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();
//Returnsellbilldetail
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();
//Sellandruternbilldetail
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();
$SellandruternbilldetailDAO = new SellandruternbilldetailMySqlDAO();
$sellAndRruternBillDetails = new Sellandruternbilldetail();
//Expenses
$myExpensesEx = new ExpensesMySqlExtDAO();

//Income
$myIncomesEx = new IncomeMySqlExtDAO();
//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
//Product
$myProductRecord = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();
$myProductunitRecord = new ProductunitMySqlDAO();

//Salaryreport
$Salaryreport = new Salaryreport();
$SalaryreportDAO = new SalaryreportMySqlDAO();
$SalaryreportEX = new SalaryreportMySqlExtDAO();


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

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();
//billsReturn
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();


//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();

$BillsreturnproductEX = new BillsreturnproductsMySqlExtDAO();

//Restaurantrawdestruction
$restaurantRawDestruction = new Restaurantrawdestruction();
$restaurantRawDestructionDAO = new RestaurantrawdestructionMySqlDAO();
$restaurantRawDestructionEX = new RestaurantrawdestructionMySqlExtDAO();
//Lastbillidspricesupdated
$lastBillIdsPricesUpdated = new Lastbillidspricesupdated();
$lastBillIdsPricesUpdatedDAO = new LastbillidspricesupdatedMySqlDAO();
$lastBillIdsPricesUpdatedEX = new LastbillidspricesupdatedMySqlExtDAO();

//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Buyandruternbilldetail
$buyAndReturnBillDetail = new Buyandruternbilldetail();
$buyAndReturnBillDetailDAO = new BuyandruternbilldetailMySqlDAO();
$buyAndReturnBillDetailExt = new BuyandruternbilldetailMySqlExtDAO();


//Sellbilldetail
$sellbilldetail = new Sellbilldetail();
$sellbilldetailDAO = new SellbilldetailMySqlDAO();
$sellbilldetailEX = new SellbilldetailMySqlExtDAO();
//Returnsellbilldetail
$returnSellBillDetail = new Returnsellbilldetail();
$returnSellBillDetailDAO = new ReturnsellbilldetailMySqlDAO();
$returnSellBillDetailEX = new ReturnsellbilldetailMySqlExtDAO();
//Sellandruternbilldetail
$sellAndRuternBillDetail = new Sellandruternbilldetail();
$sellAndRuternBillDetailDAO = new SellandruternbilldetailMySqlDAO();
$sellAndRuternBillDetailEX = new SellandruternbilldetailMySqlExtDAO();

//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

//Breadcrumb
$breadcrumbObject = new Breadcrumb();



$lastBillIdsPricesUpdated = $lastBillIdsPricesUpdatedDAO->load(1);
if (!isset($lastBillIdsPricesUpdated->id) || empty($lastBillIdsPricesUpdated->id)) {
    $lastBillIdsPricesUpdated->buybill = 0;
    $lastBillIdsPricesUpdated->buyandret = 0;
    $lastBillIdsPricesUpdated->retbuy = 0;
    $lastBillIdsPricesUpdated->sell = 0;
    $lastBillIdsPricesUpdated->sellandret = 0;
    $lastBillIdsPricesUpdated->retsell = 0;
    $lastBillIdsPricesUpdated->buyquantity = 0;
    $lastBillIdsPricesUpdated->buyandretquantity = 0;
    $lastBillIdsPricesUpdatedDAO->insert($lastBillIdsPricesUpdated);
}
if ($lastBillIdsPricesUpdated->buybill > 0) {
    $bill = $buyBillDetailDAO->load($lastBillIdsPricesUpdated->buybill);
    $lastBillIdsPricesUpdated->buybill = $bill->buybillid;
}
if ($lastBillIdsPricesUpdated->buyandret > 0) {
    $bill = $buyAndReturnBillDetailDAO->load($lastBillIdsPricesUpdated->buyandret);
    $lastBillIdsPricesUpdated->buyandret = $bill->buybillid;
}
if ($lastBillIdsPricesUpdated->sell > 0) {
    $bill = $sellbilldetailDAO->load($lastBillIdsPricesUpdated->sell);
    $lastBillIdsPricesUpdated->sell = $bill->sellbillid;
}
if ($lastBillIdsPricesUpdated->sellandret > 0) {
    $bill = $sellAndRuternBillDetailDAO->load($lastBillIdsPricesUpdated->sellandret);
    $lastBillIdsPricesUpdated->sellandret = $bill->sellbillid;
}
if ($lastBillIdsPricesUpdated->retsell > 0) {
    $bill = $returnSellBillDetailDAO->load($lastBillIdsPricesUpdated->retsell);
    $lastBillIdsPricesUpdated->retsell = $bill->returnsellbillid;
}

if ($lastBillIdsPricesUpdated->buyquantity > 0) {
    $bill = $buyBillDetailDAO->load($lastBillIdsPricesUpdated->buyquantity);
    $lastBillIdsPricesUpdated->buyquantity = $bill->buybillid;
}
if ($lastBillIdsPricesUpdated->buyandretquantity > 0) {
    $bill = $buyAndReturnBillDetailDAO->load($lastBillIdsPricesUpdated->buyandretquantity);
    $lastBillIdsPricesUpdated->buyandretquantity = $bill->buybillid;
}
$smarty->assign('last', $lastBillIdsPricesUpdated);

$Programsetting = $ProgramsettingDAO->load(1);
$smarty->assign('programsettingsdata', $Programsetting);

$vatValue = 1 + ($Programsetting->vatValue / 100);
//check and use the condetion that suite this action
if ($do == "show" || empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");

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


    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $buyPriceType = $_POST["buyPriceType"];
    if (!isset($buyPriceType)) {
        $buyPriceType = $Programsetting->Profitevaluation;
    }




    if (empty($startDate) && empty($endDate)) {
        $startDate = $endDate = date('Y-m-d');
    }
    if (isset($startDate) && isset($endDate) && $startDate != "" && $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 {
            $endDatePrepared = $endDate . ' 23:59:59';
            $startDate = $startDate . " 00:00:00";
        }

        $message = "تقرير ارباح المده من  :" . $startDate . " الى تاريخ :" . $endDate;
        switch ($buyPriceType) {
            case "first":
                $message .= "  و الحساب بـ سعر الشراء الحقيقى";
                break;
            case "last":
                $message .= "  و الحساب بـ اخر سعر شراء";
                break;
            case "mean":
                $message .= "  و الحساب بـ متوسط سعر الشراء";
                break;
            case "last_discount":
                $message .= "  و الحساب بـ اخر سعر شراء بعد الخصم";
                break;
            case "mean_discount":
                $message .= "  و الحساب بـ متوسط سعر الشراء بعد الخصم";
                break;
            case "generalPrice":
                $message .= "  و الحساب بـ المتوسط العام ";
                break;
            case "tax":
                $message .= "  و الحساب بـ اخر سعر شراء شامل القيمة المضافة ";
                break;
            case "mean_tax":
                $message .= "  و الحساب بـ متوسط سعر الشراء شامل القيمة المضافة ";
                break;
        }
        $smarty->assign('message', $message);


        /* print_r(getTotalSellbillByDate($startDate, $endDate));
          print_r('<br>');
          print_r(getTotalAditionalSellbillByDate($startDate, $endDate)); */

        $totalSellPrice = getTotalSellbillByDate($startDate, $endDate) + getTotalAditionalSellbillByDate($startDate, $endDate);

        $sellandreturn = getTotalAditionalReturnSellbillByDate($startDate, $endDate);
        if ($sellandreturn > 0) {

            $totalReturnSellPrice = getTotalReturnSellbillByDate($startDate, $endDate) + $sellandreturn;

            //print_r('<br>'.'totalReturnSellPrice='.$totalReturnSellPrice.'<br>');
        } else {
            $totalReturnSellPrice = getTotalReturnSellbillByDate($startDate, $endDate) - ($sellandreturn);
            //print_r('totalReturnSellPricexxxxxx'.$totalReturnSellPrice.'<br>');
        }

        $totalQuantityBuyPrice = getTotalQuantityBuyPriceByDate($startDate, $endDate) + getTotalAditionalQuantityBuyPriceByDate($startDate, $endDate);

        $totalQuantityReturnBuyPrice = getTotalQuantityReturnBuyPriceByDate($startDate, $endDate) + getTotalAditionalQuantityReturnBuyPriceByDate($startDate, $endDate);

        $totalExpenses = getTotalExpensesByDate($startDate, $endDate);

        //إجمالي الايرادات
        $totalIncomes = getTotalIncomesByDate($startDate, $endDate);

        $totalsalary = gettotalsalary($startDate, $endDate);

        $totalBuyCost = $totalQuantityBuyPrice - $totalQuantityReturnBuyPrice;

        $profitFinal = ($totalSellCost - $totalBuyCost) - ($totalExpenses + $totalsalary - $totalIncomes);

        #################################################################
        ##optics part
        $opticSell = getTotalSellOpticByDate($startDate, $endDate);
        $opticReturn = getTotalReturnSellOpticByDate($startDate, $endDate);

        $totalSellPrice += $opticSell;
        $totalReturnSellPrice += $opticReturn;

        $totalSellCost += ($totalSellPrice - $totalReturnSellPrice);

        //# اجمالى المباع بسعر التكلفة
        $bills_sellcost = get_total_sellcost($startDate, $endDate);

        $total_sellcost = 0;
        foreach ($bills_sellcost as $value) {
            //# load product to get its lastbuyprice and meanbuyprice .
            $productid = $value->productid;
            $product_data = $myProductRecord->load($productid);
            switch ($buyPriceType) {
                case "first":
                    $pro_price = (float) $value->buyprice;
                    break;
                case "last":
                    $pro_price = (float) $product_data->lastbuyprice;
                    break;
                case "mean":
                    $pro_price = (float) $product_data->meanbuyprice;
                    break;
                case "last_discount":
                    $pro_price = (float) $product_data->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $pro_price = (float) $product_data->meanbuyprice_withDiscount;
                    break;
                case "tax":
                    $pro_price = (float) $product_data->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $pro_price = (float) $product_data->meanbuyprice_withTax;
                    break;
            }

            $total_sellcost += ( $value->productno * $pro_price );
        }
        $totalQuantityBuyPrice += $total_sellcost;

        //# اجمالى مردود البيع بسعر التكلفة
        $bills_return_sellcost = get_total_return_sellcost($startDate, $endDate);
        $total_return_sellcost = 0;
        foreach ($bills_return_sellcost as $value) {
            //# load product to get its lastbuyprice and meanbuyprice .
            $productid = $value->productid;
            $product_data = $myProductRecord->load($productid);

            switch ($buyPriceType) {
                case "first":
                    $pro_price = (float) $value->buyprice;
                    break;
                case "last":
                    $pro_price = (float) $product_data->lastbuyprice;
                    break;
                case "mean":
                    $pro_price = (float) $product_data->meanbuyprice;
                    break;
                case "last_discount":
                    $pro_price = (float) $product_data->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $pro_price = (float) $product_data->meanbuyprice_withDiscount;
                    break;
                default:
                    $pro_price = (float) $product_data->meanbuyprice;
                    break;
                case "tax":
                    $pro_price = (float) $product_data->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $pro_price = (float) $product_data->meanbuyprice_withTax;
                    break;
            }
            $total_return_sellcost += ( $value->productno * $pro_price );
        }
        $totalQuantityReturnBuyPrice += $total_return_sellcost;
        ##
        $restaurantRawDestruction = getRestaurantRawDestruction($startDate, $endDate, $buyPriceType);
        //# تكلفة المبيعات
        //$totalBuyCost += ( $totalQuantityBuyPrice - $totalQuantityReturnBuyPrice );
        // # مجمل الربح
        $total_profit = $totalSellCost - $totalBuyCost - $restaurantRawDestruction;



        //# صافى الربح
        //$profitFinal += $total_profit - ($totalExpenses + $totalsalary);
        $profitFinal = $total_profit - ($totalExpenses + $totalsalary - $totalIncomes);


//        خصومات العملاء من جدول clientDeptChange
        $shownData = $clientDeptChangeExt->queryPayedDeptOnlyByDate($startDate, $endDate);
        $totalDiscount = 0;
        foreach ($shownData as $data) {
            $totalDiscount += $data->discountearlyRepayment;
        }



        $smarty->assign('totalsalary', $totalsalary);
        $smarty->assign('totalSellPrice', $totalSellPrice);
        $smarty->assign('totalReturnSellPrice', $totalReturnSellPrice);
        $smarty->assign('totalQuantityBuyPrice', $totalQuantityBuyPrice);
        $smarty->assign('totalQuantityReturnBuyPrice', $totalQuantityReturnBuyPrice);
        $smarty->assign('totalExpenses', $totalExpenses);
        $smarty->assign('totalIncomes', $totalIncomes);
        $smarty->assign('totalSellCost', $totalSellCost);
        $smarty->assign('totalBuyCost', $totalBuyCost);
        $smarty->assign('profitFinal', $profitFinal);
        $smarty->assign('total_profit', $total_profit);
        $smarty->assign('restaurantRawDestruction', $restaurantRawDestruction);
        $smarty->assign('totalDiscount', $totalDiscount);
    } else {
        $smarty->assign('totalSellPrice', 0);
        $smarty->assign('totalReturnSellPrice', 0);
        $smarty->assign('totalQuantityBuyPrice', 0);
        $smarty->assign('totalQuantityReturnBuyPrice', 0);
        $smarty->assign('totalExpenses', 0);
        $smarty->assign('totalIncomes', 0);
        $smarty->assign('totalSellCost', 0);
        $smarty->assign('totalBuyCost', 0);
        $smarty->assign('profitFinal', 0);
        $smarty->assign('restaurantRawDestruction', 0);
        $smarty->assign('totalDiscount', 0);
    }


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

// get sellbillaftertotalbill from Sellbill tbl
function getTotalSellbillByDate($startDate, $endDate) {
    global $mySellbillEx;

    $totalSellbill = 0;

    $totalSellbill = $mySellbillEx->queryWithDateAndConditionsExt($startDate, $endDate);
    return $totalSellbill;
}

// get sellbillaftertotalbill from  sellbillandrutern tbl
function getTotalAditionalSellbillByDate($startDate, $endDate) {
    global $mySellbillandruternEx;
    global $mySellandruternbilldetailEx;
    //*****************************************////////////////////////////////////
    $totalSellbill = 0;

    $totalSellbill = $mySellbillandruternEx->queryWithDateAndConditionsForReturnSellBillOnly2($startDate, $endDate);

    return $totalSellbill;
}

// get returnsellbillaftertotalbill from  returnsellbill tbl
function getTotalReturnSellbillByDate($startDate, $endDate) {
    global $myReturnsellbillEx;

    $totalReturnSellbill = 0;

    $totalReturnSellbill = $myReturnsellbillEx->queryWithDateAndConditionsExt($startDate, $endDate);

    return $totalReturnSellbill;
}

// get returnsellbillaftertotalbill from  sellbillandreturn tbl
function getTotalAditionalReturnSellbillByDate($startDate, $endDate) {
    //to use the variable out side the funcion
    global $sellBillAndRutern;
    global $mySellbillandruternEx;
    global $SellandruternbilldetailDAO;
    global $sellAndRruternBillDetails;

    //*****************************************////////////////////////////////////

    $totalReturnSellbill = 0;

    $sellBillAndRuternArray = $mySellbillandruternEx->queryWithDateAndConditionsForReturnSellBillOnly22($startDate, $endDate);
    //print_r($sellBillAndRuternArray);
    if (count($sellBillAndRuternArray) > 0) {
        foreach ($sellBillAndRuternArray as $mysellBillAndRuternArray) {
            $sellAndRruternBillDetails = $SellandruternbilldetailDAO->queryBySellbillid($mysellBillAndRuternArray->sellbillid);
            foreach ($sellAndRruternBillDetails as $OneDetail) {
                if ($OneDetail->selltype == 1) {
                    $totalReturnSellbill += $OneDetail->sellbilldetailtotalprice;
                }
            }
        }
    }

    return $totalReturnSellbill;
}

// show the form by date
function getTotalQuantityBuyPriceByDate($startDate, $endDate) {
    global $mySellbilldetailEx;
    global $myProductunitRecord;
    global $myProductunitEx;
    global $Programsetting;
    global $vatValue;

    $totalQuantityBuyPrice = 0;

    $sellbilldetailData = $mySellbilldetailEx->queryWithDateAndConditionsExt($startDate, $endDate);
//print("<pre>");
//print_r($sellbilldetailData);
//print("</pre>");
    $buyPriceType = $_POST["buyPriceType"];
    if (!isset($buyPriceType)) {
        $buyPriceType = $Programsetting->Profitevaluation;
    }
    foreach ($sellbilldetailData as $sellbilldetail) {
        // $productId = $sellbilldetail->sellbilldetailproductid;
        //print_r($sellbilldetail);
        $quantity = $sellbilldetail->sellbilldetailquantity;
        $productunitId = $sellbilldetail->productunitid;
        //$buyPrice = $sellbilldetail->buyprice;
        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellbilldetail->generalPrice;
                break;
            case "tax":
                $pro_price = (float) $sellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $pro_price = (float) $sellbilldetail->meanbuyprice_withTax;
                break;
        }

        $buyDiscount = $sellbilldetail->buydiscount;
        $buyDiscountType = $sellbilldetail->buydiscounttype;

        //$productData = getProoductPriceByonlyProductId($productId);
        //print("buyDiscount: ".$buyDiscount."<br>");
        //print("buyDiscountType: ".$buyDiscountType."<br>");

        $productnumber = $myProductunitEx->getProductNumber($productunitId);
        //print("productnumber: ".$productnumber."<br>");
        $productBuyPrice = $buyPrice;
        //k	print_r('ddddddddddddddddd'.$buyDiscountType);
        if ($buyDiscount > 0 && $buyDiscountType == 0) {

            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {


            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }
//print("productBuyPrice: ".$productBuyPrice."<br>====================================<br>");
        if ($productnumber == 0) {
            $productnumber = 1;
        }
        $productBuyPrice = $productBuyPrice * $productnumber;

        $totalQuantityBuyPrice = $totalQuantityBuyPrice + ($quantity * $productBuyPrice);


        //print("totalQuantityBuyPrice: ".$totalQuantityBuyPrice."<br>");
    }

    return $totalQuantityBuyPrice * $vatValue;
}

// show the form by date
function getTotalAditionalQuantityBuyPriceByDate($startDate, $endDate) {
    global $mySellandruternbilldetailEx;
    global $myProductunitRecord;
    global $myProductunitEx;
    global $Programsetting;
    global $vatValue;


    $totalQuantityBuyPrice = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeExt($startDate, $endDate, 0);

    $buyPriceType = $_POST["buyPriceType"];
    if (!isset($buyPriceType)) {
        $buyPriceType = $Programsetting->Profitevaluation;
    }
    foreach ($sellandreturndetailData as $sellandreturndetail) {
        //$productId = $sellandreturndetail->sellbilldetailproductid;
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $productunitId = $sellandreturndetail->productunitid;
        //$buyPrice = $sellandreturndetail->buyprice;
        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellandreturndetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellandreturndetail->generalPrice;
                break;
            case "tax":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $sellandreturndetail->buydiscount;
        $buyDiscountType = $sellandreturndetail->buydiscounttype;


        //$productData = getProoductPriceByonlyProductId($productId);

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        if ($productnumber == 0) {
            $productnumber = 1;
        }


        $productBuyPrice = $productBuyPrice * $productnumber;
        $totalQuantityBuyPrice = $totalQuantityBuyPrice + ($quantity * $productBuyPrice);
    }

    return $totalQuantityBuyPrice * $vatValue;
}

function getTotalQuantityReturnBuyPriceByDate($startDate, $endDate) {
    global $myReturnsellbilldetailEx;
    global $myProductunitRecord;
    global $myProductunitEx;
    global $Programsetting;
    global $vatValue;

    $totalQuantityReturnBuyPrice = 0;

    $returnsellbilldetailData = $myReturnsellbilldetailEx->queryWithDateAndConditions($startDate, $endDate);

    $buyPriceType = $_POST["buyPriceType"];
    if (!isset($buyPriceType)) {
        $buyPriceType = $Programsetting->Profitevaluation;
    }
    foreach ($returnsellbilldetailData as $returnsellbilldetail) {
        //  $productId = $returnsellbilldetail->returnsellbilldetailproductid;
        $quantity = $returnsellbilldetail->returnsellbilldetailquantity;
        $productunitId = $returnsellbilldetail->productunitid;
        //$buyPrice = $returnsellbilldetail->buyprice;
        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $returnsellbilldetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $returnsellbilldetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $returnsellbilldetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $returnsellbilldetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $returnsellbilldetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $returnsellbilldetail->generalPrice;
                break;
            case "tax":
                $buyPrice = (float) $returnsellbilldetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyPrice = (float) $returnsellbilldetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $returnsellbilldetail->buydiscount;
        $buyDiscountType = $returnsellbilldetail->buydiscounttype;


        // $productData = getProoductPriceByonlyProductId($productId);

        $productnumber = $myProductunitEx->getProductNumber($productunitId);


        $productBuyPrice = $buyPrice;
        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        if ($productnumber == 0) {
            $productnumber = 1;
        } $productBuyPrice = $productBuyPrice * $productnumber;



        $totalQuantityReturnBuyPrice = $totalQuantityReturnBuyPrice + ($quantity * $productBuyPrice);
    }

    return $totalQuantityReturnBuyPrice * $vatValue;
}

function getTotalAditionalQuantityReturnBuyPriceByDate($startDate, $endDate) {
    global $mySellandruternbilldetailEx;
    global $myProductunitRecord;
    global $myProductunitEx;
    global $Programsetting;
    global $vatValue;

    $totalQuantityReturnBuyPrice = 0;

    $sellandreturndetailData = $mySellandruternbilldetailEx->queryWithDateAndConditionsTypeExt($startDate, $endDate, 1);

    $buyPriceType = $_POST["buyPriceType"];
    if (!isset($buyPriceType)) {
        $buyPriceType = $Programsetting->Profitevaluation;
    }
    foreach ($sellandreturndetailData as $sellandreturndetail) {
        //$productId = $sellandreturndetail->sellbilldetailproductid;
        $quantity = $sellandreturndetail->sellbilldetailquantity;
        $productunitId = $sellandreturndetail->productunitid;
        //$buyPrice = $sellandreturndetail->buyprice;
        switch ($buyPriceType) {
            case "first":
                $buyPrice = (float) $sellandreturndetail->buyprice;
                break;
            case "last":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice;
                break;
            case "mean":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice;
                break;
            case "last_discount":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $buyPrice = (float) $sellandreturndetail->generalPrice;
                break;
            case "tax":
                $buyPrice = (float) $sellandreturndetail->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $buyPrice = (float) $sellandreturndetail->meanbuyprice_withTax;
                break;
        }
        $buyDiscount = $sellandreturndetail->buydiscount;
        $buyDiscountType = $sellandreturndetail->buydiscounttype;

        // $productData = getProoductPriceByonlyProductId($productId);

        $productnumber = $myProductunitEx->getProductNumber($productunitId);

        $productBuyPrice = $buyPrice;

        if ($buyDiscount > 0 && $buyDiscountType == 0) {
            $productBuyPrice = $buyPrice - $buyDiscount;
        } elseif ($buyDiscount > 0 && $buyDiscountType == 1) {
            $productBuyPrice = $buyPrice - (($buyDiscount / 100) * $buyPrice);
        }

        if ($productnumber == 0) {
            $productnumber = 1;
        } $productBuyPrice = $productBuyPrice * $productnumber;

        $totalQuantityReturnBuyPrice = $totalQuantityReturnBuyPrice + ($quantity * $productBuyPrice);
    }

    return $totalQuantityReturnBuyPrice * $vatValue;
}

// get ProoductPrice from Prooduct tbl
function getProoductPriceByonlyProductId($productId) {
    global $myProductEx;

    // get rawmaterialprice by rawmaterialid
    $productData = $myProductEx->loadByProductId($productId);

    return $productData;
}

function getTotalExpensesByDate($startDate, $endDate) {
    global $myExpensesEx;

    $expensesValue = 0;
    $startDate = date('Y-m-d', strtotime($startDate));
    $endDate = date('Y-m-d', strtotime($endDate));
    $expensesValue = $myExpensesEx->queryWithDateAndConditionsExt($startDate, $endDate);

    return $expensesValue;
}

function gettotalsalary($startDate, $endDate) {
    global $Salaryreport;
    global $SalaryreportDAO;
    global $SalaryreportEX;

    global $Employeepersonnel;
    global $EmployeepersonnelDAO;
    global $EmployeepersonnelEX;



    $allsalary = $SalaryreportEX->queryAllbydata($startDate, $endDate);

    //   print_r($allsalary);
    $sumsalary = 0;
    foreach ($allsalary as $myallsalary) {
        $sumsalary += $myallsalary->salaryreportnet;
    }



    //print_r('sumsalary'.$sumsalary.'<br>');
    $Withdrawal = 0;
    $Borrow = 0;
    $Repayment = 0;
    $allpersonaldata = $EmployeepersonnelEX->queryAllbydateforreport($startDate, $endDate);


    //  print_r($allpersonaldata);
    foreach ($allpersonaldata as $myallpersonaldata) {

        if ($myallpersonaldata->employeepersonneltype == 4) {


            $Borrow += $myallpersonaldata->employeepersonnelvalue;
        } elseif ($myallpersonaldata->employeepersonneltype == 3) {

            $Withdrawal += $myallpersonaldata->employeepersonnelvalue;
        } elseif ($myallpersonaldata->employeepersonneltype == 6) {

            $Repayment += $myallpersonaldata->employeepersonnelvalue;
        }
    }


    /* print_r('Withdrawal'.$Withdrawal.'<br>');
      print_r('Borrow'.$Borrow.'<br>');
      print_r('Repayment'.$Repayment.'<br>'); */

    $allfinal = ($sumsalary + $Withdrawal + $Borrow) - $Repayment;


    return $allfinal;
    // print_r('allfinal'.$allfinal.'<br>');
}

function getTotalSellOpticByDate($startDate, $endDate) {
    global $billsEX;

    $totalSellbill = 0;
    $totalSellbill = $billsEX->queryWithDateAndConditionsExt($startDate, $endDate);
    return $totalSellbill;
}

function getTotalReturnSellOpticByDate($startDate, $endDate) {
    global $billsReturnEX;

    $totalReturnSellbill = 0;
    $totalReturnSellbill = $billsReturnEX->queryWithDateAndConditionsExt($startDate, $endDate);
    return $totalReturnSellbill;
}

function get_total_sellcost($startDate, $endDate) {

    global $billsProductsEX;

    $total_sellcost = $billsProductsEX->get_total_sellcost($startDate, $endDate);

    return $total_sellcost;
}

function get_total_return_sellcost($startDate, $endDate) {

    global $BillsreturnproductEX;

    $total_return_sellcost = $BillsreturnproductEX->get_total_return_sellcost($startDate, $endDate);

    return $total_return_sellcost;
}

function getRestaurantRawDestruction($startDate, $endDate, $buyPriceType) {
    global $restaurantRawDestructionEX;
    $restaurantRawDestruction = $restaurantRawDestructionEX->queryBySysdateBetween($startDate, $endDate);
    $rawDestructionCost = 0;
    foreach ($restaurantRawDestruction as $value) {
        switch ($buyPriceType) {
            case 'first':
                $rawDestructionCost += $value->productBuyPrice * $value->quantity;
                break;
            case 'last':
                $rawDestructionCost += $value->lastbuyprice * $value->quantity;
                break;
            case "last_discount":
                $rawDestructionCost += $value->lastbuyprice_withDiscount * $value->quantity;
                break;
            case "mean_discount":
                $rawDestructionCost += $value->meanbuyprice_withDiscount * $value->quantity;
                break;
            case "tax":
                $rawDestructionCost += $value->lastbuyprice_withTax * $value->quantity;
                break;
            case "mean_tax":
                $rawDestructionCost += $value->meanbuyprice_withTax * $value->quantity;
                break;
            default:
                $rawDestructionCost += $value->meanbuyprice * $value->quantity;
                break;
        }
    }
    return $rawDestructionCost;
}

function getTotalIncomesByDate($startDate, $endDate) {
    global $myIncomesEx;

    $incomesValue = 0;
    $startDate = date('Y-m-d', strtotime($startDate));
    $endDate = date('Y-m-d', strtotime($endDate));
    $incomesValue = $myIncomesEx->queryWithDateAndConditionsExt($startDate, $endDate);

    return $incomesValue;
}

?>