<?php

///***************************** إعادة الجرد ********************///
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("addAjax");
//the global file operation
if (!in_array($do, $ajaxDoArr)) {
    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');
//Productserial
require_once('../models/dao/ProductserialDAO.class.php');
require_once('../models/dto/Productserial.class.php');
require_once('../models/mysql/ProductserialMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductserialMySqlExtDAO.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
if (!in_array($do, $ajaxDoArr)) {
    $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();

//Productserial
$Productserial = $myProductserial = new Productserial();
$ProductserialDAO = new ProductserialMySqlDAO();
$ProductserialEX = $myProductserialEx = new ProductserialMySqlExtDAO();

$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("inventoryexpirationview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    try {
        add();

        $url = "inventoryexpirationController.php";
        $smarty->assign('urldirect', $url);
        $note = "تمت عملية الجرد";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {

        echo $e;
        /* $url = "inventoryController.php?";
          $smarty->assign('urldirect', $url);
          $note ="حدث خطأ ... يرجى المحاولة مرة أخرى";
          $smarty->assign('msgnote', $note);
          $smarty->display("notes.html"); */
    }
} elseif ($do == "addAjax") {
    addAjax();
}
//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    $smarty->assign("inventoryexpirationScripts", 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 $Productserial;
    global $ProductserialDAO;
    global $ProductserialEX;
    global $today;

    $itr = $_POST['itr'];
    $delIds = $_POST["delIds"];
    $delIds = rtrim($delIds, ',');
    if ($delIds != "" && isset($delIds))
        $ProductserialEX->deleteByQuerySting(" and productserailid in($delIds) ");
    for ($i = 1; $i <= $itr; $i++) {
        $productid = $_POST['productid' . $i . ''];
        $sizeid = (int) $_POST['sizeid' . $i . ''];
        $colorid = (int) $_POST['colorid' . $i . ''];
        $totalproduct = $_POST['totalproduct' . $i . ''];
        $storeid = (int) $_POST['storeid' . $i . ''];

        if (isset($productid) && !empty($productid) && isset($storeid) && !empty($storeid)) {
            for ($x = 1; $x <= $totalproduct; $x++) {


                $productserailid = (int) $_POST['productserailid' . $x . '_' . $i . ''];
                $serialnumber = $_POST['serialnumber' . $x . '_' . $i . ''];
                $comment = $_POST['comment' . $x . '_' . $i . ''];
                $stratdate = $_POST['stratdate' . $x . '_' . $i . ''];
                $enddate = $_POST['enddate' . $x . '_' . $i . ''];
                $quantity = $_POST['quantity' . $x . '_' . $i . ''];
                $chassisNo = $_POST['chassisNo' . $x . '_' . $i . ''];
                $motorNo = $_POST['motorNo' . $x . '_' . $i . ''];
                $theColor = $_POST['theColor' . $x . '_' . $i . ''];
                if (empty($serialnumber)) {
                    $serialnumber = getserail(6, $productid);
                }
                $Productserial->productserailid = $productserailid;
                $Productserial->enddate = $enddate;
                $Productserial->productid = $productid;
                $Productserial->serialnumber = $serialnumber;
                $Productserial->startdate = $stratdate;
                $Productserial->type = 0;
                $Productserial->don = $quantity;
                $Productserial->storeid = $storeid;
                $Productserial->sizeid = $sizeid;
                $Productserial->colorid = $colorid;
                $Productserial->chassisNo = $chassisNo;
                $Productserial->motorNo = $motorNo;
                $Productserial->theColor = $theColor; //of car
                //print_r($Productserial);
                //print_r("<br>");
                if (isset($serialnumber) && $serialnumber != "" && isset($quantity) && $quantity != "") {
                    if ($productserailid > 0) {
                        $ProductserialDAO->update($Productserial, $comment);
                    } else {
                        $Productserial->billid = 0;
                        $Productserial->buybilldetailid = 0;
                        $ProductserialDAO->insert($Productserial, $comment);
                    }
                }
            }
        }
    }
}

function addAjax() {
    global $Productserial;
    global $ProductserialDAO;
    global $ProductserialEX;
    global $today;

    $returnArr = array();
    $itr = $i = $_POST['x'];
    $delIds = $_POST["delIds$i"];
    $delIds = rtrim($delIds, ',');
    if ($delIds != "" && isset($delIds))
        $ProductserialEX->deleteByQuerySting(" and productserailid in($delIds) ");

    $productid = $_POST['productid' . $i . ''];
    $sizeid = (int) $_POST['sizeid' . $i . ''];
    $colorid = (int) $_POST['colorid' . $i . ''];
    $totalproduct = $_POST['totalproduct' . $i . ''];
    $storeid = (int) $_POST['storeid' . $i . ''];

    if (isset($productid) && !empty($productid) && isset($storeid) && !empty($storeid)) {
        for ($x = 1; $x <= $totalproduct; $x++) {


            $productserailid = (int) $_POST['productserailid' . $x . '_' . $i . ''];
            $serialnumber = $_POST['serialnumber' . $x . '_' . $i . ''];
            $comment = $_POST['comment' . $x . '_' . $i . ''];
            $stratdate = $_POST['stratdate' . $x . '_' . $i . ''];
            $enddate = $_POST['enddate' . $x . '_' . $i . ''];
            $quantity = $_POST['quantity' . $x . '_' . $i . ''];
            $chassisNo = $_POST['chassisNo' . $x . '_' . $i . ''];
            $motorNo = $_POST['motorNo' . $x . '_' . $i . ''];
            $theColor = $_POST['theColor' . $x . '_' . $i . ''];
            if (empty($serialnumber)) {
                $serialnumber = getserail(6, $productid);
            }
            $Productserial->productserailid = $productserailid;
            $Productserial->enddate = $enddate;
            $Productserial->productid = $productid;
            $Productserial->serialnumber = $serialnumber;
            $Productserial->startdate = $stratdate;
            $Productserial->type = 0;
            $Productserial->don = $quantity;
            $Productserial->storeid = $storeid;
            $Productserial->sizeid = $sizeid;
            $Productserial->colorid = $colorid;
            $Productserial->chassisNo = $chassisNo;
            $Productserial->motorNo = $motorNo;
            $Productserial->theColor = $theColor; //of car
            //print_r($Productserial);
            //print_r("<br>");
            if (isset($serialnumber) && $serialnumber != "" && isset($quantity) && $quantity != "") {
                if ($productserailid > 0) {
                    $ProductserialDAO->update($Productserial, $comment);
                } else {
                    $Productserial->billid = 0;
                    $Productserial->buybilldetailid = 0;
                    $productserailid = $ProductserialDAO->insert($Productserial, $comment);
                }
                array_push($returnArr, array('itr' => $x . '_' . $i, 'productserailid' => $productserailid));
            }
        }
    }
    echo json_encode(array('status' => 1, 'result' => $returnArr));
}

function getserail($length = 6, $productid) {
    global $Productserial;
    global $ProductserialEX;
    global $ProductserialDAO;

    //global $serialArray;

    $serialArray = $_SESSION["serialarray"];

    //print_r($serialArray);
    //$productid=$_REQUEST["productid"];
    $characters = '0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    //check if this parcode already exists
    $data = $ProductserialEX->queryAllbyserial($randomString);
    if (count($data) > 0 || @in_array($randomString, $serialArray)) {

        //print_r('in if <br>');
        getserail(6, $productid);
    }

    $serialArray[$randomString] = $randomString;
    $_SESSION["serialarray"] = $serialArray;

    return $randomString;
}

?>