<?php
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("showsellersajax");
if (!in_array($do, $ajaxDoArr)) {
    //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");


//here the db files that include in the file
include("reportfunctions.php");

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.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');

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


//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');
//Billsreturnproduct
require_once('../models/dao/BillsreturnproductsDAO.class.php');
require_once('../models/dto/Billsreturnproduct.class.php');
require_once('../models/mysql/BillsreturnproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsreturnproductsMySqlExtDAO.class.php');

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

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

$do = $_GET['do'];

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

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

  OPERTATION in Controller

  1-load save data
  2-display show form

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

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("header.html");
}

//here goes the instances and general variables
//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

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

//Sellbilldetail
$mySellbilldetailEx = new SellbilldetailMySqlExtDAO();

//Returnsellbill
$returnSellBillDAO = new ReturnsellbillMySqlDAO();
$returnSellBillExt = new ReturnsellbillMySqlExtDAO();

//Returnsellbilldetail
$myReturnsellbilldetail = new Returnsellbilldetail();
$myReturnsellbilldetailRecord = new ReturnsellbilldetailMySqlDAO();
$myReturnsellbilldetailEx = new ReturnsellbilldetailMySqlExtDAO();

//Returnsellbill
$myReturnsellbill = new Returnsellbill();
$myReturnsellbillRecord = new ReturnsellbillMySqlDAO();
$myReturnsellbillEx = new ReturnsellbillMySqlExtDAO();

//Sellandruternbilldetail
$mySellandruternbilldetail = new Sellandruternbilldetail();
$mySellandruternbilldetailRecord = new SellandruternbilldetailMySqlDAO();
$mySellandruternbilldetailEx = new SellandruternbilldetailMySqlExtDAO();

//Sellbillandrutern
$mySellbillandrutern = new Sellbillandrutern();
$mySellbillandruternRecord = new SellbillandruternMySqlDAO();
$mySellbillandruternEx = new SellbillandruternMySqlExtDAO();
##################################
//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

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

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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

$catsIDS = "";
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");
    $Programsetting = $ProgramsettingDAO->load(1);
    ##########################################################################
    //prepare search tools
    ##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);

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

    $user = $userDAO->load($_SESSION['userid']);
    $smarty->assign("user", $user);
    if ($user->userstoreid == 0) {
        $storeData = loadStore();
        $smarty->assign("storeData", $storeData);
    }
    if ($user->branchId == 0) {
        $branchData = loadBranch();
        $smarty->assign("branchData", $branchData);
    }
    $sellerData = loadseller();
    $smarty->assign("sellerData", $sellerData);
    $userData = loadusers();
    $smarty->assign("userData", $userData);
    ###########################################################################
    //search
    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');

    $queryString = " where 1 "; //bills
    $queryStringR = " where 1 "; //billsreturn
    $queryString1 = " where 1 and sellbill.conditions = 0 "; //sellbill
    $queryString1R = " where 1 and returnsellbill.conditions = 0 "; //sellbillreturn
    $queryString1SR = " where 1 and sellbillandrutern.conditions = 0 "; //sellbillandreturn
    ##date
    if (isset($datefrom) && !empty($datefrom)) {
        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
            $datefrom = date('Y-m-d ', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($datefrom)));
        } else {
            $datefrom = $datefrom . " 00:00:00";
        }
        $queryString .= ' and bills.billdate  >= "' . $datefrom . '" ';
        $queryStringR .= ' and billsreturn.`date`  >= "' . $datefrom . '" ';
        $queryString1 .= ' and sellbill.sellbilldate  >= "' . $datefrom . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  >= "' . $datefrom . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        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
            $dateto = date('Y-m-d ', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($dateto)));
        } else {
            $dateto = $dateto . ' 23:59:59';
        }
        $queryString .= ' and bills.billdate  <= "' . $dateto . '" ';
        $queryStringR .= ' and  billsreturn.`date`  <= "' . $dateto . '" ';
        $queryString1 .= ' and sellbill.sellbilldate  <= "' . $dateto . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  <= "' . $dateto . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  <= "' . $dateto . '" ';
    }

    if (!empty($datefrom) && !empty($dateto)) {
        $datefrom = $datefrom . ' 00:00:00';
        $dateto = $dateto . ' 23:59:59';
    }
    $smarty->assign("datefrom", $datefrom);
    $smarty->assign("dateto", $dateto);
    getData($datefrom, $dateto, $queryString, $queryStringR, $queryString1, $queryString1R, $queryString1SR);
    $smarty->assign("salesreport", 1);
    //here the smarty templates
    $smarty->display("orderClientsWithSells/show.html");

    //$smarty->assign("settlementstoreshow", 1);
}elseif($do == "showsellersajax")
{
    showsellersajax();
}
//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->display("footer.html");
}

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

function getData($datefrom, $dateto, $queryString, $queryStringR, $queryString1, $queryString1R, $queryString1SR) {
    global $smarty;
    // m7md
    global $mySellbillEx;
    global $myReturnsellbillEx;
    global $mySellbillandruternEx;
    global $billsEX;
    global $billsReturnEX;
    global $clientDeptChangeExt;
    global $sellBillDAO;

    class clientData {

        public $clientid;
        public $clientname;
        public $totalsell = 0;
        public $totalreturn = 0;
        public $totaldiscount = 0;
        public $clientdebt = 0;

    }

    $existId = array();
    $sellbillDataArr = array();
    $resultsCount = 0;

    if (empty($datefrom) && empty($dateto)) {
        ##if no search make it today
        ##date
        $today = date("Y-m-d");
        $queryString .= ' and date(bills.billdate)  = "' . $today . '" ';
        $queryStringR .= ' and date(billsreturn.`date`)  = "' . $today . '" ';
        $queryString1 .= ' and  sellbill.sellbilldate  = "' . $today . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  = "' . $today . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  = "' . $today . '" ';
    }
    $billsData = $billsEX->orderClientsWithBillsSells($queryString);
    $billsDataReturn = $billsReturnEX->orderClientsWithBillsReturnSells($queryStringR);
    $sellBillData = $mySellbillEx->orderClientsWithSellbillsSells($queryString1);
    $sellBillDataReturn = $myReturnsellbillEx->orderClientsWithReturnSellbillsSells($queryString1R);
    $sellBillDataSellAndReturn = $mySellbillandruternEx->orderClientsWithSellAndReturnSellbillsSells($queryString1SR);
    $resultsCount = count($billsData) + count($billsDataReturn) + count($sellBillData) + count($sellBillDataReturn) + count($sellBillDataSellAndReturn);
    $smarty->assign("resultsCount", $resultsCount);



    ##فاتورة المبيعات
    foreach ($sellBillData as $key => $value) {
        //        var_dump($value);

        if (in_array($value->sellbillclientid, $existId)) {
            $key = array_search($value->sellbillclientid, $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value->sellbillclientid;
            array_push($existId, $value->sellbillclientid);
        }

        $myclient->clientname = $value->clientname;
        $myclient->totalsell = $value->allGenTotal;
        $myclient->sellbillaftertotalbill += $value->sellbillaftertotalbill;
        $myclient->clientdebt = $value->clientdebt;
        $myclient->selldis += $value->allGenTotal - $value->sellbillaftertotalbill;

        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->selldis);
    }

    ##فاتورة  مردودات المبيعات
    foreach ($sellBillDataReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value->returnsellbillclientid, $existId)) {
            $key = array_search($value->returnsellbillclientid, $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value->returnsellbillclientid;
            array_push($existId, $value->returnsellbillclientid);
        }

        $myclient->clientname = $value->clientname;
        $myclient->totalreturn += $value->allGenTotalReturn;
        $myclient->returnsellbillaftertotalbill += $value->returnsellbillaftertotalbill;
        $myclient->returnselldis += $value->allGenTotalReturn - $value->returnsellbillaftertotalbill;


        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->returnselldis);
    }

    ##فاتورة  مبيعات ومرتجعات
    foreach ($sellBillDataSellAndReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value->sellbillclientid, $existId)) {
            $key = array_search($value->sellbillclientid, $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value->sellbillclientid;
            array_push($existId, $value->sellbillclientid);
        }

        $myclient->clientname = $value->clientname;
        if ($value->allGenTotalSellAndReturn >= 0) {
            $myclient->totalsell += $value->allGenTotalSellAndReturn;
        } else {
            $myclient->totalreturn += $value->allGenTotalSellAndReturn;
        }
        $myclient->sellbillaftertotalbill += $value->sellbillaftertotalbill;
        $myclient->sellandreturndis += $value->allGenTotalSellAndReturn - $value->sellbillaftertotalbill;


        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->sellandreturndis);
    }

    ##فاتورة  مبيعات البصريات
    foreach ($billsData as $key => $value) {
        if (in_array($value->clientid, $existId)) {
            $key = array_search($value->clientid, $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value->clientid;
            array_push($existId, $value->clientid);
        }

        $myclient->clientname = $value->clientname;
        $myclient->totalsell += $value->totalNet;
        $myclient->totaldiscount += $value->totaldiscount;

        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
    }

    ##فاتورة  مرتجعات البصريات
    foreach ($billsDataReturn as $key => $value) {
        if (in_array($value->clientid, $existId)) {
            $key = array_search($value->clientid, $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value->clientid;
            array_push($existId, $value->clientid);
        }

        $myclient->clientname = $value->clientname;
        $myclient->totalreturn += $value->clientreceivevalue;

        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
    }

    ##صاقى المبيعات ,واجمالى الخصومات
    //    $t_bure = 0;
    $t_discount = 0;
    foreach ($sellbillDataArr as $t_data) {
        //        var_dump($t_data);
        $t_data->t_bure = $t_data->sellbillaftertotalbill - $t_data->returnsellbillaftertotalbill;
        $t_data->t_dis = $t_data->selldis - $t_data->returnselldis + $t_data->sellandreturndis;
        $t_discount += $t_data->t_dis;
    }

    foreach ($sellbillDataArr as $dataa) {

        $clientid = $dataa->clientid;

        $totalPrice = showAllOperations($clientid, $datefrom, $dateto);
        $dataa->totalPrice = $totalPrice;
    }


    //    var_dump($sellbillDataArr);
    //    $clientShowData = $clientDeptChangeExt->queryByClientIdAndDateq($cliDate);
    //    if (count($clientShowData) > 0) {
    ////        print_r($clientShowData);
    //
    //        foreach ($clientShowData as $key => $value) {//when the payment is in the bill must select from the sel bill
    ////            print_r('<pre>');
    ////            var_dump($value);
    ////            print_r('<pre>');
    //
    //            if ($value->tablename == "sellbillController.php") {
    //                $alldata = $sellBillDAO->load($value->clientdebtchangemodelid);
    //
    //
    //                $value->clientdebtchangeamount = $alldata->sellbilltotalpayed;
    //                $totalPrice += $alldata->sellbilltotalpayed;
    //            } else {
    //
    //                $clientdebtchangetype = $value->clientdebtchangetype;
    //                //print_r($clientdebtchangetype.'<br>');
    //                if ($value->tablename != 'clientController.php') {
    //                    if ($clientdebtchangetype == 0) {
    //                        //$totalPrice += $c->sellbilltotalpayed;
    //                        $totalPrice += $value->clientdebtchangeamount;
    //                    } else {
    //                        $totalPrice -= $value->clientdebtchangeamount;
    //                        //$totalPrice -= $c->sellbilltotalpayed;
    //                    }
    //                } else {
    //                    $clientControllerVal = $value->clientdebtchangeamount;
    //                }
    //
    //                //$totalPrice += $c->clientdebtchangeamount;
    //            }
    //
    //            //print_r('<br>$totalPrice = ' . $totalPrice . '  process name =  ' . $c->processname);
    //        }
    //
    //        //print_r($clientShowData);
    //    }
    //
    //    //# جمع دفعة فى فاتورة مبيعات على اجمالى الدفعات
    //    foreach ($sellbillData as $data) {
    //        if ($data->sellbilltotalpayed != 0 && $data->conditions == 0) {
    //            $totalPrice += $data->sellbilltotalpayed;
    //        }
    //    }
    //
    //    //# جمع دفعة فى فاتورة المبيعات والمرتجعات على اجمالى الدفعات
    //    foreach ($returnsellbillData[1] as $data) {
    //        if ($data->sellbilltotalpayed != 0 && $data->conditions == 0) {
    //            $totalPrice += $data->sellbilltotalpayed;
    //        }
    //    }
    //////$smarty->assign("t_bure", $t_bure);
    //////$smarty->assign("t_dis", $t_dis);
    $smarty->assign("t_discount", $t_discount);
    $smarty->assign("resultsCount", $resultsCount);
    $smarty->assign("sellbillDataArr", $sellbillDataArr);
}

function showAllOperations($clientid, $datefrom, $dateto) {
    global $clientDeptChangeExt;
    global $sellBillDAO;
    global $returnSellBillDAO;
    global $smarty;
    global $mySellbillandruternRecord;
    //فواتير المبيعات
    //from sellbill table and sellbillandreturn table

    $sellbillData = showSellBillsByClientAndDate($clientid, $datefrom, $dateto);
    //فواتير مردودات المبيعات
    //from returnsellbill table and sellbillandreturn table
    $returnsellbillData = showReturnSellBillsByClientAndDate($clientid, $datefrom, $dateto);



    //get from clientdeptchange table
    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $cliDate = '  DATE(clientdebtchange.clientdebtchangedate) >=  "' . $datefrom . '"  AND DATE(clientdebtchange.clientdebtchangedate) <= "' . $dateto . '" AND ';
    }
    $clientShowData = $clientDeptChangeExt->queryByClientIdAndDate3($clientid, $cliDate);
    if (count($clientShowData) > 0) {
        //        print_r($clientShowData);

        foreach ($clientShowData as $c) {//when the payment is in the bill must select from the sel bill
            //            print_r('<pre>');
            //            print_r($c);
            //            print_r('<pre>');
            if ($c->tablename == "sellbillController.php") {
                $alldata = $sellBillDAO->load($c->clientdebtchangemodelid);

                $c->clientdebtchangeamount = $alldata->sellbilltotalpayed;
                $totalPrice += $alldata->sellbilltotalpayed;
            } else {

                $clientdebtchangetype = $c->clientdebtchangetype;
                //print_r($clientdebtchangetype.'<br>');
                if ($c->tablename != 'clientController.php') {
                    if ($clientdebtchangetype == 0) {
                        //$totalPrice += $c->sellbilltotalpayed;
                        $totalPrice -= $c->clientdebtchangeamount;
                    } else {
                        $totalPrice += $c->clientdebtchangeamount;
                        //$totalPrice -= $c->sellbilltotalpayed;
                    }
                } else {
                    $clientControllerVal = $c->clientdebtchangeamount;
                }

                //$totalPrice += $c->clientdebtchangeamount;
            }

            //print_r('<br>$totalPrice = ' . $totalPrice . '  process name =  ' . $c->processname);
        }

        //print_r($clientShowData);
    }
    //    var_dump($totalPrice);
    //# جمع دفعة فى فاتورة مبيعات على اجمالى الدفعات
    foreach ($sellbillData as $data) {
        if ($data->sellbilltotalpayed != 0 && $data->conditions == 0) {
            $totalPrice += $data->sellbilltotalpayed;
        }
    }

    //# جمع دفعة فى فاتورة المبيعات والمرتجعات على اجمالى الدفعات
    foreach ($returnsellbillData[1] as $data) {
        if ($data->sellbilltotalpayed != 0 && $data->conditions == 0) {
            $totalPrice += $data->sellbilltotalpayed;
        }
    }

    //print_r('$clientControllerVal = ' . $clientControllerVal);
    // assign db results to the template

    return $totalPrice;
}

function showSellBillsByClientAndDate($clientid, $datefrom, $dateto) {
    global $sellBillExt;
    global $mySellbillandruternEx;
    global $mySellbilldetailEx;
    global $mySellandruternbilldetailEx;
    global $smarty;

    $bure = $_POST['bure'];

    $totalBills = 0;
    $totalQTY = 0;

    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $sellBillDate = ' sellbill.sellbilldate  >= "' . $datefrom . '" and sellbill.sellbilldate <= "' . $dateto . '" AND ';
        $sellBillReData = 'sellbillandrutern.sellbilldate  >= "' . $datefrom . '" and sellbillandrutern.sellbilldate <= "' . $dateto . '" and ';
    }
    if ($bure == 1) {
        $sellbillData = $sellBillExt->queryWithClientIdAndDate2($clientid, $sellBillDate);
    } else {
        $sellbillData = $sellBillExt->queryWithClientIdAndDateExt($clientid, $sellBillDate);
    }
    //get products number in sell bills
    if (count($sellbillData) > 0) {
        foreach ($sellbillData as $bill) {
            $totalQty1 = $mySellbilldetailEx->countProductInSellBill($bill->sellbillid);
            $bill->sellQuantity = $totalQty1;
            if ($bill->conditions == 0) {
                $totalQTY += $totalQty1;
                $totalBills += $bill->sellbillaftertotalbill;
            } /* else {
              $totalQTY -= $totalQty1;
              $totalBills -= $bill->sellbillaftertotalbill;
              } */
        }
    }


    //get sell bills from sellbillandrutern table
    if ($bure == 1) {
        $sellbillandruternData = $mySellbillandruternEx->querySellBillsOnlyWithClientIdAndDate2($clientid, $sellBillReData);
    } else {
        $sellbillandruternData = $mySellbillandruternEx->querySellBillsOnlyWithClientIdAndDateExt($clientid, $sellBillReData);
    }
    //get products number in sellbillandrutern
    if (count($sellbillandruternData) > 0) {
        foreach ($sellbillandruternData as $bill) {

            $bill->userid = -1;
            $sellbilldiscounttype = $bill->sellbilldiscounttype;
            $sellbilldiscount = $bill->sellbilldiscount;
            $sellbillprice;
            if ($sellbilldiscounttype == 1) {
                $sellbillprice = ($bill->sellbillprice) - ($bill->sellbilldiscount);
            } else {

                $sellbillprice = ($bill->sellbillprice) - ((($bill->sellbillprice) * ($bill->sellbilldiscount)) / 100);
            }
            $bill->sellbillprice = $sellbillprice;
            //print_r($bill);
            if ($bure == 1) {
                $totalQty2 = $mySellandruternbilldetailEx->countProductInSellBill($bill->sellbillid);
            } else {
                $totalQty2 = $mySellandruternbilldetailEx->countProductInSellBillExt($bill->sellbillid);
            }
            $bill->sellQuantity = $totalQty2;

            if ($bill->conditions == 0) {
                $totalQTY += $totalQty2;
                $totalBills += $sellbillprice; //(($bill->sellbillprice)-($bill->sellbilldiscount));
            } /* else {
              $totalQTY -= $totalQty2;
              $totalBills -= $sellbillprice; //(($bill->sellbillprice)-($bill->sellbilldiscount));
              } */
        }
    }

    $sellbillData = array_merge($sellbillData, $sellbillandruternData);

    //print_r($sellbillData);
    $smarty->assign("selltotalQTY", $totalQTY);
    $smarty->assign("selltotalBills", $totalBills);

    return $sellbillData;
}

function showReturnSellBillsByClientAndDate($clientid, $datefrom, $dateto) {
    global $returnSellBillExt;
    global $mySellbillandruternEx;
    global $myReturnsellbilldetailEx;
    global $mySellandruternbilldetailEx;
    global $smarty;



    $totalBills = 0;
    $totalQTY = 0;

    $bure = $_POST['bure'];

    if (!empty($datefrom) && !empty($dateto) && $datefrom != "" && $dateto != "") {
        $returnSellBillDate = ' returnsellbill.returnsellbilldate  >= "' . $datefrom . '" and returnsellbill.returnsellbilldate <= "' . $dateto . '" AND ';
        $selbillandruternReData = '  sellbillandrutern.sellbilldate  >= "' . $datefrom . '" and sellbillandrutern.sellbilldate <= "' . $dateto . '" and ';
    }
    if ($bure == 1) {
        $returnsellbillData = $returnSellBillExt->queryWithClinetIdAndDate2($clientid, $returnSellBillDate);
    } else {
        $returnsellbillData = $returnSellBillExt->queryWithClinetIdAndDateExt($clientid, $returnSellBillDate);
    }
    //get products number in returnsellbill
    if (count($returnsellbillData) > 0) {
        foreach ($returnsellbillData as $bill) {
            $totalQty1 = $myReturnsellbilldetailEx->countProductInSellBill($bill->returnsellbillid);
            $bill->returnsellQuantity = $totalQty1;
            if ($bill->conditions == 0) {
                $totalQTY += $totalQty1;
                $totalBills += $bill->returnsellbillaftertotalbill;
            }
            /* else {
              $totalQTY -= $totalQty1;
              $totalBills -= $bill->returnsellbillaftertotalbill;
              } */
        }
    }


    //get return sell bills from sellbillandrutern table
    //$sellbillandruternData =$mySellbillandruternEx->querySellBillsOnlyWithClientIdAndDate($clientid, $startDate,$endDate);
    if ($bure == 1) {
        $sellbillandruternData = $mySellbillandruternEx->queryReturnSellBillsOnlyWithClientIdAndDate2($clientid, $selbillandruternReData);
    } else {
        $sellbillandruternData = $mySellbillandruternEx->queryReturnSellBillsOnlyWithClientIdAndDateExt($clientid, $selbillandruternReData);
    }

    //print_r($sellbillandruternData);
    if (count($sellbillandruternData) > 0) {
        foreach ($sellbillandruternData as $sell) {

            $sell->userid = -1;

            $returnsellbillprice = ($sell->returnsellbillprice);


            /////////////////////
            if ($sell->conditions == 0) {
                $totalBills += $returnsellbillprice; //$sell->sellbillaftertotalbill;
            }
            /* else {
              $totalBills -= $returnsellbillprice;
              } */

            $sell->returnsellbillid = $sell->sellbillid;
            $sell->returnsellbillserial = $sell->sellbillserial;
            $sell->returnsellbillaftertotalbill = $sell->sellbillaftertotalbill;
            $sell->returnsellbilldate = $sell->sellbilldate;
            $totalQty2 = $mySellandruternbilldetailEx->countProductInReturnSellBill($sell->sellbillid);
            $sell->sellQuantity = $totalQty2;
            if ($sell->conditions == 0) {
                $totalQTY += $totalQty2;
            }
        }
    }
    $returnsellbillData = array_merge($returnsellbillData, $sellbillandruternData);
    $returnsellbill = array($returnsellbillData, $sellbillandruternData);

    $smarty->assign("returntotalQTY", $totalQTY);
    $smarty->assign("returntotalBills", $totalBills);

    return $returnsellbill;
}

function showsellersajax() {
    global $smarty;
    global $mySellbillEx;
    global $myReturnsellbillEx;
    global $mySellbillandruternEx;
    global $billsEX;
    global $billsReturnEX;
    global $clientDeptChangeExt;
    global $sellBillDAO;
    global $ProgramsettingDAO;

    class clientData {

        public $clientid;
        public $clientname;
        public $totalsell = 0;
        public $totalreturn = 0;
        public $totaldiscount = 0;
        public $clientdebt = 0;
        public $sellername;

    }
    $Programsetting = $ProgramsettingDAO->load(1);

    $datefrom = filter_input(INPUT_POST, 'datefrom');
    $dateto = filter_input(INPUT_POST, 'dateto');
    $clientid = filter_input(INPUT_POST, 'clientid');

    $queryString1 = " where 1 and sellbill.conditions = 0 "; //sellbill
    $queryString1R = " where 1 and returnsellbill.conditions = 0 "; //sellbillreturn
    $queryString1SR = " where 1 and sellbillandrutern.conditions = 0 "; //sellbillandreturn
    ##date
    if (isset($datefrom) && !empty($datefrom)) {
        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
            $datefrom = date('Y-m-d ', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($datefrom)));
        } else {
            $datefrom = $datefrom . " 00:00:00";
        }
        $queryString1 .= ' and sellbill.sellbilldate  >= "' . $datefrom . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  >= "' . $datefrom . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        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
            $dateto = date('Y-m-d ', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($dateto)));
        } else {
            $dateto = $dateto . ' 23:59:59';
        }
        $queryString1 .= ' and sellbill.sellbilldate  <= "' . $dateto . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  <= "' . $dateto . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  <= "' . $dateto . '" ';
    }

    if (!empty($datefrom) && !empty($dateto)) {
        $datefrom = $datefrom . ' 00:00:00';
        $dateto = $dateto . ' 23:59:59';
    }

    $queryString1 .=" AND sellbill.sellbillclientid = ".$clientid." ";
    $queryString1R .=" AND returnsellbill.returnsellbillclientid = ".$clientid." ";
    $queryString1SR .=" AND sellbillandrutern.sellbillclientid = ".$clientid." ";

    $existId = array();
    $sellbillDataArr = array();
    $resultsCount = 0;

    if (empty($datefrom) && empty($dateto)) {
        ##if no search make it today
        ##date
        $today = date("Y-m-d");
        $queryString1 .= ' and  sellbill.sellbilldate  = "' . $today . '" ';
        $queryString1R .= ' and returnsellbill.returnsellbilldate  = "' . $today . '" ';
        $queryString1SR .= ' and sellbillandrutern.sellbilldate  = "' . $today . '" ';
    }
    $sellBillData = R::getAll('SELECT sellbill.sellerid, sellbill.sellbillclientid , SUM(sellbill.sellbilltotalbill) as allGenTotal ,  SUM(sellbill.sellbillaftertotalbill) as sellbillaftertotalbill ,
                COUNT(sellbill.sellbillclientid ) , client.clientname as clientname , client.clientdebt as clientdebt, user.employeename as sellername  
                FROM `sellbill`
                join client on client.clientid = sellbill.sellbillclientid
                left join user on user.userid = sellbill.sellerid

                ' . $queryString1 . ' AND sellbill.conditions = 0 GROUP BY sellbill.sellerid
                ');
    $sellBillDataReturn = R::getAll('SELECT sellerid, returnsellbill.returnsellbillclientid , SUM(returnsellbill.returnsellbilltotalbill) as allGenTotalReturn , SUM(returnsellbill.returnsellbillaftertotalbill) as returnsellbillaftertotalbill ,
                COUNT(returnsellbill.returnsellbillclientid ) , client.clientname as clientname, user.employeename as sellername  
                FROM `returnsellbill`
                join client on client.clientid = returnsellbill.returnsellbillclientid
                left join user on user.userid = returnsellbill.sellerid

                ' . $queryString1R . ' AND returnsellbill.conditions = 0  GROUP BY returnsellbill.sellerid
                ');
    $sellBillDataSellAndReturn = R::getAll('SELECT sellerid, sellbillandrutern.sellbillclientid , SUM(sellbillandrutern.sellbilltotalbill) as allGenTotalSellAndReturn ,  SUM(sellbillandrutern.sellbillaftertotalbill) as sellbillaftertotalbill ,
                COUNT(sellbillandrutern.sellbillclientid ) , client.clientname as clientname, user.employeename as sellername
                 FROM `sellbillandrutern`
                join client on client.clientid = sellbillandrutern.sellbillclientid
                left join user on user.userid = sellbillandrutern.sellerid

                ' . $queryString1SR . ' AND sellbillandrutern.conditions = 0  GROUP BY sellbillandrutern.sellerid
                ');
    $resultsCount = count($sellBillData) + count($sellBillDataReturn) + count($sellBillDataSellAndReturn);
    $smarty->assign("resultsCount", $resultsCount);



    ##فاتورة المبيعات
    foreach ($sellBillData as $key => $value) {
        //        var_dump($value);

        if (in_array($value['sellerid'], $existId)) {
            $key = array_search($value['sellerid'], $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value['sellbillclientid'];
            array_push($existId, $value['sellerid']);
        }

        $myclient->clientname = $value['clientname'];
        $myclient->sellername = $value['sellername'];
        $myclient->totalsell = $value['allGenTotal'];
        $myclient->sellbillaftertotalbill += $value['sellbillaftertotalbill'];
        $myclient->clientdebt = $value['clientdebt'];
        $myclient->selldis += $value['allGenTotal'] - $value['sellbillaftertotalbill'];

        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->selldis);
    }

    ##فاتورة  مردودات المبيعات
    foreach ($sellBillDataReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value['sellerid'], $existId)) {
            $key = array_search($value['sellerid'], $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value['returnsellbillclientid'];
            array_push($existId, $value['sellerid']);
        }

        $myclient->clientname = $value['clientname'];
        $myclient->sellername = $value['sellername'];
        $myclient->totalreturn += $value['allGenTotalReturn'];
        $myclient->returnsellbillaftertotalbill += $value['returnsellbillaftertotalbill'];
        $myclient->returnselldis += $value['allGenTotalReturn'] - $value['returnsellbillaftertotalbill'];


        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->returnselldis);
    }

    ##فاتورة  مبيعات ومرتجعات
    foreach ($sellBillDataSellAndReturn as $key => $value) {
        //        var_dump($value);
        if (in_array($value['sellerid'], $existId)) {
            $key = array_search($value['sellerid'], $existId);
            $myclient = $sellbillDataArr[$key];
        } else {
            $key = -1;
            $myclient = new clientData();
            $myclient->clientid = $value['sellbillclientid'];
            array_push($existId, $value['sellerid']);
        }

        $myclient->clientname = $value['clientname'];
        $myclient->sellername = $value['sellername'];
        if ($value['allGenTotalSellAndReturn'] >= 0) {
            $myclient->totalsell += $value['allGenTotalSellAndReturn'];
        } else {
            $myclient->totalreturn += $value['allGenTotalSellAndReturn'];
        }
        $myclient->sellbillaftertotalbill += $value['sellbillaftertotalbill'];
        $myclient->sellandreturndis += $value['allGenTotalSellAndReturn'] - $value['sellbillaftertotalbill'];


        if ($key == -1) {
            array_push($sellbillDataArr, $myclient);
        }
        //        var_dump($myclient->sellandreturndis);
    }

    ##صاقى المبيعات ,واجمالى الخصومات
    //    $t_bure = 0;
    $t_discount = 0;
    foreach ($sellbillDataArr as $t_data) {
        //        var_dump($t_data);
        $t_data->t_bure = $t_data->sellbillaftertotalbill - $t_data->returnsellbillaftertotalbill;
        $t_data->t_dis = $t_data->selldis - $t_data->returnselldis + $t_data->sellandreturndis;
        $t_discount += $t_data->t_dis;
    }

    foreach ($sellbillDataArr as $dataa) {

        $clientid = $dataa->clientid;

        $totalPrice = showAllOperations($clientid, $datefrom, $dateto);
        $dataa->totalPrice = $totalPrice;
    }
    $smarty->assign("t_discount", $t_discount);
    $smarty->assign("resultsCount", $resultsCount);
    $smarty->assign("sellbillDataArr", $sellbillDataArr);
    $smarty->display('orderClientsWithSells/showSellersData.html');
}
?>