<?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");
//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');
//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');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.class.php');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.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');
//Unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.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');
//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');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.class.php');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.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');

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

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

  Controller Name :- buyBillController

  OPERTATION in Controller

  1- add buy bill, buy And Return Bill and return buy bill
  2- show buy bill details
  3- show buy bills
  4- delete buy bill

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

//handling saveid session
/* 	if(!isset($_SESSION['saveid']))
  {
  $_SESSION['saveid'] = 1;
  }
 */

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

//here goes the instances and general variables
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//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();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDebtChange = new Supplierdebtchange();
$supplierDebtChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDebtChangeExt = new SupplierdebtchangeMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
$storeExt = new StoreMySqlExtDAO();
//Programsetting
$programSettingExt = new ProgramsettingsMySqlExtDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Billname
$billNameDAO = new BillnameMySqlDAO();
$billNameExt = new BillnameMySqlExtDAO();
//Billsetting
$billSettingExt = new BillsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport;
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
//Savedaily
$saveDaily = new Savedaily();
$saveDailyDAO = new SavedailyMySqlDAO();
$saveDailyExt = new SavedailyMySqlExtDAO();
//Productserial
$Productserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = new ProductserialMySqlExtDAO();

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

$today = date("Y-m-d");
$smarty->assign("today", $today);

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);

//check and use the condition that suite this action
if ($do == "show" || empty($do)) {
    //here the permission check

    include_once("../public/authentication.php");

    $suppliersData = getSuppliers(); //undeleted suppliers
    $smarty->assign("suppliersData", $suppliersData);

    $billSerials = showBuyBills();
    $smarty->assign("billSerials", $billSerials);

    $supplierId = $_REQUEST['supplier'];
    $serial = $_REQUEST['serial'];
    $buybillid = $_REQUEST['buybillid'];
    $from = $_REQUEST['from'];
    $to = $_REQUEST['to'];

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


    show();



    $smarty->assign("customCheck", 1);
    $smarty->display("returnBillreportview/show.html");
}

//here the global templates
$smarty->assign("customValidation", 1);
$smarty->display("footer.html");

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

function show() {

    global $buyAndReturnBillExt;
    global $buyAndReturnBillDetailExt;
    global $returnBuyBill;
    global $returnBuyBillDAO;
    global $returnBuyBillExt;
    global $returnBuyBillDetailExt;
    global $ProgramsettingDAO;


    global $smarty;

    $queryString = ' WHERE';
    $queryString1 = ' WHERE';

    $serial = $_REQUEST["serial"];
    $supplierId = $_REQUEST["supplierId"];
    $buybillid = $_REQUEST["buybillid"];
    $from = $_REQUEST["from"];
    $to = $_REQUEST["to"];

    if (!empty($supplierId) && $supplierId != "-1") {
        $queryString.='  returnbuybill.returnbuybillsupplierid = ' . $supplierId . ' AND';
        $queryString1.='  buybillsupplierid = ' . $supplierId . ' AND';
    }

    if (!empty($serial) && $serial != "-1") {
        $queryString.= '  returnbuybill.returnbuybillSerial = "' . $serial . '" AND';
        $queryString1.= '  buybillSerial = "' . $serial . '" AND';
    }

    if (!empty($buybillid) && $buybillid != "-1") {
        $queryString.='  returnbuybill.returnbuybillid = "' . $buybillid . '" AND';
        $queryString1.='  buybillid = "' . $buybillid . '" AND';
    }


    if (!empty($from) && $from != "" && !empty($to) && $to != "") {
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
        } else {
            $endDatePrepared = $endDate . ' 23:59:59';
            $from = $from . " 00:00:00";
        }

        $queryString.='  returnbuybill.returnbuybilldate >= "' . $from . '" AND returnbuybill.returnbuybilldate <= "' . $to . '"  AND';
        $queryString1.='  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
    }


    if (empty($from) && empty($to) && empty($buybillid) && empty($serial) && !isset($supplierId)) {
        $from = $to = $today = date("Y-m-d");
        //display the converted time ##reportsPlusHours
        $Programsetting = $ProgramsettingDAO->load(1);
        if (isset($Programsetting->reportsPlusHours) && !empty($Programsetting->reportsPlusHours)) {
            $reportsPlusHours = $Programsetting->reportsPlusHours + 24; //24 to get the end of the day and add search hours to it
            $to = date('Y-m-d H:i:s', strtotime('+' . $reportsPlusHours . ' hour +0 minutes', strtotime($to)));
            $from = date('Y-m-d H:i:s', strtotime('+' . $Programsetting->reportsPlusHours . ' hour +0 minutes', strtotime($from)));
        } else {
            $endDatePrepared = $endDate . ' 23:59:59';
            $from = $from . " 00:00:00";
        }
        $queryString1.='  buybilldate >= "' . $from . '" AND buybilldate <= "' . $to . '"  AND';
        $queryString.='  returnbuybill.returnbuybilldate >= "' . $from . '" AND returnbuybill.returnbuybilldate <= "' . $to . '"  AND';
    }
    $arr = explode(' ', $queryString);

    $arr = explode(' ', $queryString);
    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 = ' ';
        }
    }


    $arr = explode(' ', $queryString1);
    $arr = explode(' ', $queryString1);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        // print_r('lastWord'.$lastWord.'<br>');
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString1 = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString1 = ' ';
        }
        //print("<br>queryString: ".$queryString."<br>");
    }


    $totalBills = 0;
    $totalqty = 0;
    $totaltax = 0;
    $totaldiscount = 0;

    $returnBuyBillData1 = $returnBuyBillExt->queryBystring($queryString);

    foreach ($returnBuyBillData1 as $myreturnData) {

        $returnbuybillid = $myreturnData->returnbuybillid;
        $totalBills = $totalBills + $myreturnData->returnbuybillaftertotalbill;
        $returnbuybilldetailes = $returnBuyBillDetailExt->queryByBuybillidExt($returnbuybillid);

        if ($myreturnData->conditions == 0) {

            //getalldiscount
            $buybilldiscount = $myreturnData->returnbuybilldiscount;
            $buybilldiscountrype = $myreturnData->returnbuybilldiscountrype; //1 مباشر
            $buybilltotalbill = $myreturnData->returnbuybilltotalbill;
            $buybillaftertotalbill = $myreturnData->returnbuybillaftertotalbill;
            $tax = $myBillData->tax;

            $detaildiscount = $returnBuyBillDetailExt->getsumdiscount($myreturnData->returnbuybillid);
            if ($buybilldiscountrype == 0) {
                //discount
                $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
                $myreturnData->returnbuybilldiscount = ($buybilldiscount + $detaildiscount);

                //tax
                $taxvalue = (-1 * $buybillaftertotalbill) - (number_format(($buybilltotalbill * -1) - $buybilldiscount));

                /* print_r('<br>sssssssssssssssssssssss'.$buybillaftertotalbill);
                  print_r('<br>sssssssssssssssssssssss'.number_format(($buybilltotalbill*-1)-$buybilldiscount));
                  print_r('<br>sssssssssssssssssssssss'.$buybilldiscount);
                 */
                $totaltax = $totaltax + $taxvalue;
                $myreturnData->tax = $taxvalue;
            } else {

                //discount
                $discountvalue = ($buybilltotalbill / 100) * $buybilldiscount;


                $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                $myreturnData->returnbuybilldiscount = ($discountvalue + $detaildiscount);
                //tax
                $taxvalue = $buybillaftertotalbill - ($buybilltotalbill - ($discountvalue));
                $totaltax = $totaltax + $taxvalue;
                $myreturnData->tax = $taxvalue;
            }



            $myreturnData->controlname = "returnbuybill";
            foreach ($returnbuybilldetailes as $myreturnbuybilldetailes) {
                $productnumber = $myreturnbuybilldetailes->productnumber;
                $returnbuybilldetailquantity = $myreturnbuybilldetailes->returnbuybilldetailquantity;

                $totalqty = $totalqty + ($productnumber * $returnbuybilldetailquantity);
            }
        }
    }














    $returnbuyBillData = $buyAndReturnBillExt->queryBystring($queryString1);

    foreach ($returnbuyBillData as $remyBillData) {

        $buybillid = $remyBillData->buybillid;
        $totalBills = $totalBills + $remyBillData->buybillaftertotalbill;
        $buybilldetailes = $buyAndReturnBillDetailExt->queryByBuybillidExt($buybillid);

        if ($remyBillData->conditions == 0) {


            //getalldiscount
            $buybilldiscount = 0; //$remyBillData->buybilldiscount;
            $buybilldiscountrype = $remyBillData->buybilldiscountrype; //1 مباشر
            $buybilltotalbill = $remyBillData->buybilltotalbill;
            $buybillaftertotalbill = $remyBillData->buybillaftertotalbill;
            $tax = $remyBillData->tax;

            $detaildiscount = $buyAndReturnBillDetailExt->getsumdiscount($remyBillData->buybillid, 1);

            if ($buybilldiscountrype == 0) {
                //discount
                $totaldiscount = $totaldiscount + $buybilldiscount + $detaildiscount;
                $remyBillData->buybilldiscount = ($buybilldiscount + $detaildiscount);

                //tax
                $taxvalue = 0; //$buybillaftertotalbill-($buybilltotalbill-($buybilldiscount));
                $totaltax = $totaltax + $taxvalue;
                $remyBillData->tax = $taxvalue;
            } else {

                //discount
                $discountvalue = 0; //($buybilltotalbill/100)*$buybilldiscount;


                $totaldiscount = $totaldiscount + $discountvalue + $detaildiscount;
                $remyBillData->buybilldiscount = ($discountvalue + $detaildiscount);
                //tax
                $taxvalue = 0; //$buybillaftertotalbill-($buybilltotalbill-($discountvalue));
                $totaltax = $totaltax + $taxvalue;
                $remyBillData->tax = $taxvalue;
            }


            $remyBillData->controlname = "returnbuybill";
            foreach ($buybilldetailes as $mybuybilldetailes) {
                if ($mybuybilldetailes->billtype == 1) {
                    $productnumber = $mybuybilldetailes->productnumber;
                    $buybilldetailquantity = $mybuybilldetailes->buybilldetailquantity;

                    $totalqty = $totalqty + ($productnumber * $buybilldetailquantity);
                }
            }
        }
    }

    $smarty->assign('returnBuyBillData1', $returnBuyBillData1);
    $smarty->assign('returnbuyBillData', $returnbuyBillData);
    $smarty->assign('totalBills', $totalBills);
    $smarty->assign('totalqty', $totalqty);
    $smarty->assign('totaldiscount', $totaldiscount);
    $smarty->assign('totaltax', $totaltax);
}

function getBuyBillNames() {
    global $billNameDAO;
    global $billNameExt;
    $type = 1;
    // get all not deleted
    $billNameData = $billNameExt->queryByType($type);
    return $billNameData;
}

function loadBillProperties($billnameid) {
    global $billSettingExt;

    // select all data from Billname
    $billSettingsData = $billSettingExt->queryWithBillnameId($billnameid);

    return $billSettingsData;
}

function getProducts() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;
    $productsData = $productExt->queryAllExt();
    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //print("parentId: ".$parentId."");
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $i++;
        }
    }
    return $productsData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        //print("<br>categories: ".$categories."<br>");
        //print_r($catData);
        $newParentId = $catData->productCatParent;
        //print("newParentId: ".$newParentId."<br><br>");
        if ($newParentId != 0 && count($catData) > 0) {
            $newParentName = $catData->parentName;
            $categories .= $newParentName . '/';
            fetch_recursive($newParentId, $categories);
        }
    }
    return $categories;
}

function getSuppliers() {
    global $supplierDAO;
    $suppliersData = $supplierDAO->queryByCondition(0);
    return $suppliersData;
}

function getProductCatParents() {
    global $productCatExt;
    global $productExt;

    $allParents = $productExt->queryAllCategories(); //$productCatExt->queryAllChildrenExt();
    return $allParents;
}

function checkRoundNumbers() {
    global $programSettingExt;
    $roundNumbersStatus = $programSettingExt->getRoundNumbersStatus();

    return $roundNumbersStatus;
}

function getProductCatId($productId) {
    global $productExt;
    $catId = $productExt->getProductCatId($productId);
    return $catId;
}

function showBuyBills() {
    global $buyBillExt;
    $buyBills = $buyBillExt->queryAllSerialsNotDeleted();
    return $buyBills;
}

?>