<?php

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

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

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

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

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

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

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

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

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

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

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

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

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

//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 :- collectionPermissionController

  OPERTATION in Controller

  1-
  2-
  3-
  4-

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

//here goes the instances and general variables
//client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientEX = new ClientMySqlExtDAO();

//Sellbill
$sellBill = new Sellbill();
$sellBillDAO = new SellbillMySqlDAO();
$sellBillEX = new SellbillMySqlExtDAO();

//Sellbilldetail
$SellBillDetail = new Sellbilldetail();
$SellBillDetailDAO = new SellbilldetailMySqlDAO();
$SellBillDetailEX = new SellbilldetailMySqlExtDAO();

//Returnsellbill
$returnSellBill = new Returnsellbill();
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillEX = new ReturnsellbillMySqlExtDAO();

//Returnsellbilldetail
$returnSellBillDetail = new Returnsellbilldetail();
$returnSellBillDetailDAO = new ReturnsellbilldetailMySqlDAO();
$returnSellBillDetailEX = new ReturnsellbilldetailMySqlExtDAO();

//Sellbillandrutern
$sellBillAndReturn = new Sellbillandrutern();
$sellBillAndReturnDAO = new SellbillandruternMySqlDAO();
$sellBillAndReturnEX = new SellbillandruternMySqlExtDAO();

//Sellandruternbilldetail
$SellBillAndRuternDetail = new Sellandruternbilldetail();
$SellBillAndRuternDetailDAO = new SellandruternbilldetailMySqlDAO();
$SellBillAndRuternDetailEX = new SellandruternbilldetailMySqlExtDAO();

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

//Productunit
$myProductunitEx = new ProductunitMySqlExtDAO();

//product
$product = new Product();
$productDAO = new ProductMySqlDAO();

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

$myUserGroupRecord = new UsergroupMySqlDAO();
$loadData = $myUserGroupRecord->load($_SESSION['usergroupid']);
$smarty->assign("loadData", $loadData);


if (empty($do) || $do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

    //all supplier
    $clientsData = $clientDAO->queryAll();
    $smarty->assign("clientsData", $clientsData);

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

    $queryString = ' WHERE'; //sell , selland return
    $queryString2 = ' WHERE'; //return

    $clientId = $_POST['clientId'];
    $from = $_POST["from"];
    $to = $_POST["to"];
    $buyPriceType = $_POST["buyPriceType"];

    if (empty($clientId) && empty($from) && empty($to)) {
        $from = $to = date("Y-m-d");
    }

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

    $message1 = '';

    if (isset($clientId) && $clientId != -1) {
        $queryString .= '  sellbillclientid = ' . $clientId . ' AND';
        $queryString2 .= '  returnsellbillclientid = ' . $clientId . ' AND';
        $client = $clientDAO->load($clientId);
        $message1 .= ' ارباح العميل : ' . $client->clientname;
    }
    if (isset($from) && !empty($from) && isset($to) && !empty($to)) {
        $queryString .= ' DATE( sellbillsysdate )  >= "' . $from . '" AND DATE( sellbillsysdate ) <= "' . $to . '"';
        $queryString2 .= ' DATE( returnsellbillsysdate )  >= "' . $from . '" AND DATE( returnsellbillsysdate ) <= "' . $to . '"';

        $message1 .= ' التاريخ من : ' . $from . ' التاريخ الى : ' . $to;
    }
    $message1 .= ' الحساب بـ ';
    switch ($buyPriceType) {
        case "first":
            $message1 .= 'سعر الشراء ';
            break;
        case "last":
            $message1 .= ' اخر سعر شراء';
            break;
        case "mean":
            $message1 .= 'متوسط سعر الشراء ';
            break;
        case "last_discount":
            $message1 .= ' اخر سعر شراء بعد الخصم';
            break;
        case "mean_discount":
            $message1 .= 'متوسط سعر الشراء بعد الخصم ';
            break;
        case "generalPrice":
            $message1 .= 'متوسط العام ';
            break;
        case "tax":
            $message1 .= 'اخر سعر شراء شامل القيمة المضافة ';
            break;
        case "mean_tax":
            $message1 .= 'متوسط سعر الشراء شامل القيمة المضافة';
            break;
    }
    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryString);
    //print_r($arr);
    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>dddddddddddd".$queryString."ddddddddddd<br>");
    }

    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryString2);
    //print_r($arr);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString2 = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString2 = ' ';
        }
        //print("<br>dddddddddddd".$queryString2."ddddddddddd<br>");
    }


    if ($queryString != ' ') {//queryString2 like queryString empty together or not emty together
        //totals
        $sellProfit = 0;
        $returnProfit = 0;


        $sellBillArray = array();
        $returnSellBillArray = array();
        $sellBillAndReturnArray = array();


        //sell
        $sellBill = $sellBillEX->GetSellBillUsingQueryString($queryString);

        foreach ($sellBill as $mysellBill) {
            $thisProfits = 0;
            $thisBillBuyPrice = 0;
            $thisBillSellPrice = 0;
            $SellBillDetail = $SellBillDetailDAO->queryBySellbillid($mysellBill->sellbillid);
            foreach ($SellBillDetail as $mySellBillDetail) {
                $unitId = $mySellBillDetail->productunitid;
                $productId = $mySellBillDetail->sellbilldetailproductid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                $overAllAveragePrice = $productunitData->overAllAveragePrice;
                $myproductNumber = $productunitData->productnumber;
                switch ($buyPriceType) {
                    case "first":
                        $buyprice = (float) $mySellBillDetail->buyprice;
                        break;
                    case "last":
                        $buyprice = (float) $mySellBillDetail->lastbuyprice;
                        break;
                    case "mean":
                        $buyprice = (float) $mySellBillDetail->meanbuyprice;
                        break;
                    case "last_discount":
                        $buyprice = (float) $mySellBillDetail->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $buyprice = (float) $mySellBillDetail->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $buyprice = (float) $overAllAveragePrice;
                        break;
                    case "tax":
                        $buyprice = (float) $mySellBillDetail->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $buyprice = (float) $mySellBillDetail->meanbuyprice_withTax;
                        break;
                }
                $myBuyPrice = $buyprice * ($mySellBillDetail->sellbilldetailquantity * $myproductNumber);
                $thisBillBuyPrice += $myBuyPrice;
                $thisProfits += $mySellBillDetail->sellbilldetailtotalprice - $myBuyPrice;
                $thisBillSellPrice += $mySellBillDetail->sellbilldetailtotalprice;

                /* print_r('<pre>');
                  print_r('</br>buyprice='.$buyprice.'</br>');
                  print_r('</br>myproductNumber='.$myproductNumber.'</br>');
                  print_r('</br>sellbilldetailtotalprice='.$mySellBillDetail->sellbilldetailtotalprice.'</br>');
                  print_r('</br>discountvalue='.$mySellBillDetail->discountvalue.'</br>');
                  print_r('</br>sellProfit='.$sellProfit.'</br>');
                  print_r('</pre>'); */
            }

            //reduce discount value
            $discount = 0;
            if ($mysellBill->sellbilldiscounttype == 1) {
                $discount = $mysellBill->sellbilldiscount;
            } elseif ($mysellBill->sellbilldiscounttype == 2) {
                $discount = ($mysellBill->sellbilldiscount / 100) * $mysellBill->sellbilltotalbill;
            }
            $thisProfits -= $discount;

            $sellProfit += $thisProfits;
            $mysellBill->userid = $discount;
            $mysellBill->billnameid = $thisBillBuyPrice; //سعر الشراء
            $mysellBill->sellerid = $thisBillSellPrice; //سعر البيع
            $mysellBill->tax = $thisProfits;
            array_push($sellBillArray, $mysellBill);
        }

        //rturn
        $returnSellBill = $returnSellBillEX->GetReturnSellBillUsingQueryString($queryString2);

        foreach ($returnSellBill as $myreturnSellBill) {
            $thisProfits = 0;
            $thisBillBuyPrice = 0;
            $thisBillSellPrice = 0;
            $returnSellBillDetail = $returnSellBillDetailDAO->queryByReturnsellbillid($myreturnSellBill->returnsellbillid);

            foreach ($returnSellBillDetail as $myreturnSellBillDetail) {

                $unitId = $myreturnSellBillDetail->productunitid;
                $productId = $myreturnSellBillDetail->returnsellbilldetailproductid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                $overAllAveragePrice = $productunitData->overAllAveragePrice;
                $myproductNumber = $productunitData->productnumber;
                switch ($buyPriceType) {
                    case "first":
                        $buyprice = (float) $myreturnSellBillDetail->buyprice;
                        break;
                    case "last":
                        $buyprice = (float) $myreturnSellBillDetail->lastbuyprice;
                        break;
                    case "mean":
                        $buyprice = (float) $myreturnSellBillDetail->meanbuyprice;
                        break;
                    case "last_discount":
                        $buyprice = (float) $myreturnSellBillDetail->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $buyprice = (float) $myreturnSellBillDetail->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $buyprice = (float) $overAllAveragePrice;
                        break;
                    case "tax":
                        $buyprice = (float) $myreturnSellBillDetail->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $buyprice = (float) $myreturnSellBillDetail->meanbuyprice_withTax;
                        break;
                }
                $myBuyPrice = $buyprice * ($myreturnSellBillDetail->returnsellbilldetailquantity * $myproductNumber);

                $thisProfits += $myreturnSellBillDetail->returnsellbilldetailtotalprice - $myBuyPrice;

                $thisBillBuyPrice += $myBuyPrice;
                $thisBillSellPrice += $myreturnSellBillDetail->returnsellbilldetailtotalprice;

                /* print_r('<pre>');
                  print_r('</br>buyprice='.$buyprice.'</br>');
                  print_r('</br>myproductNumber='.$myproductNumber.'</br>');
                  print_r('</br>returnsellbilldetailtotalprice='.$myreturnSellBillDetail->returnsellbilldetailtotalprice.'</br>');
                  print_r('</br>discountvalue='.+$myreturnSellBillDetail->buydiscount.'</br>');
                  print_r('</br>returnProfit='.$returnProfit.'</br>');
                  print_r('</pre>'); */
            }

            //reduce discount value
            $discount = 0;
            if ($myreturnSellBill->returnsellbilldiscounttype == 1) {
                $discount = $myreturnSellBill->returnsellbilldiscount;
            } elseif ($myreturnSellBill->returnsellbilldiscounttype == 2) {
                $discount = ($myreturnSellBill->returnsellbilldiscount / 100) * $myreturnSellBill->returnsellbilltotalbill;
            }

            $thisProfits -= $discount;


            $returnProfit += $thisProfits;

            $myreturnSellBill->userid = $discount;
            $myreturnSellBill->billnameid = $thisBillBuyPrice;
            $myreturnSellBill->sellerid = $thisBillSellPrice;
            $myreturnSellBill->tax = $thisProfits;

            array_push($returnSellBillArray, $myreturnSellBill);
        }

        //sell and return
        $sellBillAndReturn = $sellBillAndReturnEX->GetSellBillAndReturnUsingQueryString($queryString);
        foreach ($sellBillAndReturn as $mysellBillAndReturn) {
            $sellBill = new Sellbill();

            $returnSellBill = new Returnsellbill();


            $thisProfitsSell = 0;
            $thisProfitsReturn = 0;

            $thisBillBuyPrice = 0;
            $thisBillSellPrice = 0;

            $SellBillAndRuternDetail = $SellBillAndRuternDetailDAO->queryBySellbillid($mysellBillAndReturn->sellbillid);
            foreach ($SellBillAndRuternDetail as $mySellBillAndRuternDetail) {
                $unitId = $mySellBillAndRuternDetail->productunitid;
                $productId = $mySellBillAndRuternDetail->sellbilldetailproductid;
                $productunitData = loadProductUnitWithProductAndUnit($productId, $unitId);
                $overAllAveragePrice = $productunitData->overAllAveragePrice;
                $myproductNumber = $productunitData->productnumber;
                switch ($buyPriceType) {
                    case "first":
                        $buyprice = (float) $mySellBillAndRuternDetail->buyprice;
                        break;
                    case "last":
                        $buyprice = (float) $mySellBillAndRuternDetail->lastbuyprice;
                        break;
                    case "mean":
                        $buyprice = (float) $mySellBillAndRuternDetail->meanbuyprice;
                        break;
                    case "last_discount":
                        $buyprice = (float) $mySellBillAndRuternDetail->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $buyprice = (float) $mySellBillAndRuternDetail->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $buyprice = (float) $overAllAveragePrice;
                        break;
                    case "tax":
                        $buyprice = (float) $mySellBillAndRuternDetail->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $buyprice = (float) $mySellBillAndRuternDetail->meanbuyprice_withTax;
                        break;
                }
                $myBuyPrice = $buyprice * ($mySellBillAndRuternDetail->sellbilldetailquantity * $myproductNumber);

                $thisBillBuyPrice += $myBuyPrice;
                $thisBillSellPrice += $mySellBillAndRuternDetail->sellbilldetailtotalprice;

                if ($mySellBillAndRuternDetail->selltype == 0) {// بيع
                    $thisProfitsSell += $mySellBillAndRuternDetail->sellbilldetailtotalprice - $myBuyPrice;

                    $sellBill->billnameid += $myBuyPrice;
                    $sellBill->sellerid += $mySellBillAndRuternDetail->sellbilldetailtotalprice;
                } elseif ($mySellBillAndRuternDetail->selltype == 1) {//مردود
                    $thisProfitsReturn += $mySellBillAndRuternDetail->sellbilldetailtotalprice - $myBuyPrice;

                    $returnSellBill->billnameid += $myBuyPrice;
                    $returnSellBill->sellerid += $mySellBillAndRuternDetail->sellbilldetailtotalprice;
                }

                /* print_r('<pre>');
                  print_r('</br>buyprice='.$buyprice.'</br>');
                  print_r('</br>myproductNumber='.$myproductNumber.'</br>');
                  print_r('</br>sellbilldetailtotalprice='.$mySellBillAndRuternDetail->sellbilldetailtotalprice.'</br>');
                  print_r('</br>discountvalue='.$mySellBillAndRuternDetail->discountvalue.'</br>');
                  print_r('</br>='.$returnProfit.'</br>');
                  print_r('</br>sellProfit='.$sellProfit.'</br>');
                  print_r('</pre>'); */
            }

            //reduce discount value
            $discount = 0;
            if ($mysellBillAndReturn->sellbilldiscounttype == 1) {
                $discount = $mysellBillAndReturn->sellbilldiscount;
            } elseif ($mysellBillAndReturn->sellbilldiscounttype == 2) {
                $discount = ($mysellBillAndReturn->sellbilldiscount / 100) * $mysellBillAndReturn->sellbilltotalbill;
            }
            /* $thisProfitsSell-=$discount;

              $sellProfit+=$thisProfitsSell;
              $returnProfit+=$thisProfitsReturn;

              $mysellBillAndReturn->userid=$discount;
              $mysellBillAndReturn->billnameid=$thisBillBuyPrice;
              $mysellBillAndReturn->sellerid=$thisBillSellPrice;
              $mysellBillAndReturn->tax=$thisBillSellPrice-$thisBillBuyPrice; */



            $sellBill->userid = $discount;
            $returnSellBill->userid = 0;

            $sellBill->tax = $sellBill->sellerid - $sellBill->billnameid - $sellBill->userid;
            $returnSellBill->tax = $returnSellBill->sellerid - $returnSellBill->billnameid;

            $sellProfit += $sellBill->tax;
            $returnProfit += $returnSellBill->tax;

            $sellBill->sellbillid = $mySellBillAndRuternDetail->sellbillid;
            $returnSellBill->returnsellbillid = $mySellBillAndRuternDetail->sellbillid;
            //array_push($sellBillAndReturnArray,$mysellBillAndReturn);
            array_push($sellBillArray, $sellBill);
            array_push($returnSellBillArray, $returnSellBill);
        }

        $netprofit = $sellProfit - $returnProfit;
    }
    /* print_r('<pre>');
      print_r($sellBillAndReturnArray);
      print_r('</pre>'); */
    $smarty->assign("sellProfit", $sellProfit);
    $smarty->assign("returnProfit", $returnProfit);
    $smarty->assign("clientCurrentDebt", $client->clientdebt);
    $smarty->assign("netprofit", $netprofit);
    $smarty->assign("sellBillArray", $sellBillArray);
    //$smarty->assign("sellBillAndReturnArray",$sellBillAndReturnArray);
    $smarty->assign("returnSellBillArray", $returnSellBillArray);
    $smarty->assign("message1", $message1);
    //js for unit is with footer
    $smarty->display("clientProfitsView/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->assign("collectionPermission",1);
$smarty->display("footer.html");

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

function loadProductUnitWithProductAndUnit($productId, $unitId) {

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

    // select all data from productunit tbl
    $productunitData = $myProductunitEx->queryWithProductIdAndUnitId($productId, $unitId);

    return $productunitData;
}
