<?php

///***************************** إعادة الجرد بالباركود********************///
//the global file operation
include("../public/impOpreation.php");

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

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

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

  ======================== */
//Store
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Storereport
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();


$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
//here the global templates
$smarty->display("header.html");
$today = date('Y-m-d');
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
    include_once("../public/authentication.php");

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

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


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

    //$smarty->assign("storenegative", $_SESSION['storenegative']);
    //here the smarty templates
    //$smarty->display("invoicesearningsreportview/start.html");
    $smarty->display("invoicesearningsreportview/byparcode.html");
} elseif ($do == "start") {
    $choosenStores = filter_input(INPUT_POST, 'storeId', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    if (in_array("all", $choosenStores)) {
        $ids = 'all';
        $queryString = " where conditions = 0 order by storeId asc ";
    } else {
        $ids = '';
        foreach ($choosenStores as $value) {
            $ids .= $value . ",";
        }
        $ids = rtrim($ids, ',');
        $queryString = " where conditions = 0 and storeId in($ids) order by storeId asc ";
    }
    $stores = $storeEX->queryAllQueryStringSimple($queryString);
    $smarty->assign("stores", $stores);
    $smarty->assign("stores_json", json_encode($stores));
    $smarty->assign("storesCount", count($stores));
    $smarty->assign("ids", $ids);
    $smarty->display("invoicesearningsreportview/show.html");
} elseif ($do == "doinventory") {
    try {
        add();
        $note = "تمت عملية الجرد";
        $url = "inventorybybarcodeController.php";
        $smarty->assign('urldirect', $url);
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        //echo $e;
        $url = "inventorybybarcodeController.php";
        $smarty->assign('urldirect', $url);
        $note = "حدث خطأ ... يرجى المحاولة مرة أخرى";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "productwithoutInventory") {
    $stores = $storeDAO->queryByConditions(0);
    $smarty->assign("storesData", $stores);

    //search
    $from = filter_input(INPUT_POST, "from");
    $to = filter_input(INPUT_POST, "to");
    $choosenStores = filter_input(INPUT_POST, 'storeId', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    if (!empty($choosenStores)) {//!empty($from) || !empty($to) ||
        $queryStringJoin = ' and storereport.tablename = "inventoryController.php" ';
        if (!empty($from)) {
            $message = $message . 'من تاريخ : ' . $from . '';
            $queryStringJoin .= ' AND storereport.storereportdate >= "' . $from . '" ';
        }
        if (!empty($to)) {
            $message = $message . 'إلى تاريخ : ' . $to . '';
            $queryStringJoin .= ' AND storereport.storereportdate <= "' . $to . '"';
        }



        $queryString = " where storereport.storereportid is NULL ";

        if (in_array("all", $choosenStores) || empty($choosenStores)) {
            //do nothing
            $ids = 'all';
            $queryStringStores = " where conditions = 0 order by storeId asc ";
        } else {
            $ids = '';
            foreach ($choosenStores as $value) {
                $ids .= $value . ",";
            }
            $ids = rtrim($ids, ',');
            $queryString .= " and storedetail.storeid in($ids) ";
            $queryStringStores = " where conditions = 0 and storeId in($ids) order by storeId asc ";
        }

        $choosenStoresArr = $storeEX->queryAllQueryStringSimple($queryStringStores);

        $noInventoryProducts_arr = array();
        $noInventory = $storeDetailExt->queryProductsNotInInventoryNoServiceFatma($queryStringJoin, $queryString);
        foreach ($noInventory as $value) {
            if (!isset($noInventoryProducts_arr[$value->productid])) {
                $value->storeName[$value->storeid] = $value->productquantity; //storeName is used as array for all stores that has product and also save product quantity in it
                $noInventoryProducts_arr[$value->productid] = $value;
            } else {
                $noInventoryProducts_arr[$value->productid]->storeName[$value->storeid] = $value->productquantity; //storeName is used as array for all stores that has product and also save product quantity in it
            }
        }
        $smarty->assign("noInventoryProducts", $noInventoryProducts_arr);
        $smarty->assign("choosenStores", $choosenStoresArr);
        $smarty->assign("message", $message);
    }
    $smarty->display("invoicesearningsreportview/productsWitoutInventory.html");
}

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

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

function getStores() {
    global $storeDAO;

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

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

    $itr = $_POST['hidden_itr'];
    $storeid = $_POST['ids'];
    for ($i = 1; $i <= $itr; $i++) {
        $newQty = $_POST['pronum' . $i];
        //print_r('</br>$newQty'.$i.'='.$newQty);
        $productId = $_POST['productid' . $i];
        $storedetailid = $_POST["detailid$i" . "_" . $storeid];
        $oldQty = $_POST["storeQty$i" . "_" . $storeid];


        if (isset($newQty) && $newQty != '') {
            //update quantity in storedetail
            $storeDetail->productquantity = $newQty;
            $storeDetail->userid = $_SESSION['userid'];
            $storeDetail->storeid = $storeid;
            $storeDetail->storedetaildate = $today;
            $storeDetail->storedetailid = $storedetailid;

            $storeDetailExt->updateProductquantity($storeDetail);

            //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'];
            $storeReportDAO->insert($storeReport);
        }
    }
}

?>