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


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



//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();


//Product
$productRequest = new Productrequest();
$productRequestDAO = new ProductrequestsMySqlDAO();
$productRequestExt = new ProductrequestsMySqlExtDAO();


$store = new Store();
$storeDAO = new StoreMySqlDAO();
$storeEX = new StoreMySqlExtDAO();


$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailEX = new StoredetailMySqlExtDAO();

//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

$myStoremovement = new Storemovement();
$myStoremovementRecord = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();

//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

$userdata = $userDAO->load($_SESSION['userid']);


if ($do == "getProducts") {
    $productsData = loadProductWithByName();
    $smarty->assign("productsData", $productsData);
}


## search for product in stores and get its quantity in each store
elseif ($do == "productsearch") {
    $productId = filter_input(INPUT_POST, "productId");
    $storeId = $userdata->userstoreid;

    if ($storeId == 0 || empty($storeId)) {
        $storeId = filter_input(INPUT_POST, "storeId");
    }


    $store = $storeEX->queryWithConditionExpectId($storeId);
    $storeCount = 0;

    foreach ($store as $sStore) {
        ## get quantity of this product in each store
        $storeDetail = $storeDetailEX->queryByStoreidAndProductid($productId, $sStore->storeId);
        if ($storeDetail) {
            $sStore->storeDescription = $storeDetail->productquantity;
            $storeCount++;
        } else {
            $sStore->storeDescription = 0;
        }
    }



    $smarty->assign("store", $store);
    $smarty->assign("storeCount", $storeCount);

    $smarty->display("productrequestview/searchproducts.html"); //the template page
}

## send product request to selected store
elseif ($do == "productrequest") {

    $productId = filter_input(INPUT_POST, "productId");
    $requiredNo = filter_input(INPUT_POST, "requiredNo");
    $storeId = filter_input(INPUT_POST, "storeId");
    $requestStoreId = filter_input(INPUT_POST, "requestStoreId");

    $productRequest->productid = $productId;
    $productRequest->storeid = $storeId;

    if ($userdata->userstoreid == 0 || empty($userdata->userstoreid)) {
        $productRequest->requeststoreid = $requestStoreId;
    } else {
        $productRequest->requeststoreid = $userdata->userstoreid;
    }



    $productRequest->productnoreq = $requiredNo;
    $productRequest->productnoaccept = 0;
    $productRequest->useridadd = $_SESSION['userid'];
    $productRequest->useridresponse = 0;
    $productRequest->status = 0;
    $productRequest->seen = 0;
    $productRequest->deleted = 0;

    try {
        $productRequestDAO->insert($productRequest);
        echo 1;
    } catch (Exception $ex) {
        echo $ex;
    }
}

## mark request as seen
elseif ($do == "seerequestnotice") {

    $requestId = filter_input(INPUT_POST, "requestId");

    $productRequest = $productRequestDAO->load($requestId);
    $productRequest->seen = 1;

    try {
        $productRequestDAO->update($productRequest);
        echo 1;
    } catch (Exception $ex) {
        echo $ex;
    }
}


## make request decision
elseif ($do == "requestdecision") {

    $requestId = filter_input(INPUT_POST, "requestId");
    $decision = filter_input(INPUT_POST, "decision");
    $approvedNo = filter_input(INPUT_POST, "approvedNo");
    $result = 1;

    $productRequest = $productRequestDAO->load($requestId);

    try {

        if ($decision == 2 && $productRequest->status == 0) {  ## move product from store to other
            $storeDetail = $storeDetailEX->getProductQuantity($productRequest->productid, $productRequest->storeid);
            if ($approvedNo > $storeDetail->productquantity) {
                $result = 2;
            } else {
                $productRequest->productnoaccept = $approvedNo;
                $productRequestDAO->update($productRequest);
                moveToStore($productRequest->productid, $approvedNo, $productRequest->storeid, $productRequest->requeststoreid);
            }
        }

        if ($productRequest->status == 0 && $result == 1) {
            $productRequest->status = $decision;
            $productRequest->useridresponse = $_SESSION['userid'];
            $productRequestDAO->update($productRequest);
        }

        echo $result;
    } catch (Exception $ex) {
        echo $ex;
    }
}

function moveToStore($productId, $approvedNo, $storeFrom, $storeTo) {
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailEX;
    global $myStoremovement;
    global $myStoremovementRecord;

    ## source store
    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeFrom);
    $productbeforeFrom = $storeDetail->productquantity;
    $productafterFrom = $productbeforeFrom - $approvedNo;
    $storeDetail->productquantity = $productafterFrom;
    $storeDetailDAO->update($storeDetail);



    ## destination store
    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeTo);
    if (count($storeDetail) < 1) {
//insert in storedetail tbl
        insertStoredetail($storeTo, $productId, 0);
        $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeTo);
    }

    $productbeforeTo = $storeDetail->productquantity;
    $productafterTo = $productbeforeTo + $approvedNo;
    $storeDetail->productquantity = $productafterTo;
    $storeDetailDAO->update($storeDetail);



    $myStoremovement->conditions = 0;
    $myStoremovement->storeidfrom = $storeFrom;
    $myStoremovement->storeidto = $storeTo;
    $myStoremovement->transferproductdate = date("Y-m-d");
    $myStoremovement->userid = $_SESSION["userid"];
    $myStoremovement->productid = $productId;
    $myStoremovement->transferproductamount = $approvedNo;
    $myStoremovement->operationnum = 0;
    $myStoremovement->comment = 'طلب منتج من فرع اخر ';
    $transferproductId = $myStoremovementRecord->insert($myStoremovement);

    //insert in storereport
    insertStorereport($productId, $storeFrom, $approvedNo, $productbeforeFrom, $productafterFrom, 1, $transferproductId, "طلب منتج من فرع اخر", "productrequest.php");
    insertStorereport($productId, $storeTo, $approvedNo, $productbeforeTo, $productafterTo, 0, $transferproductId, "طلب منتج من فرع اخر", "productrequest.php");
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount) {
    global $storeDetail;
    global $storeDetailDAO;

    $storeDetail->userid = $_SESSION['userid'];
    $storeDetail->storedetaildate = date("Y-m-d");
    $storeDetail->productquantity = $productChangeAmount;
    $storeDetail->storeid = $storeid;
    $storeDetail->productid = $productid;

    $storeDetailDAO->insert($storeDetail);
}

function loadProductWithByName() {
    global $productExt;

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

    $name = $_GET['term']; //It could be product name or category name

    $productsData = $productExt->queryByNameExtWithoutLimit($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;
            array_push($return_arr, $row_array);
        }
    }


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

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
    //print($parentid."<br>");
    $catData = $productCatExt->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;
}

function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

?>