<?php

session_start();
ob_start();

// get the config file
include_once("../public/config.php");

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

//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');
//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');
//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');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.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');
//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');


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

//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.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');
//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');

$do = $_GET['do'];

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

  Controller Name :- storedetailCTRL تقرير مخزون اول مدة

  OPERTATION in Controller

  1-load save data
  2-display show form

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

//here the global templates
//$smarty->display("header.html");
//here goes the instances and general variables
//Lastbillidspricesupdated
$lastBillIdsPricesUpdated = new Lastbillidspricesupdated();
$lastBillIdsPricesUpdatedDAO = new LastbillidspricesupdatedMySqlDAO();

//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();
//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();
//Returnbuybill
$returnBuyBill = new Returnbuybill();
$returnBuyBillDAO = new ReturnbuybillMySqlDAO();
$returnBuyBillExt = new ReturnbuybillMySqlExtDAO();
//Returnbuybilldetail
$returnBuyBillDetail = new Returnbuybilldetail();
$returnBuyBillDetailDAO = new ReturnbuybilldetailMySqlDAO();
$returnBuyBillDetailExt = new ReturnbuybilldetailMySqlExtDAO();
//Buyandruternbill
$buyAndReturnBill = new Buyandruternbill();
$buyAndReturnBillDAO = new BuyandruternbillMySqlDAO();
$buyAndReturnBillExt = new BuyandruternbillMySqlExtDAO();
//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();
##################################
//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();
//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();

//bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();
//billsReturnproducts
$billsReturnProducts = new Billsreturnproduct();
$billsReturnProductsDAO = new BillsreturnproductsMySqlDAO();
$billsReturnProductsEX = new BillsreturnproductsMySqlExtDAO();

$storeReportEX = new StorereportMySqlExtDAO();

///////////////product///////////////
$ProductDAO = new ProductMySqlDAO();
$Product = new Product();
$ProductEX = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

//
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();



$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 ($do == "updatePricesBuyBills") {
    $allbuyBills = $buyBillDetailExt->buyOnlyAllBills($lastBillIdsPricesUpdated->buybill, $lastBillIdsPricesUpdated->buyandret);
    foreach ($allbuyBills as $billProduct) {
        fixPricesBuyBills($billProduct);
    }
    header("location:profitreportController.php");
} elseif ($do == "updatePricesSellBills") {
    $sell = $sellbilldetailEX->queryAllNotDel(" and sellbilldetailid > $lastBillIdsPricesUpdated->sell order by sellbilldetailid asc");
    foreach ($sell as $value) {
        $prices = getLastPrices($value->sellbilldetailproductid, $value->sellbilldate);
        $sellbilldetailEX->updatePrices_f("sellbilldetail", $prices->buybilldetailprice, $prices->lastbuyprice, $prices->meanbuyprice, $prices->lastbuyprice_withDiscount, $prices->meanbuyprice_withDiscount, "sellbilldetailid", $value->sellbilldetailid);
        $lastBillIdsPricesUpdated->sell = $value->sellbilldetailid;
        $lastBillIdsPricesUpdatedDAO->update($lastBillIdsPricesUpdated);
    }
    $sellAndRet = $sellAndRuternBillDetailEX->queryAllNotDel(" and sellbilldetailid > $lastBillIdsPricesUpdated->sellandret order by sellbilldetailid asc");
    foreach ($sellAndRet as $value) {
        $prices = getLastPrices($value->sellbilldetailproductid, $value->sellbilldate);
        $sellbilldetailEX->updatePrices_f("sellandruternbilldetail", $prices->buybilldetailprice, $prices->lastbuyprice, $prices->meanbuyprice, $prices->lastbuyprice_withDiscount, $prices->meanbuyprice_withDiscount, "sellbilldetailid", $value->sellbilldetailid);
        $lastBillIdsPricesUpdated->sellandret = $value->sellbilldetailid;
        $lastBillIdsPricesUpdatedDAO->update($lastBillIdsPricesUpdated);
    }
    $retSell = $returnSellBillDetailEX->queryAllNotDel(" and returnsellbilldetailid > $lastBillIdsPricesUpdated->retsell order by returnsellbilldetailid asc");
    foreach ($retSell as $value) {
        $prices = getLastPrices($value->returnsellbilldetailproductid, $value->returnsellbilldate);
        $sellbilldetailEX->updatePrices_f("returnsellbilldetail", $prices->buybilldetailprice, $prices->lastbuyprice, $prices->meanbuyprice, $prices->lastbuyprice_withDiscount, $prices->meanbuyprice_withDiscount, "returnsellbilldetailid", $value->returnsellbilldetailid);
        $lastBillIdsPricesUpdated->retsell = $value->returnsellbilldetailid;
        $lastBillIdsPricesUpdatedDAO->update($lastBillIdsPricesUpdated);
    }
    header("location:profitreportController.php");
} elseif ($do == "updateQuantityBeforeBuyBills") {
    $allbuyBills = $buyBillDetailExt->buyOnlyAllBills($lastBillIdsPricesUpdated->buyquantity, $lastBillIdsPricesUpdated->buyandretquantity, ' where quantitybefore is null');
    foreach ($allbuyBills as $billProduct) {
        fixPricesBuyBillsQuantityBefore($billProduct);
    }
    header("location:profitreportController.php");
} elseif ($do == "updatePricesBuyBillsAllProducts") {
    $productsOverAllAverage = $buyBillDetailExt->getOverallAverage();
    $sql = '';
    foreach ($productsOverAllAverage as $value) {
        $sql.="UPDATE product SET overAllAveragePrice = $value->overallAverage WHERE productId = $value->buybilldetailproductid;";
    }

    if ($sql != '') {
        $ProductEX->updateBulk($sql);
    }
    header("location:profitreportController.php");
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function fixPricesBuyBills($billProduct) {
    global $buyBillDetailExt;
    global $lastBillIdsPricesUpdated;
    global $lastBillIdsPricesUpdatedDAO;
    //get all buy bills for the product and before it
    $previousProductBills = $buyBillDetailExt->buyOnlyAllBills(0, 0, " where buybilldetailproductid = $billProduct->buybilldetailproductid and buybilldate < '" . $billProduct->buybilldate . "' ");
    $totalQuantity = 0;
    $TotalPriceTimesQuantity = 0;
    $TotalPriceWithDiscountTimesQuantity = 0;
    $lastBuyPriceLastBillBefore = 0;
    foreach ($previousProductBills as $data) {
        $prototal = $data->buybilldetailtotalprice;
        $rowDiscount = $data->discountvalue; //of buy bill details "of product"
        $gendis = $data->buybilldiscount; //of bill "for all products at end of bill"
        $discount_type = $data->buybilldiscountrype; //of bill also
        $billTotalBeforeDiscount = $data->buybilltotalbill; //of bill also
        ##get $billDiscountVal
        $billDiscountVal = $gendis;
        if ($discount_type == "1") {
            $billDiscountVal = ($gendis / 100) * $billTotalBeforeDiscount;
            $billDiscountVal = round($billDiscountVal, 2);
        }

        $finalquantity = $data->buybilldetailquantity * $data->productnumber;
        $price = ($prototal + $rowDiscount);
        $priceWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));


        $totalQuantity +=$finalquantity;
        $TotalPriceTimesQuantity += $price;
        $TotalPriceWithDiscountTimesQuantity += $priceWithDiscount;
        $lastBuyPriceLastBillBefore = $data->buybilldetailprice;
//        $lastBuyPriceOnePiece = $data->buybilldetailprice;
//        $billnameId = $data->billnameid;
//        //
//        $productId = $data->buybilldetailproductid;
//        $buyProduct = $productDAO->load($productId);
//        if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
//            $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
//        }
//        if ($buyProduct->meanbuyprice_withDiscount == NULL || $buyProduct->meanbuyprice_withDiscount == 0) {
//            $buyProduct->meanbuyprice_withDiscount = $buyProduct->productBuyPrice;
//        }
        //lastAndMeanBuyPrice($lastBuyPriceOnePiece, $buyProduct, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount);
    }
    ##calc Prices And Save It
    //now it is until previous bill
    $meanPrice = round(($TotalPriceTimesQuantity / $totalQuantity), 3); //now it is until previous bill
    $meanPriceWithDiscount = round(($TotalPriceWithDiscountTimesQuantity / $totalQuantity), 3); //now it is until previous bill
    $lastbuyprice = $billProduct->buybilldetailprice;
    ###########################
    $prototal = $billProduct->buybilldetailtotalprice;
    //$rowDiscount = $billProduct->discountvalue; //of buy bill details "of product"
    $gendis = $billProduct->buybilldiscount; //of bill "for all products at end of bill"
    $discount_type = $billProduct->buybilldiscountrype; //of bill also
    $billTotalBeforeDiscount = $billProduct->buybilltotalbill; //of bill also
    ##get $billDiscountVal
    $billDiscountVal = $gendis;
    if ($discount_type == "1") {
        $billDiscountVal = ($gendis / 100) * $billTotalBeforeDiscount;
        $billDiscountVal = round($billDiscountVal, 2);
    }

    $finalquantity = $billProduct->buybilldetailquantity * $billProduct->productnumber;
    $priceWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
    $lastbuyprice_withDiscount = round(($priceWithDiscount / $finalquantity), 2);
    ################################
    ##calc Prices And Save It
    //now it is the new price
    $meanPrice = ($totalQuantity * $meanPrice + $finalquantity * $lastbuyprice) / ($totalQuantity + $finalquantity);
    $meanPriceWithDiscount = ($totalQuantity * $meanPriceWithDiscount + $finalquantity * $lastbuyprice_withDiscount) / ($totalQuantity + $finalquantity);
    $meanPrice = round($meanPrice, 2);
    $meanPriceWithDiscount = round($meanPriceWithDiscount, 2);
    ###########################

    $productId = $billProduct->buybilldetailproductid;
    $buybilldetailid = $billProduct->buybilldetailid;

    if ($meanPrice == 0) {
        $meanPrice = $lastbuyprice;
    }
    if ($lastbuyprice_withDiscount == 0) {
        $lastbuyprice_withDiscount = $lastbuyprice;
    }
    if ($meanPriceWithDiscount == 0) {
        $meanPriceWithDiscount = $lastbuyprice;
    }
    //update Product
    $buyBillDetailExt->updatePrices_f("product", $lastbuyprice, $meanPrice, $lastbuyprice_withDiscount, $meanPriceWithDiscount,0,0, "productId", $productId);
    //update bill
    if ($billProduct->typeOfBill == 1) {//buy
        $lastBillIdsPricesUpdated->buybill = $buybilldetailid;
        $buyBillDetailExt->updatePrices_f("buybilldetail", $lastbuyprice, $meanPrice, $lastbuyprice_withDiscount, $meanPriceWithDiscount,0,0, "buybilldetailid", $buybilldetailid);
    } else {//buy and ret
        $lastBillIdsPricesUpdated->buyandret = $buybilldetailid;
        $buyBillDetailExt->updatePrices_f("buyandruternbilldetail", $lastbuyprice, $meanPrice, $lastbuyprice_withDiscount, $meanPriceWithDiscount,0,0, "buybilldetailid", $buybilldetailid);
    }
    ##update this too
    $lastBillIdsPricesUpdatedDAO->update($lastBillIdsPricesUpdated);
}

function fixPricesBuyBillsQuantityBefore($billProduct) {
    global $storeReportEX;
    global $buyAndReturnBillDetailExt;
    global $buyBillDetailExt;
    global $lastBillIdsPricesUpdated;
    global $lastBillIdsPricesUpdatedDAO;


    $productId = $billProduct->buybilldetailproductid;
    $billId = $billProduct->buybillid;
    if ($billProduct->typeOfBill == 1) {//buy
        $tablename = 'buyBillController.php';
    } else {//buy and ret
        $tablename = 'buyAndReturnBillController.php';
    }
    $buybilldetailid = $billProduct->buybilldetailid;

    $storeReport = $storeReportEX->getProductQuantityBeforeConditions($productId, $billId, $tablename);
    $productOrder = $buyBillDetailExt->getProductOrderInBillDetails($billId, $buybilldetailid, $productId);
    $quantityBefore = $storeReport[$productOrder]->productbefore;

    if (isset($quantityBefore)) {
        //update bill
        if ($billProduct->typeOfBill == 1) {//buy
            $lastBillIdsPricesUpdated->buyquantity = $buybilldetailid;
            $buyBillDetailExt->updatequantityBefore($quantityBefore, $buybilldetailid);
        } else {//buy and ret
            $lastBillIdsPricesUpdated->buyandretquantity = $buybilldetailid;
            $buyAndReturnBillDetailExt->updatequantityBefore($quantityBefore, $buybilldetailid);
        }
        ##update this too
        $lastBillIdsPricesUpdatedDAO->update($lastBillIdsPricesUpdated);
    }
}

function getLastPrices($productId, $date) {
    global $buyBillDetailExt;
    global $ProductDAO;
    $priceData = $buyBillDetailExt->buyOnlyAllBillsLatPricesBefore(" where buybilldetailproductid = $productId and buybilldate < '" . $date . "' order by buybilldate desc limit 1");
    $prices = new stdClass();
    if (isset($priceData->buybilldetailid) && $priceData->buybilldetailid > 0) {
        $prices->buybilldetailprice = (float) $priceData->buybilldetailprice;
        $prices->lastbuyprice = (float) $priceData->lastbuyprice;
        $prices->meanbuyprice = (float) $priceData->meanbuyprice;
        $prices->lastbuyprice_withDiscount = (float) $priceData->lastbuyprice_withDiscount;
        $prices->meanbuyprice_withDiscount = (float) $priceData->meanbuyprice_withDiscount;
    } else {
        $priceData = $ProductDAO->load($productId);
        $prices->buybilldetailprice = (float) $priceData->productBuyPrice;
        $prices->lastbuyprice = (float) $priceData->lastbuyprice;
        $prices->meanbuyprice = (float) $priceData->meanbuyprice;
        $prices->lastbuyprice_withDiscount = (float) $priceData->lastbuyprice_withDiscount;
        $prices->meanbuyprice_withDiscount = (float) $priceData->meanbuyprice_withDiscount;
    }
    return $prices;
}

function lastAndMeanBuyPrice($lastBuyPriceOnePiece, $buyProduct, $billnameId, $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount) {

    global $ProductDAO;
    global $buyBillDetailExt;
    global $ProductunitDAO;
    global $billSettingExt;
    global $Programsettingdata;


    //# load billSettingData
    $billpropertyid = 67; //# هذا الرقم يدل على تطبيق نسب الخصم فى فاتورة الشراء فى الداتا بيز
    $billSettingData = $billSettingExt->queryByBillidAndBillpropertyid($billnameId, $billpropertyid);


//    ##1- get mean
//    //# عند تطبيق تطبيق نسب الخصم
//    if ($billSettingData[0]->billsettingsvalue == 0) {
//        //# $prototal الاجمالى
//        $Bast = ($productquantityBefore * $buyProduct->meanbuyprice ) + ($prototal + $rowDiscount);
//        $makam = $productquantityAfter;
//        $meanBuyPrice = round(($Bast / $makam), 3);
//        ##with discount ##decrease pro total with its share of general discount
//        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
//        $Bast = ($productquantityBefore * $buyProduct->meanbuyprice_withDiscount ) + $prototalWithDiscount;
//        $makam = $productquantityAfter;
//        $meanBuyPrice_withDiscount = round(($Bast / $makam), 3);
//    }
//    else {
//        $realPrice_precentage = $buyProduct->buypricereal_precentage; //#   نسبة سعر الشراء الفعلى
//        $total_precntage = ( $realPrice_precentage / 100 ) * ($prototal + $rowDiscount); //# نسبة شعر الشراء على 100 * الاجمالى
//        $Bast = ($productquantityBefore * $buyProduct->meanbuyprice ) + ( $prototal - $total_precntage );
//        $makam = $productquantityAfter;
//        $meanBuyPrice = round(($Bast / $makam), 3);
//        ##with discount ##decrease pro total with its share of general discount
//        $prototalWithDiscount = $prototal - ($billDiscountVal * ($prototal / $billTotalBeforeDiscount));
//        $realPrice_precentage = $buyProduct->buypricereal_precentage; //#   نسبة سعر الشراء الفعلى
//        $total_precntage = ( $realPrice_precentage / 100 ) * $prototalWithDiscount; //# نسبة شعر الشراء على 100 * الاجمالى
//        $Bast = ($productquantityBefore * $buyProduct->meanbuyprice ) + ( $prototalWithDiscount - $total_precntage );
//        $makam = $productquantityAfter;
//        $meanBuyPrice_withDiscount = round(($Bast / $makam), 3);
//    }
//
//    ##2-save them
//    $buyProduct->meanbuyprice = abs($meanBuyPrice);
//    $buyProduct->meanbuyprice_withDiscount = abs($meanBuyPrice_withDiscount);
//    $buyProduct->lastbuyprice = $lastBuyPriceOnePiece;
//    $buyProduct->lastbuyprice_withDiscount = round(($prototalWithDiscount / $productChangeAmount), 3);
}

?>