<?php

@session_start();
@ob_start();

if (!ini_get('date.timezone')) {
    date_default_timezone_set('GMT'); //Asia/Riyadh
}
include("../public/include_dao.php");

include_once("noticefunctions.php");

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');

//Menuurl
require_once('../models/dao/MenuurlDAO.class.php');
require_once('../models/dto/Menuurl.class.php');
require_once('../models/mysql/MenuurlMySqlDAO.class.php');
require_once('../models/mysql/ext/MenuurlMySqlExtDAO.class.php');

//Relusergroupproperties
require_once('../models/dao/RelusergrouppropertiesDAO.class.php');
require_once('../models/dto/Relusergrouppropertie.class.php');
require_once('../models/mysql/RelusergrouppropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/RelusergrouppropertiesMySqlExtDAO.class.php');

//Notics
require_once('../models/dao/NoticsDAO.class.php');
require_once('../models/dto/Notic.class.php');
require_once('../models/mysql/NoticsMySqlDAO.class.php');
require_once('../models/mysql/ext/NoticsMySqlExtDAO.class.php');


//Languages
require_once('../models/dao/LanguagesDAO.class.php');
require_once('../models/dto/Language.class.php');
require_once('../models/mysql/LanguagesMySqlDAO.class.php');
require_once('../models/mysql/ext/LanguagesMySqlExtDAO.class.php');

//Menuurl
$Menuurl = new Menuurl();
$MenuurlDAO = new MenuurlMySqlDAO();
$MenuurlEX = new MenuurlMySqlExtDAO();


//Usergroup
$Usergroup = new Usergroup();
$UsergroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();

//Notics
$Notics = new Notic();
$NoticsDAO = new NoticsMySqlDAO();
$NoticsExt = new NoticsMySqlExtDAO();

//user
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();



//Language
$languages = new Language();
$languagesDAO = new LanguagesMySqlDAO();
$languagesEX = new LanguagesMySqlExtDAO();

//Relusergroupproperties
$myRelusergrouppropertiesRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergrouppropertiesEx = new RelusergrouppropertiesMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

$sessionUserId = $_SESSION['userid'];
$userGroupIDs = $_SESSION['usergroupid'];
if (empty($sessionUserId) || empty($userGroupIDs)) {
    //this condition is repeated in comming lines it will make logout but with empty() check
    //but we will try to login with obgy first
    if (!empty($_SESSION['user_id']) && !empty($_SESSION['erpDB'])) {
        header("location:login.php?do=en");
        exit();
    }
}

if (isset($_SESSION['usergroupid']) && $_SESSION['usergroupid'] != "") {
    $myusergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("Usergroupdata", $myusergroupdata);
}



$_SESSION['hidecat'] = $myusergroupdata->hidecat;
$_SESSION['clientnegative'] = $myusergroupdata->clientnegative;
$_SESSION['suplliernegative'] = $myusergroupdata->suplliernegative;
$_SESSION['storenegative'] = $myusergroupdata->storenegative;

$prog = $ProgramsettingDAO->load(1);
//var_dump($prog);
##set time zone
date_default_timezone_set($prog->timezone);
//echo date_default_timezone_get();
if (empty($prog->currancy)) {
    $prog->currancy = "ريال";
}

$language = $languagesDAO->queryAll();
if (count($language) > 0) {
    $smarty->assign("language", $language);
}
eval(base64_decode("ZnVuY3Rpb24gaGFuZGxlU3luY1VzZXJzKCR1c2VyaWQpIHsKICAgIGdsb2JhbCAkbXlVc2VyUmVjb3JkOwogICAgZ2xvYmFsICRteVVzZXJFeDsKICAgIGlmIChpc3NldCgkX1NFU1NJT05bJ2xpY19zeW5jdXNlcnMnXSkgJiYgJF9TRVNTSU9OWydsaWNfc3luY3VzZXJzJ10gPT0gIjEiKSB7CiAgICAgICAgJGFsbG93U3luYyA9ICRfU0VTU0lPTlsnbGljX3N5bmN1c2VycyddOwogICAgICAgICRzeW5jVGltZSA9ICRfU0VTU0lPTlsnbGljX3N5bmN0aW1lJ107CiAgICAgICAgLy9zeW5jIHVzZXJzIG5vdCBhbGxvd2VkCiAgICAgICAgJG15dXNlciA9ICRteVVzZXJSZWNvcmQtPmxvYWQoJHVzZXJpZCk7CiAgICAgICAgaWYgKCFpc3NldCgkc3luY1RpbWUpIHx8IGVtcHR5KCRzeW5jVGltZSkpIHsKICAgICAgICAgICAgJHN5bmNUaW1lID0gMDsKICAgICAgICB9CiAgICAgICAgIyN1c2VyIGZyb20gZGlmZnJlbnQgZGl2aWNlIHRyeSB0byB1c2UgdGhlIGFjY291bnQKICAgICAgICBpZiAoJG15dXNlci0+bG9naW5pcCAhPSAkX1NFUlZFUlsnUkVNT1RFX0FERFInXSkgewogICAgICAgICAgICAjI2NoZWNrIHRoZSBwYXNzZWQgdGltZSBzY2luY2UgbGFzdCB1c2VkCiAgICAgICAgICAgICRzZWNvbmRzUGFzc2VkID0gc3RydG90aW1lKGRhdGUoJ1ktbS1kIEg6aTpzJykpIC0gc3RydG90aW1lKCRteXVzZXItPmxhc3RhY3RpdmV0aW1lKTsKICAgICAgICAgICAgaWYgKCRzZWNvbmRzUGFzc2VkID4gJHN5bmNUaW1lICogNjApIHsKICAgICAgICAgICAgICAgICMjMyBtaW5zIG9yIG1vcmUgcGFzc2VkCiAgICAgICAgICAgICAgICAkbXlVc2VyRXgtPnVwZGF0ZUxvZ2dpblN0YXR1cygkX1NFUlZFUlsnUkVNT1RFX0FERFInXSwgZGF0ZSgnWS1tLWQgSDppOnMnKSwgY2hlY2tEZXZpY2UoKSwgJHVzZXJpZCk7CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICAvL3NlbmQgdGhlIHVzZXIgcGFnZSB0ZWxsIGhpbSB0aGUgYWNjb3VudCBpcyBjdXJyZW50bHkgdXNlZAogICAgICAgICAgICAgICAgaGVhZGVyKCJsb2NhdGlvbjpsb2dpbi5waHA/ZG89dXNlZG5vdyIpOwogICAgICAgICAgICAgICAgZXhpdDsKICAgICAgICAgICAgfQogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICRteVVzZXJFeC0+dXBkYXRlTG9nZ2luU3RhdHVzKCRfU0VSVkVSWydSRU1PVEVfQUREUiddLCBkYXRlKCdZLW0tZCBIOmk6cycpLCBjaGVja0RldmljZSgpLCAkdXNlcmlkKTsKICAgICAgICB9CiAgICB9Cn0="));
if (isset($_SESSION['erp_lang'])) {
    $smarty->assign("lang_code", $_SESSION['erp_lang']);
} else {
    $_SESSION['erp_lang'] = 'ar';
    $smarty->assign("lang_code", $_SESSION['erp_lang']);
}


$smarty->assign("currency", $prog->currancy);
$smarty->assign("copytype", $prog->copytype);
$smarty->assign("colortype", $prog->colortype);
$smarty->assign("syncstructure", $prog->syncstructure);
$smarty->assign("db", $_SESSION['dbname']);

$myUserEx->removeUserIpForEndedSessionsUsers();


$sessionEmployeename = $_SESSION['employeename'];
if (empty($sessionUserId) || empty($userGroupIDs)) {
    //send the user to the login page
    header("location:login.php");
} else {
    handleSyncUsers($_SESSION['userid']);
    $smarty->assign("sessionEmployeename", $sessionEmployeename);
    $smarty->assign("sessionUserId", $sessionUserId);
    $smarty->assign("companyname", $prog);

    $userGroupIDs = $_SESSION['usergroupid'];


    // print_r($userGroupIDs.'vvvvvvvvvvvvvvvvvvvv');
    $reluseData = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndValue($userGroupIDs);


    //if this group not created yet
    if (count($reluseData) <= 0) {
        session_destroy();
        header("location:login.php");
    } else {
        //  print_r('in else 1');
        // print_r($myusergroupdata);
        $cashedheaderSize = 0;
        if ($myusergroupdata->hidemenu == 1) {//display
            if (file_exists('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html')) {
                $cashedheaderSize = filesize('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html');
                $cashedheaderSize = rtrim($cashedheaderSize);
            }
            $smarty->assign("cashedheaderSize", $cashedheaderSize);
            if ($cashedheaderSize > 1024) {//1024 menas 1 KB//it is needed in usergroup admin as it creates small dummy data in cash header//also this check is in html
                $cashedheader = file_get_contents("../temp__cashedheader/cashedheader_" . $_SESSION['dbname'] . "_" . $_SESSION['userid'] . ".html");
                $smarty->assign("cashedheader", $cashedheader);
            } else {
                //print_r('in if');
                $h = 1;
                foreach ($reluseData as $reluse) {
                    $propertyid = $reluse->propertyid;
                    //print_r("propertyid=".$propertyid."<br>");
                    $subReluseData = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndPropertyparent($userGroupIDs, $propertyid);

                    /* print_r("<pre><meta charset='utf-8'>");
                      print_r($subReluseData);
                      print_r("</pre>"); */
                    if (count($subReluseData) <= 0) {
                        $subReluseNum = 0;
                    } else {
                        $subReluseNum = 1;
                    }
                    $smarty->assign("subReluseNum" . $h . "", $subReluseNum);

                    $smarty->assign("subReluseData" . $h . "", $subReluseData);

                    $k = 1;
                    foreach ($subReluseData as $subReluse) {
                        $subPropertyid = $subReluse->propertyid;
//                        if ($subPropertyid == 360)
//                            echo $subPropertyid.'<br/>';
                        $subSubReluseData = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndPropertyparent($userGroupIDs, $subPropertyid);
                        /* 	print_r('<pre>');

                          print_r($subSubReluseData);
                          print_r('<pre>');

                         */
                        if (count($subSubReluseData) <= 0) {
                            $subSubReluseNum = 0;
                        } else {
                            $subSubReluseNum = 1;
                        }


                        foreach ($subSubReluseData as $thirdSub) {
                            $thirdSubData = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndPropertyparent($userGroupIDs, $thirdSub->propertyid);

                            if (count($thirdSubData) <= 0) {
                                $thirdSubNum = 0;
                            } else {
                                $thirdSubNum = 1;
                            }
//                            echo "thirdSubData" . $h . "_" . $k . "_" . $s . "";
//                            var_dump($thirdSubData);
//                            $smarty->assign("thirdSubNum" . $h . "_" . $k . "_" . $s . "", $thirdSubNum);
//                            $smarty->assign("thirdSubData" . $h . "_" . $k . "_" . $s . "", $thirdSubData);

                            $thirdSub->third = $thirdSubData;

                            $s++;
                        }

                        $smarty->assign("subSubReluseNum" . $h . "_" . $k . "", $subSubReluseNum);

                        $smarty->assign("subSubReluseData" . $h . "_" . $k . "", $subSubReluseData);

                        $s = 1;


                        $k++;
                    }

                    $h++;
                }

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

    $theRoleAndpageName_f = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndURL($userGroupIDs, PageNamectrl_f());
    $theRoleAndpageName = $myRelusergrouppropertiesEx->queryAllwithUsergroupidAndURL($userGroupIDs, PageNamectrl());

    if (count($theRoleAndpageName_f) > 0 || count($theRoleAndpageName) > 0 || PageNamectrl() == "index.php") {
        $myUserEx->updateLogginStatus($_SERVER['REMOTE_ADDR'], date('Y-m-d H:i:s'), checkDevice(), $_SESSION['userid']);
    } else {

        header("location:login.php");
    }
}
//

$idarray = array();
$x = array();
$finalnamex = "";
$allmenudata = $MenuurlDAO->queryAll();

if (count($allmenudata) > 0) {
    foreach ($allmenudata as $myallmenudata) {


        $allusergroupids = $myallmenudata->usergroupid;
        //

        $idarray = explode(',', $allusergroupids);
        //print_r($idarray);
        $kay = in_array($_SESSION['usergroupid'], $idarray);
        if ($kay) {

            $finalnamex = $finalnamex . $myallmenudata->menuurlid . ",";
        }
    }

    $allusergroupids = substr($finalnamex, 0, -1);

    if ($allusergroupids != "") {
        $alllastdata = $MenuurlEX->queryAllinarray($allusergroupids);
    }

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

/* stop calculating notice in php get it with ajax
  /////////////////////////notics////////////////////////////

  $allnotics = $NoticsDAO->queryAll();
  $sum = 0;
  foreach ($allnotics as $data) {
  $productno = $data->productno;
  $productnotsellno = $data->productnotsellno;
  $kempilano = $data->kempilano;
  $clientcheckno = $data->clientcheckno;
  $suppliercheckno = $data->suppliercheckno;

  $sum = $productno + $productnotsellno + $kempilano + $clientcheckno + $suppliercheckno;
  }
  $smarty->assign("sum", $sum);



  #################################################################  notics   #################################################################
  $sum = calcNotice() + getProductRequestNotice() + getToWorkshopOrderNotice() + getOtherRequestsNotice();
  $smarty->assign("sum", $sum); */

//$smarty->assign("sum", "  ... جارى العد ...");
function checkDevice() {
// checkDevice() : checks if user device is phone, tablet, or desktop
// RETURNS 0 for desktop, 1 for mobile, 2 for tablets,
// But i change it to return phone, tablet, or desktop directly
    $deviceType;
    if (is_numeric(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "mobile"))) {
        $deviceType = is_numeric(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "tablet")) ? 2 : 1;
    } else {
        $deviceType = 0;
    }
    //
    $devTypeText = '';
    if ($deviceType == 0) {
        $devTypeText = "DESKTOP";
    } else if ($deviceType == 1) {
        $devTypeText = "MOBILE";
    } else {
        $devTypeText = "TABLET";
    }
    return $devTypeText;
}

/* -------------------------------------------------------------------------- */
?>

