<?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");
//Buybill
require_once('../models/dao/BuybillDAO.class.php');
require_once('../models/dto/Buybill.class.php');
require_once('../models/mysql/BuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybillMySqlExtDAO.class.php');
//Buybilldetail
require_once('../models/dao/BuybilldetailDAO.class.php');
require_once('../models/dto/Buybilldetail.class.php');
require_once('../models/mysql/BuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuybilldetailMySqlExtDAO.class.php');
//Returnbuybill
require_once('../models/dao/ReturnbuybillDAO.class.php');
require_once('../models/dto/Returnbuybill.class.php');
require_once('../models/mysql/ReturnbuybillMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybillMySqlExtDAO.class.php');
//Returnbuybilldetail
require_once('../models/dao/ReturnbuybilldetailDAO.class.php');
require_once('../models/dto/Returnbuybilldetail.class.php');
require_once('../models/mysql/ReturnbuybilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/ReturnbuybilldetailMySqlExtDAO.class.php');
//Buyandruternbill
require_once('../models/dao/BuyandruternbillDAO.class.php');
require_once('../models/dto/Buyandruternbill.class.php');
require_once('../models/mysql/BuyandruternbillMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbillMySqlExtDAO.class.php');
//Buyandruternbilldetail
require_once('../models/dao/BuyandruternbilldetailDAO.class.php');
require_once('../models/dto/Buyandruternbilldetail.class.php');
require_once('../models/mysql/BuyandruternbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/BuyandruternbilldetailMySqlExtDAO.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');
//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');
//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');
//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');
//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');

//Soldserialproduct
require_once('../models/dao/SoldserialproductDAO.class.php');
require_once('../models/dto/Soldserialproduct.class.php');
require_once('../models/mysql/SoldserialproductMySqlDAO.class.php');
require_once('../models/mysql/ext/SoldserialproductMySqlExtDAO.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'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

/* ======================

  Controller Name :- buyBillController

  OPERTATION in Controller

  1- تكويد المنتجات

  ======================== */

//here the global templates
$smarty->display("header.html");
//Buybill
$buyBill = new Buybill();
$buyBillDAO = new BuybillMySqlDAO();
$buyBillExt = new BuybillMySqlExtDAO();

//Buybilldetail
$buyBillDetail = new Buybilldetail();
$buyBillDetailDAO = new BuybilldetailMySqlDAO();
$buyBillDetailExt = new BuybilldetailMySqlExtDAO();

//Returnbuybill
$Buyandruternbill = new Buyandruternbill();
$BuyandruternbillDAO = new BuyandruternbillMySqlDAO();
$BuyandruternbillEX = new BuyandruternbillMySqlExtDAO();

//Soldserialproduct
$Soldserialproduct = new Soldserialproduct();
$SoldserialproductDAO = new SoldserialproductMySqlDAO();
$SoldserialproductEX = new SoldserialproductMySqlExtDAO();

//Buyandruternbilldetail
//print_r($_SESSION['hidecat'].'vvvvvvvvvvvvvv<br>');
//Productserial
$productSerial = new Productserial();
$productSerialDAO = new ProductserialMySqlDAO();
$productSerialExt = new ProductserialMySqlExtDAO();
//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

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

//Programsetting
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$programSettingExt = new ProgramsettingsMySqlExtDAO();

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

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

$today = date("Y-m-d");
$smarty->assign("today", $today);

$smarty->assign("hidecat", $_SESSION['hidecat']);
//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");
    header("location:?do=show");
} elseif ($do == "show") {

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

    $productCatData = $productCatExt->getProductCatParents();
    $smarty->assign("productCatData", $productCatData);

    $catWithProduct = loadProductCategories();
    $smarty->assign("catWithProduct", $catWithProduct);

    $allproductserail = getallproductserail();
    $smarty->assign("allproductserail", $allproductserail);

    $productserailid = $_REQUEST["productserailid"];

    if (isset($productserailid) && $productserailid != -1) {

        $productdata = show($productserailid);
        $smarty->assign("productdata", $productdata);
        $smarty->assign("countproductdata", count($productdata));

        //print_r($productdata);
        $text = $productSerialExt->queryallExbyidExt($productserailid);
        $message = "تقرير منتج بالباركود " . "(" . $text->serialnumber . "_" . $text->productName . ")";
        $smarty->assign("message", $message);
    }

    $smarty->display("productserailreportview/show.html");
} elseif ($do == "showvalidity") {

    $allproductserail = getallproductserail();
    $smarty->assign("allproductserail", $allproductserail);

    $daynumber = $_REQUEST["daynumber"];
    $condition = $_REQUEST["condition"];
    $productSearchId = (int) $_REQUEST['productId'];
    if (isset($condition) && $condition != -1) {
        if (!empty($productSearchId)) {
            $productData = $productExt->loadProduct($productSearchId);
            $message .= "تقرير صلاحية منتج <h4>" . $productData->productName . "/ " . $productData->productCatName . " " . $condition . " " . $daynumber . " يوم";
        } else {
            $message = "تقرير صلاحية منتج " . $condition . " " . $daynumber . " يوم";
        }

        $smarty->assign("message", $message);
        showvalidity($condition, $daynumber, $productSearchId);
    }
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("productserailreportview/showvalidity.html");
} elseif ($do == "tempdelete") {

    //here the permssion check
    include_once("../public/authentication.php");
    $id = $_REQUEST["id"];
    $url = "productserailreportController.php?do=show&productserailid=" . $id;
    try {

        delserail();
        $smarty->assign('urldirect', $url);
        $note = "تمت العملية بنجاح";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } catch (Exception $e) {
        $smarty->assign('urldirect', $url);
        $note = "حدث خطا اثناء اجراء العمليه";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("settlementstoreshow", 1);
//here the global templates
$smarty->display("footer.html");

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

function getProductCatId($productId) {
    global $productExt;
    $catId = $productExt->getProductCatId($productId);
    return $catId;
}

function getallproductserail() {
    global $productSerial;
    global $productSerialDAO;
    global $productSerialExt;


    $alldata = $productSerialExt->queryallEx();
    return $alldata;
}

function delserail() {
    global $productSerial;
    global $productSerialDAO;
    global $productSerialExt;

    $id = $_GET["id"];
    $del = $_GET["del"];
    $productSerialExt->updatedel($id, $del);
}

function show($productserailid) {
    global $productSerial;
    global $productSerialDAO;
    global $productSerialExt;

    global $Soldserialproduct;
    global $SoldserialproductDAO;
    global $SoldserialproductEX;

    $productdata = $productSerialExt->queryallExbyid($productserailid);
    $now = new DateTime(date('Y-m-d H:i:s'));
    foreach ($productdata as $pro) {
        ///////////To show product category name (the product whole path)
        $parentId = $pro->productCatId;
        //names of product's parents
        $pathArr = getProductPath_recursive($parentId, $categories);

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

        //calc remaining days using "date_interval_format() Function" or "DateInterval::format"
        $endDate = $pro->enddate . ' ' . date('H:i:s'); ##take time part with the date to make accurate calculation
        $endDate = new DateTime($endDate);
        $interval = $now->diff($endDate);
        $pro->diff = (int) $interval->format('%r%a'); //a - Total number of days as a result of date_diff()//r - Sign "-" when negative, empty when positive
    }
    return $productdata;
}

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

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

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

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

function showvalidity($condition, $daynumber, $productSearchId) {
    global $productSerial;
    global $productSerialDAO;
    global $productSerialExt;

    global $smarty;
    $now = new DateTime(date('Y-m-d H:i:s'));
    $queryString = '';
    if ($productSearchId > 0) {
        $queryString = ' and productserial.productid = ' . $productSearchId . ' ';
    }
    $productsData = $productSerialExt->queryallExbydiffExt2($condition, $daynumber, $queryString);
    foreach ($productsData as $pro) {
        ///////////To show product category name (the product whole path)
        //calc remaining days using "date_interval_format() Function" or "DateInterval::format"
        $endDate = $pro->enddate . ' ' . date('H:i:s'); ##take time part with the date to make accurate calculation
        $endDate = new DateTime($endDate);
        $interval = $now->diff($endDate);
        $pro->different = (int) $interval->format('%r%a'); //a - Total number of days as a result of date_diff()//r - Sign "-" when negative, empty when positive
        //print_r($_SESSION['hidecat'].'vvvvvvvvvvvvvv<br>');
        //new product name with all path
        if ($_SESSION['hidecat'] == 1) {
            $parentId = $pro->productCatId;
            //names of product's parents
            $pathArr = getProductPath_recursive($parentId, $categories);
            $pro->productName = $pro->productName . '/' . $pathArr;
        } else {
            $pro->productName = $pro->productName;
        }
    }
    $smarty->assign('productsData', $productsData);
}

function loadProductCategories() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;

    //NOTICE: select categories which have products in it only, not all categories.
    $productsData = $productExt->queryAllProducts();

    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;
}
?>