<?php

//the global file operation
session_start();
ob_start();

//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");
//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');
//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');
//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');
//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');
//Productionrate
require_once('../models/dao/ProductionrateDAO.class.php');
require_once('../models/dto/Productionrate.class.php');
require_once('../models/mysql/ProductionrateMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateMySqlExtDAO.class.php');
//Productionrateproduct
require_once('../models/dao/ProductionrateproductDAO.class.php');
require_once('../models/dto/Productionrateproduct.class.php');
require_once('../models/mysql/ProductionrateproductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionrateproductMySqlExtDAO.class.php');

//task order
require_once('../models/dao/TaskorderDAO.class.php');
require_once('../models/dto/Taskorder.class.php');
require_once('../models/mysql/TaskorderMySqlDAO.class.php');
require_once('../models/mysql/ext/TaskorderMySqlExtDAO.class.php');
//task order products
require_once('../models/dao/TaskorderproductsDAO.class.php');
require_once('../models/dto/Taskorderproduct.class.php');
require_once('../models/mysql/TaskorderproductsMySqlDAO.class.php');
require_once('../models/mysql/ext/TaskorderproductsMySqlExtDAO.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');

//productionExecution
require_once('../models/dao/ProductionexecutionDAO.class.php');
require_once('../models/dto/Productionexecution.class.php');
require_once('../models/mysql/ProductionexecutionMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionMySqlExtDAO.class.php');
//productionExecutionProduct
require_once('../models/dao/ProductionexecutionoutputDAO.class.php');
require_once('../models/dto/Productionexecutionoutput.class.php');
require_once('../models/mysql/ProductionexecutionoutputMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionoutputMySqlExtDAO.class.php');
//productionExecutionOutput
require_once('../models/dao/ProductionexecutionproductDAO.class.php');
require_once('../models/dto/Productionexecutionproduct.class.php');
require_once('../models/mysql/ProductionexecutionproductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionproductMySqlExtDAO.class.php');
//productionExecutionWaste
require_once('../models/dao/ProductionexecutionwasteDAO.class.php');
require_once('../models/dto/Productionexecutionwaste.class.php');
require_once('../models/mysql/ProductionexecutionwasteMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductionexecutionwasteMySqlExtDAO.class.php');
//Simplemanufacturesetting
require_once('../models/dao/SimplemanufacturesettingDAO.class.php');
require_once('../models/dto/Simplemanufacturesetting.class.php');
require_once('../models/mysql/SimplemanufacturesettingMySqlDAO.class.php');
require_once('../models/mysql/ext/SimplemanufacturesettingMySqlExtDAO.class.php');
//
require_once ('../models/dao/BuypriceshistorybookDAO.class.php');
require_once ('../models/dto/Buypriceshistorybook.class.php');
require_once ('../models/mysql/BuypriceshistorybookMySqlDAO.class.php');
require_once ('../models/mysql/ext/BuypriceshistorybookMySqlExtDAO.class.php');

//
require_once ('../models/dao/SizecolorstoredetailDAO.class.php');
require_once ('../models/dto/Sizecolorstoredetail.class.php');
require_once ('../models/mysql/SizecolorstoredetailMySqlDAO.class.php');
require_once ('../models/mysql/ext/SizecolorstoredetailMySqlExtDAO.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');
//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');
//get the do the action
$do = $_GET['do'];

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

  Controller Name :- productionExecutionAjaxController

  OPERTATION in Controller
  ======================== */

//here goes the instances and general variables
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$myProductEx = new ProductMySqlExtDAO();
//Storereport
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
//Productcat
$myProductcatRecord = $productCatDAO = new ProductcatMySqlDAO();
$myProductcatEx = $productCatExt = new ProductcatMySqlExtDAO();

//Productionrate
$productionrate = new Productionrate();
$productionrateDAO = new ProductionrateMySqlDAO();
$productionrateEX = new ProductionrateMySqlExtDAO();

//Productionrateproduct
$Productionrateproduct = new Productionrateproduct();
$ProductionrateproductDAO = new ProductionrateproductMySqlDAO();
$ProductionrateproductEX = new ProductionrateproductMySqlExtDAO();



//taskorder
$taskorder = new Taskorder();
$taskorderDao = new TaskorderMySqlDAO();
$taskorderExt = new TaskorderMySqlExtDAO();

//taskorder products
$taskorderproducts = new Taskorderproduct();
$taskorderproductsDao = new TaskorderproductsMySqlDAO();
$taskorderproductsExt = new TaskorderproductsMySqlExtDAO();

//Store
$myStoreRecord = new StoreMySqlDAO();

//productionExecution
$productionExecution = new Productionexecution();
$productionExecutionDao = new ProductionexecutionMySqlDAO();
$productionExecutionExt = new ProductionexecutionMySqlExtDAO();

//productionExecutionProduct
$productionExecutionProduct = new Productionexecutionproduct();
$productionExecutionProductDao = new ProductionexecutionproductMySqlDAO();
$productionExecutionProductExt = new ProductionexecutionproductMySqlExtDAO();

//productionExecutionOutput
$productionExecutionOutput = new Productionexecutionoutput();
$productionExecutionOutputDao = new ProductionexecutionoutputMySqlDAO();
$productionExecutionOutputExt = new ProductionexecutionoutputMySqlExtDAO();

//productionExecutionWaste
$productionExecutionWaste = new Productionexecutionwaste();
$productionExecutionWasteDao = new ProductionexecutionwasteMySqlDAO();
$productionExecutionWasteExt = new ProductionexecutionwasteMySqlExtDAO();
//Simplemanufacturesetting
$simplesetting = new Simplemanufacturesetting();
$simplesettingDao = new SimplemanufacturesettingMySqlDAO();
$simplesettingExt = new SimplemanufacturesettingMySqlExtDAO();
//Buypriceshistorybook
$buyPricesHistoryBook = new Buypriceshistorybook();
$buyPricesHistoryBookDAO = new BuypriceshistorybookMySqlDAO();
$buyPricesHistoryBookEX = new BuypriceshistorybookMySqlExtDAO();
//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();
//Billsetting
$myBillsettingEx = new BillsettingsMySqlExtDAO();
//Programsetting
$programSettingDAO = new ProgramsettingsMySqlDAO();


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


if ($do == "getTaskOrderProducts") {

    $orderId = filter_input(INPUT_POST, 'orderId');

    $orderData = $taskorderDao->load($orderId);
    $allRawProducts = $taskorderproductsExt->queryAllProductsByTaskOrderId($orderId);

    $simpleSettingData = $simplesettingDao->load(1);
    foreach ($allRawProducts as $value) {
        $finalquantity = $value->quantity * $value->productnumber;
        $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($simpleSettingData->storeid, $value->productid, 0, 0, $value->productBuyPrice, $finalquantity, 0);
        $value->productBuyPrice = $comingData[0];
    }

    $smarty->assign('allRawProducts', $allRawProducts);

    $smarty->assign('proNumber', $orderData->num);

    $smarty->display('productionExecutionView/rawProducts.html');
} elseif ($do == "checkOrderId") {
    $orderId = filter_input(INPUT_POST, 'orderId');
    $editId = filter_input(INPUT_POST, 'editId');
    if ($editId) {
        $allExecution = $productionExecutionExt->getOtherOrders($editId, $orderId);
    } else {
        $allExecution = $productionExecutionDao->queryByOrderId($orderId);
    }

    if (count($allExecution) >= 1)
        echo -1;
    else
        echo 1;
} elseif ($do == "getEqProducts") {
    $simpleSettingData = $simplesettingDao->load(1);

    $smarty->assign('allowedit', 1);
    $smarty->assign('allowAddDel', (int) $_POST['allowAddDel']);
    $smarty->assign('showPriceCol', (int) $_POST['showPriceCol']);
    $proId = (int) filter_input(INPUT_POST, 'proId');
    $noOfOccurance = $sizeColorStoreDetailEX->checkIfProductHasSizecolor($proId);
    if ($noOfOccurance > 0) {//the product has size and color
        //get all productionEquation of that product
        $allProductEquations = $productionrateEX->queryAllRateByfinalNameSC($proId);
        foreach ($allProductEquations as $eq) {
            ##
            $eq->productName = $eq->productName . '/ ' . $eq->productCatName;
            if (!empty($eq->sizeName) && !empty($eq->colorName)) {
                $eq->productId = "hasSizeColor" . $eq->finalName . "-" . $eq->sizeid . "-" . $eq->colorid;
                $eq->productName .= '/ ' . $eq->sizeName . '/ ' . $eq->colorName;
            }
            ##
            $allRawProducts = $ProductionrateproductEX->queryAllByProductionRateId($eq->productionRateId);
            foreach ($allRawProducts as $p) {
                switch ($Programsettingdata->Inventoryevaluation) {
                    case "first":
                        $pro_price = (float) $p->productBuyPrice;
                        break;
                    case "last":
                        $pro_price = (float) $p->lastbuyprice;
                        break;
                    case "mean":
                        $pro_price = (float) $p->meanbuyprice;
                        break;
                    case "last_discount":
                        $pro_price = (float) $p->lastbuyprice_withDiscount;
                        break;
                    case "mean_discount":
                        $pro_price = (float) $p->meanbuyprice_withDiscount;
                        break;
                    case "generalPrice":
                        $pro_price = (float) $p->overAllAveragePrice;
                        break;
                    case "tax":
                        $pro_price = (float) $p->lastbuyprice_withTax;
                        break;
                    case "mean_tax":
                        $pro_price = (float) $p->meanbuyprice_withTax;
                        break;
                    case "realBuyPrice":
                        $finalquantity = $p->quantity * $p->productnumber;
                        $comingData = getBuyPriceFromAndHandleBuyPricesHistoryBook($simpleSettingData->storeid, $p->productId, 0, 0, $p->productBuyPrice, $finalquantity, 0);
                        $pro_price = $comingData[0];
                        break;
                }
                $p->productBuyPrice = $pro_price;


                ##
                $p->productName = $p->productName . '/ ' . $p->productCatName;
                if (!empty($p->sizeName) && !empty($p->colorName)) {
                    $p->productId = "hasSizeColor" . $p->productId . "-" . $p->sizeid . "-" . $p->colorid;
                    $p->productName .= '/ ' . $p->sizeName . '/ ' . $p->colorName;
                }
            }
            $eq->productionRateProducts = $allRawProducts;
        }
        $smarty->assign('allProductEquations', $allProductEquations);
        $smarty->assign('proHasSizeColor', 1);
        $smarty->assign('proNumber', 1);
        $smarty->display('productionExecutionView/allSCProEquations.html');
    } else {

        $productEquationRow = $productionrateEX->queryOneRateByfinalName($proId);
        $allRawProducts = $ProductionrateproductEX->queryAllByProductionRateId($productEquationRow->productionRateId);
        $smarty->assign('allRawProducts', $allRawProducts);
        $smarty->assign('proHasSizeColor', 0);
        $smarty->assign('proNumber', 1);
        $smarty->display('productionExecutionView/rawProducts.html');
    }
} elseif ($do == "getProducts") {
    $productsData = loadProductWithByName();
    $smarty->assign("productsData", $productsData);
} elseif ($do == "getStore") {
    $itr = filter_input(INPUT_POST, 'itr');
    $type = filter_input(INPUT_POST, 'type');
    $storeId = filter_input(INPUT_POST, 'storeId');

    if (!$type)
        $type = "out";

    $allStore = $myStoreRecord->queryByConditions(0);

    $data = '<select class="select2_store ' . $type . 'Store" id="' . $type . 'store' . $itr . '" name="' . $type . 'Store' . $itr . '" data-search="true">
                <option value="-1">اختر المخزن</option>';
    foreach ($allStore as $store) {
        if ($store->storeId == $storeId)
            $data .= '<option value="' . $store->storeId . '" selected>' . $store->storeName . '</option>';
        else
            $data .= '<option value="' . $store->storeId . '">' . $store->storeName . '</option>';
    }

    $data .= '</select>';

    echo $data;
} elseif ($do == "getProData") {
    $productId = filter_input(INPUT_POST, 'proId');
    if (strpos($productId, "hasSizeColor") !== false) {
        $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
        $productId = $productIdComplex[0];
        $sizeId = $productIdComplex[1];
        $colorId = $productIdComplex[2];
    }

    $proData = $productDAO->load($productId);
    echo $proData->productSellAllPrice . ',';
    echo $proData->productSellHalfPrice . ',';
    echo $proData->productSellUnitPrice;
}

///////////////////////////// functions \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function getFinalProductsWithOutProductionEquation() {
    global $myProductEx;

    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $hiddenpricetype = $_REQUEST["hiddenpricetype"];

    $productsData = $myProductEx->getFinalProductsWithProductionRate($name);
    if (count($productsData) > 0) {
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
//names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

//send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


//جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
//تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
//نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }


            array_push($return_arr, $row_array);
        }
    }

//echo $return_arr;
    echo json_encode($return_arr);
}

function fetch_recursive($parentid, $categories) {
    global $myProductcatEx;
//print($parentid."<br>");
    $catData = $myProductcatEx->getCategoryAndParentByCatId($parentid);
//print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

//if($newParentId != 0 && isset($newParentId))
        {
//$newParentName = $catData->parentName;
//$categories .= $newParentName.'/';
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

// select from Product tbl
function loadProductWithByName() {
    global $myProductEx;
    global $myBillsettingEx;
    global $Programsettingdata;
    $categories;
    $row_array = array();
    $return_arr = array();

    $name = $_GET['term']; //It could be product name or category name
    $limit = $Programsettingdata->searchlimit; //intval($_GET['page_limit']);
    if (empty($limit))
        $limit = 30;
    $storeid = (int) $_REQUEST["storeid"];
    if (empty($storeid))
        $storeid = 1;

    $property = $myBillsettingEx->queryByBillidAndBillpropertyid(3, 101); //0 search catname,proname only //1 search sizename,colorname too
    $controlNameSearch = (int) $property[0]->billsettingsvalue;
    $queryString = '';

    $productsData = $myProductEx->queryByNameExtWithoutLimit2($name, $storeid, '', " limit $limit", $controlNameSearch);

    if (count($productsData) > 0) {


        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //send product id and product name as something that select2 expects.
            if (!is_null($pro->sizecolorstoredetailid) && $pro->sizecolorstoredetailid > 0) {//has size and color
                $row_array['id'] = "hasSizeColor" . $pro->productId . "-" . $pro->sizeid . "-" . $pro->colorid;
            } else {//without size and color
                $row_array['id'] = $pro->productId;
            }
            //$row_array['sizecolorstoredetailid'] = $pro->sizecolorstoredetailid;
            $row_array['text'] = $pro->productName . '/' . $pathArr;
            if (!is_null($pro->sizeName) && !empty($pro->sizeName)) {
                $row_array['text'] .= '/' . $pro->sizeName;
            }
            if (!is_null($pro->colorName) && !empty($pro->colorName)) {
                $row_array['text'] .= '/' . $pro->colorName;
            }

            $row_array['sizeid'] = $pro->sizeid;
            $row_array['colorid'] = $pro->colorid;

            $row_array['productquantity'] = $pro->productquantity;
            //جملة
            if ($hiddenpricetype == 0) {
                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
            //تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
            //نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }
            array_push($return_arr, $row_array);
        }
    }


//echo $return_arr;
    echo json_encode($return_arr);
}

function getBuyPriceFromAndHandleBuyPricesHistoryBook($storeId, $productid, $sizeid, $colorid, $productBuyPrice, $soldQuantity, $type = 0) { //0 add ,1 del
    global $buyPricesHistoryBookDAO;
    global $buyPricesHistoryBookEX;

    $idQuantityString = '';
    $remainQuantity = $soldQuantity;
    $totalPrice = 0;
    $lastUsedBuyPriceFromHistoryBookId = 0;
    do {
        $buyPriceFromHistoryBook = $buyPricesHistoryBookEX->getBuyPriceOfFirstAvailableSellQuantity($storeId, $productid, $sizeid, $colorid, " and buypriceshistorybook.id > $lastUsedBuyPriceFromHistoryBookId");
        if (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0) {
            $availableBuyQuantity = $buyPriceFromHistoryBook->buyQuantity - $buyPriceFromHistoryBook->sellQuantity;
            if ($availableBuyQuantity >= $remainQuantity) {
                $totalPrice += $remainQuantity * $buyPriceFromHistoryBook->buyprice;
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$remainQuantity,";
                $remainQuantity -= $remainQuantity; //$remainQuantity = 0;
            } elseif ($remainQuantity > $availableBuyQuantity) {
                $totalPrice += $availableBuyQuantity * $buyPriceFromHistoryBook->buyprice;
                $lastUsedBuyPriceFromHistoryBookId = $buyPriceFromHistoryBook->id;
                //
                $idQuantityString .= "$buyPriceFromHistoryBook->id-$availableBuyQuantity,";
                $remainQuantity -= $availableBuyQuantity;
            }
        }
    } while (isset($buyPriceFromHistoryBook->id) && $buyPriceFromHistoryBook->id > 0 && $remainQuantity > 0);
    if ($remainQuantity > 0) {
        $totalPrice += $remainQuantity * $productBuyPrice;
        $remainQuantity -= $remainQuantity;
    }

    $theBuyPrice = round(($totalPrice / $soldQuantity), 2);
    return array(
        $theBuyPrice,
        $idQuantityString
    );
}

?>