<?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");
include_once("dailyentryfun.php");

//here the db files that include in the file
// GOES HERE ....................
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');

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

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

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


//Breadcrumb
require_once("../library/breadcrumb.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 :-storeCTRL

  OPERTATION in Controller

  1-display add form
  2- add in storerawmaterails tble
  3-display sucess or error
  4-display show and delete
  5-display edit
  ======================== */


//here the global templates
$smarty->display("header.html");



//Store
$myStore = new Store();
$myStoreRecord = new StoreMySqlDAO();
$myStoreEx = new StoreMySqlExtDAO();

//Storedetail
$myStoredetailRecord = new StoredetailMySqlDAO();

//Breadcrumb
$breadcrumbObject = new Breadcrumb();


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

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


//check and use the condetion that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");


    //breadcrumb
    $breadcrumbObject->add('المخازن><a href="storeController.php?do=show">المخازن</a> > اضافة مخزن', 'storeController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);



    //here the smarty templates
    $smarty->display("storeview/add.html");
} elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");

    try {
        // here the function that do the action
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

    $storeData = show();
//    var_dump($storeData);

    $Programsettingdata = $ProgramsettingDAO->load(1);
//    $smarty->assign("Programsettingdata", $Programsettingdata);
    foreach ($storeData as $story) {
        switch ($Programsettingdata->Inventoryevaluation) {
            case "first":
                $totQtyPrice = (float) $story->tot_productBuyPrice;
                break;
            case "last":
                $totQtyPrice = (float) $story->tot_lastbuyprice;
                break;
            case "mean":
                $totQtyPrice = (float) $story->tot_meanbuyprice;
                break;
            case "last_discount":
                $totQtyPrice = (float) $story->tot_lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $totQtyPrice = (float) $story->tot_meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $totQtyPrice = (float) $story->tot_overAllAveragePrice;
                break;
            case "tax":
                $totQtyPrice = (float) $story->lastbuyprice_withTax;
                break;
            case "mean_tax":
                $totQtyPrice = (float) $story->meanbuyprice_withTax;
                break;
        }
        $story->totQtyPrice2 = $totQtyPrice;
    }

    $smarty->assign("storeData", $storeData);


    //breadcrumb
    $breadcrumbObject->add('المخازن><a href="storeController.php?do=show">المخازن</a> > عرض المخازن', 'storeController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("storeview/show.html");

    $smarty->assign("customBank", 1);
    $smarty->assign("customCheck", 1);
} elseif ($do == "delete") {
    include_once("../public/authentication.php");

    // here the function that do the action

    $storeId = $_GET['storeId'];
    $storedeleteValid = delete($storeId);

    if ($storedeleteValid[1] == 0) {
        header("location:?do=sucess");
    } elseif ($storedeleteValid[1] == 2) {
        $url = "storeController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لقد حدث خطأ اثناء اجراء العملية";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    } else {
        $url = "storeController.php?do=show";
        $smarty->assign('urldirect', $url);
        $note = "لا يمكن حذف  هذا المخزن الا بعد حذف كل البيانات المرتبطه به";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "returndelete") {
    include_once("../public/authentication.php");

    $storeId = $_GET['storeId'];
    try {
        // here the function that do the action
        returndelete($storeId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "deletetemp") {
    include_once("../public/authentication.php");

    $storeId = $_GET['storeId'];
    try {
        // here the function that do the action
        deletetemp($storeId);
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    //here the permssion check
    include_once("../public/authentication.php");

    $loadData = edit();
    $smarty->assign("loadData", $loadData);


    //breadcrumb
    $breadcrumbObject->add('المخازن><a href="storeController.php?do=show">المخازن</a> > تعديل مخزن', 'storeController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("storeview/edit.html");
}



//edit  update
elseif ($do == "update") {

    //here the permssion check
    include_once("../public/authentication.php");
    //
    try {
        // here the function that do the action
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
}



//edit  update
elseif ($do == "executeOperation") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    executeOperation();

    $storeData = show();

    $Programsettingdata = $ProgramsettingDAO->load(1);
//    $smarty->assign("Programsettingdata", $Programsettingdata);
    foreach ($storeData as $story) {
        switch ($Programsettingdata->Inventoryevaluation) {
            case "first":
                $totQtyPrice = (float) $story->tot_productBuyPrice;
                break;
            case "last":
                $totQtyPrice = (float) $story->tot_lastbuyprice;
                break;
            case "mean":
                $totQtyPrice = (float) $story->tot_meanbuyprice;
                break;
            case "last_discount":
                $totQtyPrice = (float) $story->tot_lastbuyprice_withDiscount;
                break;
            case "mean_discount":
                $totQtyPrice = (float) $story->tot_meanbuyprice_withDiscount;
                break;
            case "generalPrice":
                $totQtyPrice = (float) $story->tot_overAllAveragePrice;
                break;
            case "tax":
                $totQtyPrice = (float) $story->tot_lastbuyprice_withTax;
                break;
            case "mean_tax":
                $totQtyPrice = (float) $story->tot_meanbuyprice_withTax;
                break;
        }
        $story->totQtyPrice2 = $totQtyPrice;
    }
    $smarty->assign("storeData", $storeData);


    //breadcrumb
    $breadcrumbObject->add('المخازن><a href="storeController.php?do=show">المخازن</a> > عرض المخازن', 'storeController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    $smarty->display("storeview/show.html");

    $smarty->assign("customBank", 1);
    $smarty->assign("customCheck", 1);
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}



$smarty->assign("customStore", 1);

$smarty->assign("customValidation", 1);

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

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

// add in Storerawmaterial tbl
function add() {

    //to use the variable out side the funcion
    global $myStore;
    global $myStoreRecord;


    $storeName = $_POST['storeName'];
    $storeDescription = $_POST['storeDescription'];


    //add in Store tbl
    $myStore->conditions = 0;
    $myStore->storeDate = date("Y-m-d");
    $myStore->storeName = $storeName;
    $myStore->userId = $_SESSION["userid"];

    $myStoreRecord->insert($myStore, $storeDescription);

    $treeId = addTreeElement($storeName, 49, 3, 0, 1, '', 0, 0);
    $treeIdBetween = addTreeElement($storeName . " وسيط", 49, 3, 0, 1, '', 0, 0);
    $myStore->treeId = $treeId;
    $myStore->treeIdBetween = $treeIdBetween;
    $myStoreRecord->update($myStore, $storeDescription);
}

//show
function show() {

    //to use the variable out side the funcion
    global $myStoreEx;

//    $storeData = $myStoreEx->queryWithOrderWithQuantityAndPrice();



    if ($_SESSION['searchinonestore'] == 0) {
        if ($_SESSION['storeids'] == 0) {
            $storeData = $myStoreEx->storeEvaluationAtAllPrices();
        }else{
            $queryString = ' and store.storeId in (' . $_SESSION['storeids'] . ')';
            $storeData = $myStoreEx->storeEvaluationAtAllPrices($queryString);
        }
    }else{
        $queryString = ' and store.storeId = '.$_SESSION['storeid'].' ';
        $storeData = $myStoreEx->storeEvaluationAtAllPrices($queryString);
    }
    

    return $storeData;
}

//show
function delete($storeId) {

    //to use the variable out side the funcion
    global $myStoreRecord;
    global $myStoredetailRecord;

    try {
        if (!empty($storeId)) {
            $storedetailData = $myStoredetailRecord->queryByStoreid($storeId);
            if (count($storedetailData) <= 0) {
                $storedeleteValid = 0;

                $oldStore = $myStoreRecord->load($storeId);
                delTreeElementById($oldStore->treeId);
                delTreeElementById($oldStore->treeIdBetween);
                $myStoreRecord->delete($storeId);
                $note = "success";
            } else {
                $storedeleteValid = 1;
                $note = "لا يمكن حذف  هذا المخزن";
            }
        } else {
            $storedeleteValid = 2;
            $note = "حدث خطأ أثناء حذف المخزن";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء حذف المخزن";
    }


    return array($note, $storedeleteValid);
}

//deletetemp Store tbl
function deletetemp($storeId) {
    //to use the variable out side the funcion
    global $myStore;
    global $myStoreEx;


    try {
        if (!empty($storeId)) {
            $myStore->conditions = 1;
            $myStore->storeDate = date("Y-m-d");
            $myStore->userId = $_SESSION["userid"];
            $myStore->storeId = $storeId;

            $myStoreEx->updateConditions($myStore);

            $note = "success";
        } else {
            $note = "حدث خطأ أثناء إخفاء المخزن";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء إخفاء المخزن";
    }

    return $note;
}

//returndelete Store tbl
function returndelete($storeId) {
    //to use the variable out side the funcion
    global $myStore;
    global $myStoreEx;


    try {
        if (!empty($storeId)) {
            $myStore->conditions = 0;
            $myStore->storeDate = date("Y-m-d");
            $myStore->userId = $_SESSION["userid"];
            $myStore->storeId = $storeId;

            $myStoreEx->updateConditions($myStore);


            $note = "success";
        } else {
            $note = "حدث خطأ أثناء اظهار المخزن";
        }
    } catch (Exception $e) {
        $note = "حدث خطأ أثناء اظهار المخزن";
    }

    return $note;
}

//edit from Store tbl
function edit() {
    //to use the variable out side the funcion
    global $myStoreRecord;

    //get Variable
    $storeId = $_GET['storeId'];

    $loadData = $myStoreRecord->load($storeId);

    return $loadData;
}

function update() {
    //to use the variable out side the funcion
    global $myStore;
    global $myStoreRecord;
    global $accountsTreeDAO;


    $storeName = $_POST['storeName'];
    $storeDescription = $_POST['storeDescription'];
    $conditions = $_POST['conditions'];
    $storeId = $_POST['storeId'];
    $storeDate = $_POST['storeDate'];

    $myStore = $myStoreRecord->load($storeId);

    //update data in Store tbl
    $myStore->conditions = $conditions;
    $myStore->storeDate = $storeDate;
    $myStore->storeName = $storeName;
    $myStore->userId = $_SESSION["userid"];
    $myStore->storeId = $storeId;

    $myStoreRecord->update($myStore, $storeDescription);



    $getRow = $accountsTreeDAO->load($myStore->treeId);
    $getRow->name = $storeName;
    $getRow->customName = $storeName;
    $var = editTreeElement($getRow);

    $getRow = $accountsTreeDAO->load($myStore->treeIdBetween);
    $getRow->name = $storeName . " وسيط";
    $getRow->customName = $storeName . " وسيط";
    $var = editTreeElement($getRow);
}

function executeOperation() {
    //to use the variable out side the funcion
    global $myStoreRecord;
    global $smarty;

    $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        foreach ($choosedItemArr as $storeId) {

            //get store name
            $storeData = $myStoreRecord->load($storeId);
            $storeName = $storeData->storeName;

            if ($operationType == '1') {
                //tempdelete
                $note = deletetemp($storeId);
                if ($note != "success") {
                    $outputString .= $storeName . ": " . $note . "<br/>";
                } else {
                    $outputString .= $storeName . ": " . "تمت العملية بنجاح <br/>";
                }
            } elseif ($operationType == "2") {
                //returndelete
                $note = returndelete($storeId);
                if ($note != "success") {
                    $outputString .= $storeName . ": " . $note . "<br/>";
                } else {
                    $outputString .= $storeName . ": " . "تمت العملية بنجاح <br/>";
                }
            } elseif ($operationType == "3") {
                //returndelete
                $note = delete($storeId);

                if ($note[0] != "success") {
                    $outputString .= $storeName . ": " . $note[0] . "<br/>";
                } else {
                    $outputString .= $storeName . ": " . "تمت العملية بنجاح <br/>";
                }
            }
        }

        $smarty->assign("outputString", $outputString);
    }
}

?>