<?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");
//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');
//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');
//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');
//Restaurantrawdestruction
require_once('../models/dao/RestaurantrawdestructionDAO.class.php');
require_once('../models/dto/Restaurantrawdestruction.class.php');
require_once('../models/mysql/RestaurantrawdestructionMySqlDAO.class.php');
require_once('../models/mysql/ext/RestaurantrawdestructionMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

//here goes the instances and general variables
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();
//Storereport
$storeReportDAO = new StorereportMySqlDAO();
$storeReportExt = new StorereportMySqlExtDAO();
//Restaurantrawdestruction
$restaurantRawDestruction = new Restaurantrawdestruction();
$restaurantRawDestructionDAO = new RestaurantrawdestructionMySqlDAO();
$restaurantRawDestructionEX = new RestaurantrawdestructionMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

//check and use the condition that suite this action
if (empty($do)) {
    $storeId = $_GET['storeid'];
    $productId = $_GET['productid'];
    $catId = $_GET['catid'];
    $sizeId = 0;
    $colorId = 0;

    $queryString = ' WHERE';

    if (isset($storeId) && !empty($storeId) && $storeId != '-1') {
        //get product in this store
        $queryString .= ' storedetail.storeId = ' . $storeId . ' AND';
    }
    if (isset($catId) && !empty($catId) && $catId != '-1') {
        //get products in this category
        $queryString .= ' productcat.productCatId = ' . $catId . ' AND';
    }
    if (isset($productId) && !empty($productId) && $productId != '-1') {
        //get product by id
        $sizeId = 0;
        $colorId = 0;
        if (strpos($productId, "hasSizeColor") !== false) {
            $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
            $productId = $productIdComplex[0];
            $sizeId = $productIdComplex[1];
            $colorId = $productIdComplex[2];
            $queryString .= ' sizecolorstoredetail.productid = ' . $productId . ' AND';
            $queryString .= ' sizecolorstoredetail.sizeid = ' . $sizeId . ' AND';
            $queryString .= ' sizecolorstoredetail.colorid = ' . $colorId . ' AND';
        } else {
            $queryString .= ' storedetail.productid = ' . $productId . ' AND';
        }
    }

    //explode string on space character to remove last AND occurence
    $arr = explode(' ', $queryString);
    //print_r($arr);
    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 = ' ';
        }
        //print("<br>".$queryString."<br>");
    }


    $queryStringDestruction = '';
    if ($storeId > 0) {
        $queryStringDestruction .= " and storeid = $storeId ";
    }
    if ($productId > 0) {
        $queryStringDestruction .= " and productid = $productId ";
        if ($sizeId > 0 && $colorId > 0) {
            $queryStringDestruction .= " and sizeid = $sizeId ";
            $queryStringDestruction .= " and colorid = $colorId ";
        }
    }

    $productData = getInventoryProducts($queryString, $queryStringDestruction);
    echo json_encode($productData);
    //$smarty->assign("productData", $productData);
    //here the smarty templates
    //$smarty->display("restaurantRawDestructionView/products.html");
}

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

function getInventoryProducts($queryString, $queryStringDestruction) {
    global $storeDetailExt;
    global $storeReportExt;
    global $restaurantRawDestructionEX;
    global $productDAO;
    global $Programsettingdata;
    $productData = $storeDetailExt->queryProductsInInventoryExt2NoService($queryString);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////To show product category name (the product whole path)
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //new product name with all path
            $pro->productName = $pro->productName . '/' . $pathArr;

            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductIdAndStoreId($pro->productid, $_REQUEST['storeid']);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProductsWithStoreId($pro->productid, $_REQUEST['storeid'], $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }

            //for restaurantRawDestruction controller
            $buyprice = 0;
            $row = $productDAO->load($pro->productid);
            switch ($Programsettingdata->Inventoryevaluation) {
                case "first":
                    $buyprice = (float) $row->productBuyPrice;
                    break;
                case "last":
                    $buyprice = (float) $row->lastbuyprice;
                    break;
                case "mean":
                    $buyprice = (float) $row->meanbuyprice;
                    break;
                case "generalPrice":
                    $buyprice = (float) $row->overAllAveragePrice;
                    break;
                case "last_discount":
                    $buyprice = (float) $row->lastbuyprice_withDiscount;
                    break;
                case "mean_discount":
                    $buyprice = (float) $row->meanbuyprice_withDiscount;
                    break;
                case "tax":
                    $buyprice = (float) $row->lastbuyprice_withTax;
                    break;
                case "mean_tax":
                    $buyprice = (float) $row->meanbuyprice_withTax;
                    break;
            }
        }

        $lastDestructionDate = '';
        if ($queryStringDestruction != '') {
            $queryStringDestruction .= " order by id desc ";
            $resturantData = $restaurantRawDestructionEX->queryByQueryString($queryStringDestruction);
            if (isset($resturantData[0])) {
                $lastDestructionDate = $resturantData[0]->sysdate;
            }
            $pro->price = $buyprice;
            $pro->lastDestructionDate = $lastDestructionDate;
        }
    }
    return $productData;
}

function getProductInStore($storeId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryWithStoreIdExt($storeId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////To show product category name (the product whole path)
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

            //new product name with all path
            $pro->productName = $pro->productName . '/' . $pathArr;

            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

function getProductInCategory($catId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryByProductQtyByCatId($catId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

function getProduct($productId) {
    global $storeDetailExt;
    global $storeReportExt;

    $productData = $storeDetailExt->queryWithProductIdExt($productId);
    if (count($productData) > 0) {
        foreach ($productData as $pro) {
            ///////////تاريخ آخر عملية إعادة جرد
            $lastDate = $storeReportExt->getLastInventoryDateByProductId($pro->productid);
            $pro->lastInventoryDate = $lastDate;

            //////////تلوين المنتجات اللي اتعملها إعادة جرد في خلال 10 أيام سابقة.
            $today = date("Y-m-d");
            $date = date("Y-m-d", strtotime('-10 day' . $today));
            $storeReportData = $storeReportExt->getlatestInventoryProducts($pro->productid, $date, $today);
            if (count($storeReportData) > 0) {
                $pro->status = 1;
            } else {
                $pro->status = 0;
            }
        }
    }
    return $productData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

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

        return fetch_recursive($newParentId, $categories);
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

?>