<?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");
include_once("dailyentryfun.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');
//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');
//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');
//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');
//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');
//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');
//Productcatunit
require_once('../models/dao/ProductcatunitDAO.class.php');
require_once('../models/dto/Productcatunit.class.php');
require_once('../models/mysql/ProductcatunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatunitMySqlExtDAO.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/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');

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 :- inventoryController

  OPERTATION in Controller

  1- show products with store id or product category id or product id
  2- update product quantity

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

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

//here goes the instances and general variables
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport();
$storeReportDAO = new StorereportMySqlDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Productunit
$productUnit = new Productunit();
$productUnitDAO = new ProductunitMySqlDAO();
$productUnitExt = new ProductunitMySqlExtDAO();
//Store
$storeDAO = new StoreMySqlDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();

//
$sizeColorStoreDetail = new Sizecolorstoredetail();
$sizeColorStoreDetailDAO = new SizecolorstoredetailMySqlDAO();
$sizeColorStoreDetailEX = new SizecolorstoredetailMySqlExtDAO();

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

$today = date("Y-m-d");

//check and use the condition that suite this action
if (empty($do) || $do == "show") {
    //here the permission check
    include_once("../public/authentication.php");

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

    //get product categories
//    $catData = getProductCatsForShow();
//    $smarty->assign("catData", $catData);
    $catData = getCategoryChilds();
    $smarty->assign("catData", $catData[1]);

    $storesData = getStores();
    $smarty->assign("storesData", $storesData);

    $smarty->assign("storenegative", $_SESSION['storenegative']);

    $programsettingsdata = $ProgramsettingDAO->load(1);
    $smarty->assign("programsettingsdata", $programsettingsdata);
    //here the smarty templates
    $smarty->display("inventoryview/add.html");
    $smarty->assign("custominventory", 1);
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    try {
        add();
        $Inv_byCode = (int) $_POST['Inv_byCode'];
        if ($Inv_byCode == 1) {
            $url = "inventorybybarcodeController.php";
            $smarty->assign('urldirect', $url);
            $note = "تمت عملية الجرد";
            $smarty->assign('msgnote', $note);
            $smarty->display("notes2.html");
        } else {
            $url = "inventoryController.php?";
            $smarty->assign('urldirect', $url);
            $note = "تمت عملية الجرد";
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        }
    } catch (Exception $e) {

        echo $e;
        /* $url = "inventoryController.php?";
          $smarty->assign('urldirect', $url);
          $note ="حدث خطأ ... يرجى المحاولة مرة أخرى";
          $smarty->assign('msgnote', $note);
          $smarty->display("notes.html"); */
    }
} elseif ($do == "autosave") {
    autosave();
} elseif ($do == "details") {
    $id = (int) $_GET['id'];
    $details = R::getRow('select * from storereport where storereportid=' . $id);
    $details['productName'] = R::getCell('select productName from product where productId=' . $details['productid']);
    $details['storeName'] = R::getCell('select storeName from store where storeId=' . $details['storeid']);
    $details['employeename'] = R::getCell('select employeename from user where userid=' . $details['userid']);
    $smarty->assign('details', $details);
    $smarty->display("inventoryview/details.html");
}
//here the global templates
$smarty->assign("inventoryScripts", 1);
$smarty->display("footer.html");

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

function getCategoryChilds($parentid = 0) {
    global $productCatExt;
    global $productCatDAO;
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid);

    return array($parentobject, $childsArray);
}

function getProductCatsForShow() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;
    $productsData = $productExt->queryAllProducts2();

    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $smarty->assign("parentId" . $i, $parentId);
            $i++;
        }
        $itr = $i - 1;
        $smarty->assign("itr", $itr);
    }
    return $productsData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

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

function getStores() {
    global $storeDAO;

    $storesData = $storeDAO->queryByConditions(0);
    return $storesData;
}

function add() {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $storeReport;
    global $storeReportDAO;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $today;

    $itr = $_POST['itr'];
    //print_r('itr='.$itr);
    for ($i = 1; $i <= $itr; $i++) {
        $newQty = $_POST['newQty' . $i];
        //print_r('</br>$newQty'.$i.'='.$newQty);
        $productId = $_POST['productId' . $i];
        $storedetailid = $_POST['storedetailid' . $i];
        $oldQty = $_POST['oldQty' . $i];
        $storeid = $_POST['storeid' . $i];

        $sizeId = 0;
        $colorId = 0;

        if (isset($newQty) && $newQty != '') {
            //update quantity in storedetail
            if (strpos($productId, "hasSizeColor") !== false) {
                $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
                $productId = $productIdComplex[0];
                $sizeId = $productIdComplex[1];
                $colorId = $productIdComplex[2];
                $sizecolorstoredetail = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2($productId, $storeid, $sizeId, $colorId);
                //
                $oldQty = $sizecolorstoredetail->quantity;
                $sizecolorstoredetail->userid = $_SESSION['userid'];
                $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
                $sizecolorstoredetail->quantity = $newQty;
                $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
                onlineTempStoreDetailFunc2($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, $newQty, 1);
                //affect product to make it have total quantity
                $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
                $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
            } else {

                $storeDetail = $storeDetailExt->getProductQuantity($productId, $storeid);
                //
                $oldQty = $storeDetail->productquantity;
                $storeDetail->productid = $productId;
                $storeDetail->productquantity = $newQty;
                $storeDetail->userid = $_SESSION['userid'];
                $storeDetail->storeid = $storeid;
                $storeDetail->storedetaildate = $today;
                $storeDetail->storedetailid = $storedetailid;

                /* print_r("<pre>");
                  print_r($storeDetail);
                  print_r("<pre>"); */
                $storeDetailExt->updateProductquantity($storeDetail);
                onlineTempStoreDetailFunc2($storeDetail->storeid, $storeDetail->productid, 0, 0, $newQty, 1);
            }
            //check if quantity increased or decreased
            if ($oldQty > $newQty) {
                $status = "بالنقص";
                $actualQty = $oldQty - $newQty;
                $type = 1;
            } else if ($oldQty < $newQty) {
                $status = "بالزيادة";
                $actualQty = $newQty - $oldQty;
                $type = 0;
            } else if ($oldQty == $newQty) {
                $status = "لم يتغير";
                $actualQty = $newQty;
                $type = 0;
            }



            //insert new row into storereport
            $storeReport->processname = "تم إعادة جرد المنتج بالقيمة الحالية " . $status;
            $storeReport->productafter = $newQty;
            $storeReport->productbefore = $oldQty;
            $storeReport->productid = $productId;
            $storeReport->productquantity = $actualQty;
            $storeReport->storeid = $storeid;
            $storeReport->storereportdate = $today;
            $storeReport->storereportmodelid = -1;
            $storeReport->storereporttype = $type;
            $storeReport->tablename = "inventoryController.php";
            $storeReport->userid = $_SESSION['userid'];
            $storeReport->sizeid = $sizeId;
            $storeReport->colorid = $colorId;
            //print_r($storeReport);
            $id = $storeReportDAO->insert($storeReport);
            $storeReport->storereportid = $id;
            onlineTempStoreReportFunc($storeReport);
            doInventoryDailyEntry($storeid, $productId, $actualQty, $newQty, $type, $storeReport);
        }
    }
}

function doInventoryDailyEntry($storeId, $productId, $quantity, $newQty, $type, $storeReport) {//$type = 0 incease , 1 decrease
    if ($quantity != 0 && $storeReport->productbefore != $storeReport->productafter) {
        ## 1- get needed data
        $store = R::getRow('select storeName,treeId from store where storeId=' . $storeId);
        $dailyEntryCostprice = R::getCell('select dailyEntryCostprice from programsettings where programsettingsid=1');
        $priceColName = '';
        switch ($dailyEntryCostprice) {
            case "first":
                $priceColName = 'productBuyPrice';
                break;
            case "last":
                $priceColName = 'lastbuyprice';
                break;
            case "mean":
                $priceColName = 'meanbuyprice';
                break;
            case "last_discount":
                $priceColName = 'lastbuyprice_withDiscount';
                break;
            case "mean_discount":
                $priceColName = 'meanbuyprice_withDiscount';
                break;
            case "tax":
                $priceColName = 'lastbuyprice_withTax';
                break;
            case "mean_tax":
                $priceColName = 'meanbuyprice_withTax';
                break;
            case "generalPrice":
                $priceColName = 'meanbuyprice_withTax';
                break;
//        case "realBuyPrice":
//            $priceColName = 'meanbuyprice';
//            break;
            default:
                $priceColName = 'meanbuyprice';
                break;
        }
        $productData = R::getRow('select ' . $priceColName . ' as price,productName,productCatId from product where productId=' . $productId);
        $catName = R::getCell('select productCatName from productcat where productCatId=' . $productData['productCatId']);
        $productCost = $productData['price'] * $quantity;
        $productName = "(" . $productData['productName'] . "/" . $catName . ")";
        $store ['storeName'] = "(" . $store ['storeName'] . ")";



        ## 2- do entry
        $dailyEntry->entryComment = 'اعادة جرد للمنتج : ' . $productName . ' فى مخزن : ' . $store ['storeName'] . ' بالكمية : ' . $newQty . '';
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $productCost;
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $productCost;
        if ($type == 0) {//quantity increased
            //من المخزن
            $dailyEntryDebtor->accountstreeid = $store['treeId'];
            //الى عجز و زيادة المخزون
            $dailyEntryCreditor->accountstreeid = 188;
        } elseif ($type == 1) {//quantity decreased
            //من عجز و زيادة المخزون
            $dailyEntryDebtor->accountstreeid = 188;
            //الى المخزن
            $dailyEntryCreditor->accountstreeid = $store['treeId'];
        }
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 0, $storeReport->storereportid, "inventoryController.php?do=details&id=$storeReport->storereportid");

        $did = $returnedData[1];
        return $did;
    }
}

function autosave() {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailExt;
    global $storeReport;
    global $storeReportDAO;
    global $sizeColorStoreDetailDAO;
    global $sizeColorStoreDetailEX;
    global $today;

    $newQty = $_POST['newQty'];
    $productId = $_POST['productId'];
    $storedetailid = $_POST['storedetailid'];
    $oldQty = $_POST['oldQty'];
    $storeid = $_POST['storeid'];

    $sizeId = 0;
    $colorId = 0;

    if (isset($newQty) && $newQty != '') {
        //update quantity in storedetail
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $sizecolorstoredetail = $sizeColorStoreDetailEX->getIdByProductStoreSizeAndColorEX2($productId, $storeid, $sizeId, $colorId);
            //
            $oldQty = $sizecolorstoredetail->quantity;
            $sizecolorstoredetail->userid = $_SESSION['userid'];
            $sizecolorstoredetail->sysdate = date("Y-m-d H:i:s");
            $sizecolorstoredetail->quantity = $newQty;
            $sizeColorStoreDetailDAO->update($sizecolorstoredetail);
            onlineTempStoreDetailFunc2($sizecolorstoredetail->storeid, $sizecolorstoredetail->productid, $sizecolorstoredetail->sizeid, $sizecolorstoredetail->colorid, $newQty, 1);
            //affect product to make it have total quantity
            $storeDetailData = $storeDetailExt->queryWithStoreAndProductandunit($productId, $sizecolorstoredetail->storeid, 0);
            $storeDetailExt->updateQuantityWithSumChild($storeDetailData->storedetailid, $_SESSION['userid'], date("Y-m-d"), 0, $sizecolorstoredetail->storeid, $sizecolorstoredetail->productid);
        } else {

            $storeDetail = $storeDetailExt->getProductQuantity($productId, $storeid);
            //
            $oldQty = $storeDetail->productquantity;
            $storeDetail->productid = $productId;
            $storeDetail->productquantity = $newQty;
            $storeDetail->userid = $_SESSION['userid'];
            $storeDetail->storeid = $storeid;
            $storeDetail->storedetaildate = $today;
            $storeDetail->storedetailid = $storedetailid;

            /* print_r("<pre>");
              print_r($storeDetail);
              print_r("<pre>"); */
            $storeDetailExt->updateProductquantity($storeDetail);
            onlineTempStoreDetailFunc2($storeDetail->storeid, $storeDetail->productid, 0, 0, $newQty, 1);
        }
        //check if quantity increased or decreased
        if ($oldQty > $newQty) {
            $status = "بالنقص";
            $actualQty = $oldQty - $newQty;
            $type = 1;
        } else if ($oldQty < $newQty) {
            $status = "بالزيادة";
            $actualQty = $newQty - $oldQty;
            $type = 0;
        } else if ($oldQty == $newQty) {
            $status = "لم يتغير";
            $actualQty = $newQty;
            $type = 0;
        }



        //insert new row into storereport
        $storeReport->processname = "تم إعادة جرد المنتج بالقيمة الحالية " . $status;
        $storeReport->productafter = $newQty;
        $storeReport->productbefore = $oldQty;
        $storeReport->productid = $productId;
        $storeReport->productquantity = $actualQty;
        $storeReport->storeid = $storeid;
        $storeReport->storereportdate = $today;
        $storeReport->storereportmodelid = -1;
        $storeReport->storereporttype = $type;
        $storeReport->tablename = "inventoryController.php";
        $storeReport->userid = $_SESSION['userid'];
        $storeReport->sizeid = $sizeId;
        $storeReport->colorid = $colorId;
        //print_r($storeReport);
        $id = $storeReportDAO->insert($storeReport);
        $storeReport->storereportid = $id;

        onlineTempStoreReportFunc($storeReport);
        doInventoryDailyEntry($storeid, $productId, $actualQty, $newQty, $type, $storeReport);
    }
}

?>