<?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();
$myStoreEx = new StoreMySqlExtDAO();

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

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

    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $stores = $myStoreEx->queryByConditions();
        }else{
            $stores = $myStoreEx->queryByConditions(' and store.storeId in (' . $_SESSION['storeids'] . ')');
        }
        $smarty->assign("storesData", $stores);
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = '.$_SESSION['storeid'].' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }else{
        $storedef = $myStoreEx->queryByConditionsOne(' and store.storeId = '.$_SESSION['storeid'].' ');
        $smarty->assign("storedef", $storedef);
        $smarty->assign("storeid", $_SESSION['storeid']);
    }




    // $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("storehousingview/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"); */
    }
}
//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);
        }
    }
}

?>