<?php

//the global file operation
include("../public/impOpreation.php");
include_once("initiateStaticSessionCommingWithCurl.php");
include_once("../library/uploadImages.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
// GOES HERE ....................
include("../public/include_dao.php");


require_once('../models/dao/BranchDAO.class.php');
require_once('../models/dto/Branch.class.php');
require_once('../models/mysql/BranchMySqlDAO.class.php');
require_once('../models/mysql/ext/BranchMySqlExtDAO.class.php');


//Bank
require_once('../models/dao/BankDAO.class.php');
require_once('../models/dto/Bank.class.php');
require_once('../models/mysql/BankMySqlDAO.class.php');
require_once('../models/mysql/ext/BankMySqlExtDAO.class.php');

//Project
require_once('../models/dao/ProjectDAO.class.php');
require_once('../models/dto/Project.class.php');
require_once('../models/mysql/ProjectMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectMySqlExtDAO.class.php');

//user
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.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');

//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.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');

//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');
//Employee
require_once('../models/dao/EmployeeDAO.class.php');
require_once('../models/dto/Employee.class.php');
require_once('../models/mysql/EmployeeMySqlDAO.class.php');
require_once('../models/mysql/ext/EmployeeMySqlExtDAO.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 :- userCTRL

  OPERTATION in Controller

  1-display add form
  2- add in user tble
  3-display sucess or error
  4-display show form
  5-delete from user tbl
  6-edit in user data

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


//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("header.html");
}



//here goes the instances and general variables
//user
$myUser = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

//usergroup
$myUserGroup = new Usergroup();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroupEx = new UsergroupMySqlExtDAO();


//Store
$Store = new Store();
$StoreDAO = new StoreMySqlDAO();
$StoreEX = new StoreMySqlExtDAO();
//save
$mySaveRecord = new SaveMySqlDAO();

//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

//Bank
$myBank = new Bank();
$myBankRecord = new BankMySqlDAO();
$myBankEx = new BankMySqlExtDAO();


//Project
$Project = new Project();
$ProjectDAO = new ProjectMySqlDAO();
$ProjectEx = new ProjectMySqlExtDAO();

//Programsetting
$programsetting = new Programsetting();
$programsettingDAO = new ProgramsettingsMySqlDAO();
$programsettingEX = new ProgramsettingsMySqlExtDAO();
//
$employee = new Employee();
$employeeDAO = new EmployeeMySqlDAO();
$employeeEX = new EmployeeMySqlExtDAO();

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

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

    $UserGroupData = loadusergroup();
    $smarty->assign("UserGroupData", $UserGroupData);

    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    $storData = loadStore();
    $smarty->assign("storData", $storData);

    $allbranchdata = $BranchDAO->queryAll();
    $smarty->assign("allbranchdata", $allbranchdata);


    $allbankdata = $myBankRecord->queryAll();
    $smarty->assign("allbankdata", $allbankdata);

    $allprojectdata = $ProjectDAO->queryAll();
    $smarty->assign("allprojectdata", $allprojectdata);

    $allCharities = R::getAll('select * from charities where del < 2');
    $smarty->assign('allCharities', $allCharities);

    $loginUsergroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);
    $smarty->assign("loginUsergroupid", $_SESSION['usergroupid']);
    $smarty->assign("loginUsergroupData", $loginUsergroupData);

    $allUsers = R::getAll('select userid,employeename from user where conditions=0 and userid > 0');
    $smarty->assign('allUsers', $allUsers);

    $programsetting = $programsettingDAO->load(1);
    $smarty->assign("programsetting", $programsetting);


    $smarty->display("userview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $UserGroupData = loadusergroup();
    $smarty->assign("UserGroupData", $UserGroupData);

    $usergroupId = $_REQUEST['usergroupid'];

    if (isset($usergroupId) && $usergroupId != "-1") {
        $groupData = $myUserGroupRecord->load($usergroupId);
        $message = "المجموعة: " . $groupData->usergroupname;
        $smarty->assign("message", $message);

        showByUsergroupId($usergroupId);
    } else {
        showAll();
    }

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

    $smarty->display("userview/show.html");
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    try {
        delete();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "deleteFinaly") {
    include_once("../public/authentication.php");
    try {
        deleteFinaly();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

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

    $UserGroupData = loadusergroup();
    $smarty->assign("UserGroupData", $UserGroupData);

    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);


    $storData = loadStore();
    $smarty->assign("storData", $storData);

    $allbranchdata = $BranchDAO->queryAll();
    $smarty->assign("allbranchdata", $allbranchdata);


    $allbankdata = $myBankRecord->queryAll();
    $smarty->assign("allbankdata", $allbankdata);

    $allprojectdata = $ProjectDAO->queryAll();
    $smarty->assign("allprojectdata", $allprojectdata);

    $allCharities = R::getAll('select * from charities where del < 2');
    $smarty->assign('allCharities', $allCharities);

    $loginUsergroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);
    $smarty->assign("loginUsergroupid", $_SESSION['usergroupid']);
    $smarty->assign("loginUsergroupData", $loginUsergroupData);

    $allUsers = R::getAll('select userid,employeename from user where conditions=0 and userid > 0');
    $smarty->assign('allUsers', $allUsers);

    $programsetting = $programsettingDAO->load(1);
    $smarty->assign("programsetting", $programsetting);


    if ($programsetting->saudielectronicinvoice == 1) {
        $userid = $_GET["userid"];
        $esaudiusersetting = R::findOne('esaudiusersetting', 'userid = ?', [$userid]);
        $smarty->assign("esaudiusersetting", $esaudiusersetting);
    }

    //here the smarty templates
    $smarty->display("userview/edit.html");
} elseif ($do == "update") {
    //here the permssion check
    include_once("../public/authentication.php");
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
$smarty->assign("customUser", 1);
//here the global templates
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

} else {
    $smarty->display("footer.html");
}

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

// select from usergroup tbl
function loadusergroup() {

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

    // select all data from usergroup tbl
    $UserGroupData = $myUserGroupRecord->queryByConditions(0);

    return $UserGroupData;
}

//select all save data
function loadSave() {

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

    //load all save data
    $saveData = $mySaveRecord->queryByConditions(0);

    return $saveData;
}

//select all save data
function loadStore() {

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

    //load all save data
    $StoreData = $StoreDAO->queryByConditions(0);

    return $StoreData;
}

// add in user tbl
function add() {

    //to use the variable out side the funcion
    global $myUser;
    global $myUserRecord;
    global $myUserEx;


    $userName = $_POST['username'];
    $passWord = $_POST['password'];
    $userstoreid = $_POST['userstoreid'];
    $userstoreidDef = $_POST['userstoreidDef'];
    $employeeName = $_POST['employeename'];
    $usergroupId = $_POST['usergroupid'];
    $saveId = $_POST['saveid'];

    $awardrate = (float) $_POST["awardrate"];
    $awardrategomla = $_POST["awardrategomla"];
    $awardratehalf = $_POST["awardratehalf"];

    $searchinonesave = (isset($_POST["searchinonesave"])) ? $_POST["searchinonesave"] : 1;
    $branchid = (int) $_POST["branchid"];
    $question = $_POST["question"];
    $answer = $_POST["answer"];
    $directSaveBills = $_POST["directSaveBills"];
    $addEmployeeToo = (int) $_POST["addEmployeeToo"];
    $salary = (float) $_POST["salary"];
    $obygyDoctorId = (int) $_POST["obygyDoctorId"];
    $viewclients = (int) $_POST["viewclients"];
    $viewbills = (int) $_POST["viewbills"];
    $showfile = (int) $_POST["showfile"];
    $closeSavid = $_POST['closeSavid'];
    #
    $storeSupervisor = (int) $_POST["storeSupervisor"];
    $storeSupervisorStores = filter_input(INPUT_POST, 'storeSupervisorStores', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $projectids = filter_input(INPUT_POST, 'projectids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $bankids = filter_input(INPUT_POST, 'bankids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $saveids = filter_input(INPUT_POST, 'saveids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $searchinonestorebalance = $_POST["searchinonestorebalance"];
    $storeids = filter_input(INPUT_POST, 'storeids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $charityids = filter_input(INPUT_POST, 'charityids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $laterNakdiUserIds = filter_input(INPUT_POST, 'laterNakdiUserIds', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

    $storeSupervisorStores_str = '';
    foreach ($storeSupervisorStores as $value) {
        $storeSupervisorStores_str .= $value . ",";
    }
    $storeSupervisorStores_str = rtrim($storeSupervisorStores_str, ',');
    ###########################



    $handle = new upload($_FILES['pdffile']);
    $pdffile = uploadImageswhioutresize($handle, "../upload/users");


    $empid = 0;
    if ($addEmployeeToo == 1) {
        $empid = (int) CURL_IT2(array('empName' => $userName, 'empSalary' => $salary), 'employeeController.php?do=add');
    }

    $myUser->searchinonesave = $searchinonesave;

    //print_r($userstoreid.'xxxxxxxxxxxxxxxx');
    //insert data in user tbl

    if ($branchid == 0) { //all) {
        $myUser->branchId = -1;
    } else {
        $myUser->branchId = $branchid;
    }

    $myUser->currentdate = date("Y-m-d");
    $myUser->conditions = 0;
    $myUser->employeename = $employeeName;
    $myUser->password = $passWord;
    $myUser->username = $userName;
    $myUser->usergroupid = $usergroupId;
    $myUser->saveid = $saveId;
    $myUser->userstoreid = $userstoreid;
    $myUser->userstoreidDef = $userstoreidDef;
    $myUser->awardrate = $awardrate;
    $myUser->awardrategomla = $awardrategomla;
    $myUser->awardratehalf = $awardratehalf;
    $myUser->webApiId = (int) $_POST['webApiId'];

    $noOfUsersInDB = $myUserEx->queryAllcountuser_f();
    //$myUser->blockedByLimits = 1;
    $myUser->blockedByLimits = 0;
    if ($_SESSION['lic_userno'] > $noOfUsersInDB) {
        $myUser->blockedByLimits = 0;
    }
    $myUser->question = $question;
    $myUser->answer = $answer;
    $myUser->directSaveBills = $directSaveBills;
    $myUser->empid = $empid;
    $myUser->obygyDoctorId = $obygyDoctorId;
    $myUser->viewclients = $viewclients;
    $myUser->viewbills = $viewbills;
    $myUser->storeSupervisor = $storeSupervisor;
    $myUser->storeSupervisorStores = $storeSupervisorStores_str;
    $myUser->closeSavid = $closeSavid;
    if (isset($projectids)) {
        if (in_array("0", $projectids)) {
            $myUser->projectids = '0';
        } else {
            $myUser->projectids = '-1,' . implode(",", $projectids);
        }
    } else {
        $myUser->projectids = '-1,';
    }

    if (isset($saveids)) {
        if (in_array("0", $saveids)) {
            $myUser->saveids = '0';
        } else {
            if (!in_array($saveId, $saveids)) {
                $myUser->saveids = $saveId . ',' . implode(",", $saveids);
            } else {
                $myUser->saveids = '-1,' . implode(",", $saveids);
            }
        }
    } else {
        $myUser->saveids = $saveId;
    }

    if (isset($bankids)) {
        if (in_array("0", $bankids)) {
            $myUser->bankids = '0';
        } else {
            $myUser->bankids = '-1,' . implode(",", $bankids);
        }
    } else {
        $myUser->bankids = '-1,';
    }

    if (isset($charityids)) {
        if (in_array("0", $charityids)) {
            $myUser->charityids = '0';
        } else {
            $myUser->charityids = '-1,' . implode(",", $charityids);
        }
    } else {
        $myUser->charityids = '-1,';
    }

    if (isset($laterNakdiUserIds)) {
        if (in_array("0", $laterNakdiUserIds)) {
            $myUser->laterNakdiUserIds = '0';
        } else {
            $myUser->laterNakdiUserIds = '-1,' . implode(",", $laterNakdiUserIds);
        }
    } else {
        $myUser->laterNakdiUserIds = '-1,-1';
    }

    $myUser->searchinonestorebalance = $searchinonestorebalance;
    if (isset($storeids)) {
        if (in_array("0", $storeids)) {
            $myUser->storeids = '0';
        } else {
            if (!in_array($userstoreidDef, $storeids)) {
                $myUser->storeids = $userstoreidDef . ',' . implode(",", $storeids);
            } else {
                $myUser->storeids = implode(",", $storeids);
            }
        }
    } else {
        $myUser->storeids = $userstoreidDef;
    }
    $myUser->dellaternakdipayed = $_POST['dellaternakdipayed'];
    $userid = $myUserRecord->insert($myUser);

    if (!empty($userid) && $_POST["ebillsaudi"]) {
        $esaudiusersetting = R::dispense('esaudiusersetting');
        $esaudiusersetting->userid = $userid;
        $esaudiusersetting->licensetype = $_POST["licensetype"];
        $esaudiusersetting->licensenumber = $_POST["licensenumber"];
        $esaudiusersetting->streetname = $_POST["streetname"];
        $esaudiusersetting->buildingnumber = $_POST["buildingnumber"];
        $esaudiusersetting->neighborhood = $_POST["neighborhood"];
        $esaudiusersetting->city = $_POST["city"];
        $esaudiusersetting->postalzone = $_POST["postalzone"];
        $esaudiusersetting->countrycode = $_POST["countrycode"];
        $esaudiusersetting->companytaxregistrationnumber = $_POST["companytaxregistrationnumber"];
        $esaudiusersetting->companyname = $_POST["companyname"];
        R::store($esaudiusersetting);
    }
}

// show the form
function showByUsergroupId($usergroupId) {
    //to use the variable out side the funcion

    global $myUserRecord;
    global $myUserEx;

    global $smarty;


    // get the all colums number
    $userData = $myUserEx->queryWithGroupIdAndUserId($_SESSION['userid'], $usergroupId);

    // assign your db results to the template
    $smarty->assign('userData', $userData);
}

// show the form
function showAll() {
    //to use the variable out side the funcion

    global $myUserRecord;
    global $myUserEx;

    global $smarty;

    //select all data from user tbl
    $userData = $myUserEx->queryAllWithoutSessionUser($_SESSION['userid']);

    // assign your db results to the template
    $smarty->assign('userData', $userData);
}

//update tempdelete in user tbl
function delete() {
    //to use the variable out side the funcion
    global $myUser;
    global $myUserEx;

    //get variable
    $conditions = $_GET['conditions'];
    $userId = $_GET['userid'];
    if ($conditions == 1) {
        $myUser->conditions = 0;
    } else {
        $myUser->conditions = 1;
    }

    //update conditions in user tbl
    $myUser->userid = $userId;
    $myUser->currentdate = date("Y-m-d");

    $myUserEx->updateConditions($myUser);
}

//finaly deleted from user tbl
function deleteFinaly() {
    //to use the variable out side the funcion
    global $myUserRecord;

    //get variable
    $userId = $_GET['userid'];

    //delete from user tbl
    $myUserRecord->delete($userId);
}

// edit in table
function edit() {
    //to use the variable out side the funcion
    global $myUserRecord;
    global $myUserGroupRecord;
    global $employeeDAO;

    //get variable
    $userId = $_GET['userid'];

    //load data by usergroupid
    $loadData = $myUserRecord->load($userId);
    if ($loadData->empid > 0) {
        $empData = $employeeDAO->load($loadData->empid);
        $loadData->empName = $empData->employeeName;
    }
    $loadData->storeSupervisorStores = explode(',', $loadData->storeSupervisorStores);
    $loadData->projectids = explode(',', $loadData->projectids);
    $loadData->bankids = explode(',', $loadData->bankids);
    $loadData->saveids = explode(',', $loadData->saveids);
    $loadData->storeids = explode(',', $loadData->storeids);
    $loadData->charityids = explode(',', $loadData->charityids);
    $loadData->laterNakdiUserIds = explode(',', $loadData->laterNakdiUserIds);

    //	print_r("<pre>");
    //print_r($loadData);
    //print_r("<pre>");
    return $loadData;
}

// update table
function update() {
    //to use the variable out side the funcion
    global $myUser;
    global $myUserRecord;
    global $myUserEx;
    global $smarty;


    $userName = $_POST['username'];
    $passWord = $_POST['password'];
    $userstoreid = $_POST['userstoreid'];
    $userstoreidDef = $_POST['userstoreidDef'];
    $employeeName = $_POST['employeename'];
    $usergroupId = $_POST['usergroupid'];
    $saveId = $_POST['saveid'];
    $userId = $_POST['userid'];
    $currentDate = $_POST['currentdate'];
    $conditions = $_POST['conditions'];
    $awardrate = (float) $_POST["awardrate"];
    $awardrategomla = $_POST["awardrategomla"];
    $awardratehalf = $_POST["awardratehalf"];
    $branchid = (int) $_POST["branchid"];

    $question = $_POST["question"];
    $answer = $_POST["answer"];

    $directSaveBills = $_POST["directSaveBills"];
    $obygyDoctorId = (int) $_POST["obygyDoctorId"];
    $viewclients = (int) $_POST["viewclients"];
    $viewbills = (int) $_POST["viewbills"];
    $closeSavid = $_POST['closeSavid'];

    #
    $storeSupervisor = (int) $_POST["storeSupervisor"];
    $storeSupervisorStores = filter_input(INPUT_POST, 'storeSupervisorStores', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $projectids = filter_input(INPUT_POST, 'projectids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $bankids = filter_input(INPUT_POST, 'bankids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $saveids = filter_input(INPUT_POST, 'saveids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $searchinonestorebalance = $_POST["searchinonestorebalance"];
    $storeids = filter_input(INPUT_POST, 'storeids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $charityids = filter_input(INPUT_POST, 'charityids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $laterNakdiUserIds = filter_input(INPUT_POST, 'laterNakdiUserIds', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);


    $storeSupervisorStores_str = '';
    foreach ($storeSupervisorStores as $value) {
        $storeSupervisorStores_str .= $value . ",";
    }
    $storeSupervisorStores_str = rtrim($storeSupervisorStores_str, ',');
    ###########################

    $handle = new upload($_FILES['pdffile']);
    $pdffile = updateImagesWithoutresiz($handle, 'hiddenfile', "../upload/users");
    $searchinonesave = (isset($_POST["searchinonesave"])) ? $_POST["searchinonesave"] : 1;


    $myUser = $myUserRecord->load($userId);
    $myUser->searchinonesave = $searchinonesave;

    if ($branchid == 0) { //all) {
        $myUser->branchId = -1;
    } else {
        $myUser->branchId = $branchid;
    }
    //insert data in user tbl
    $myUser->currentdate = $currentDate;
    $myUser->awardrate = $awardrate;
    $myUser->awardrategomla = $awardrategomla;
    $myUser->awardratehalf = $awardratehalf;
    $myUser->conditions = $conditions;
    $myUser->employeename = $employeeName;
    $myUser->password = $passWord;
    $myUser->username = $userName;
    $myUser->usergroupid = $usergroupId;
    $myUser->saveid = $saveId;
    $myUser->branchId = $branchid;
    $myUser->userid = $userId;
    $myUser->userstoreid = $userstoreid;
    $myUser->userstoreidDef = $userstoreidDef;

    $myUser->question = $question;
    $myUser->answer = $answer;

    $noOfUsersInDB = $myUserEx->queryAllcountuser_f();
    //$myUser->blockedByLimits = 1;
    $myUser->blockedByLimits = 0;

    if ($_SESSION['lic_userno'] > $noOfUsersInDB) {
        $myUser->blockedByLimits = 0;
    }
    $myUser->directSaveBills = $directSaveBills;
    $myUser->obygyDoctorId = $obygyDoctorId;
    $myUser->viewclients = $viewclients;
    $myUser->viewbills = $viewbills;
    $myUser->storeSupervisor = $storeSupervisor;
    $myUser->storeSupervisorStores = $storeSupervisorStores_str;
    $myUser->closeSavid = $closeSavid;
    if (isset($projectids)) {
        if (in_array("0", $projectids)) {
            $myUser->projectids = '0';
        } else {
            $myUser->projectids = '-1,' . implode(",", $projectids);
        }
    } else {
        $myUser->projectids = '-1,';
    }

    if (isset($saveids)) {
        if (in_array("0", $saveids)) {
            $myUser->saveids = '0';
        } else {
            if (!in_array($saveId, $saveids)) {
                $myUser->saveids = $saveId . ',' . implode(",", $saveids);
            } else {
                $myUser->saveids = '-1,' . implode(",", $saveids);
            }
        }
    } else {
        $myUser->saveids = $saveId;
    }

    if (isset($bankids)) {
        if (in_array("0", $bankids)) {
            $myUser->bankids = '0';
        } else {
            $myUser->bankids = '-1,' . implode(",", $bankids);
        }
    } else {
        $myUser->bankids = '-1,';
    }

    if (isset($charityids)) {
        if (in_array("0", $charityids)) {
            $myUser->charityids = '0';
        } else {
            $myUser->charityids = '-1,' . implode(",", $charityids);
        }
    } else {
        $myUser->charityids = '-1,';
    }

    if (isset($laterNakdiUserIds)) {
        if (in_array("0", $laterNakdiUserIds)) {
            $myUser->laterNakdiUserIds = '0';
        } else {
            $myUser->laterNakdiUserIds = '-1,' . implode(",", $laterNakdiUserIds);
        }
    } else {
        $myUser->laterNakdiUserIds = '-1,-1';
    }

    $myUser->searchinonestorebalance = $searchinonestorebalance;
    if (isset($storeids)) {
        if (in_array("0", $storeids)) {
            $myUser->storeids = '0';
        } else {
            if (!in_array($userstoreidDef, $storeids)) {
                $myUser->storeids = $userstoreidDef . ',' . implode(",", $storeids);
            } else {
                $myUser->storeids = implode(",", $storeids);
            }
        }
    } else {
        $myUser->storeids = $userstoreidDef;
    }
    $myUser->dellaternakdipayed = $_POST['dellaternakdipayed'];

    $myUserRecord->update($myUser);



    if (!empty($userId) && $_POST["ebillsaudi"]) {
        $esaudiusersetting = R::load('esaudiusersetting', $_POST["esaudiusersetting_id"]);
        $esaudiusersetting->userid = $userId;
        $esaudiusersetting->licensetype = $_POST["licensetype"];
        $esaudiusersetting->licensenumber = $_POST["licensenumber"];
        $esaudiusersetting->streetname = $_POST["streetname"];
        $esaudiusersetting->buildingnumber = $_POST["buildingnumber"];
        $esaudiusersetting->neighborhood = $_POST["neighborhood"];
        $esaudiusersetting->city = $_POST["city"];
        $esaudiusersetting->postalzone = $_POST["postalzone"];
        $esaudiusersetting->countrycode = $_POST["countrycode"];
        $esaudiusersetting->companytaxregistrationnumber = $_POST["companytaxregistrationnumber"];
        $esaudiusersetting->companyname = $_POST["companyname"];
        R::store($esaudiusersetting);
    }



    //if there no result in the arry send it to the login form

    if ($_SESSION['user_id'] == $userId) {
        $_SESSION['saveid'] = $myUser->saveid;
        $_SESSION['saveids'] = trim($myUser->saveids, ',');
        $_SESSION['projectids'] = trim($myUser->projectids, ',');
        $_SESSION['bankids'] = $myUser->bankids;
        $_SESSION['storeids'] = $myUser->storeids;
        $_SESSION['searchinonestorebalance'] = $myUser->searchinonestorebalance;
        $_SESSION['viewbills'] = $myUser->viewbills;
        $_SESSION['branchId'] = $myUser->branchId;
        $_SESSION['charityids'] = $myUser->charityids;
    }



    /*     * ******************************** fatma younis ********************************************** */
    $validationResult = $myUserEx->validationUser($userName, $passWord);

    //if there no result in the arry send it to the login form
    if (!isset($validationResult) || empty($validationResult)) {
        // the login form is empty
        $smarty->display("login.html");
    } else {
        /* $_SESSION['userid'] = $validationResult->userid;
          $_SESSION['usergroupid']=$validationResult->usergroupid;
          $_SESSION['username']=$validationResult->username;
          $_SESSION['usergroupname']=$validationResult->usergroupname;
          $_SESSION['saveid']=$validationResult->saveid;
          $_SESSION['employeename']=$validationResult->employeename;
          $_SESSION['searchinonesave']=$validationResult->searchinonesave;
         */
        $_SESSION['branchId'] = $validationResult->branchId;

        /* $_SESSION['dbname'] = $db; */
    }
    /*     * ****************************************************************************** */
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
    //    $post = [
    //        'data_arr' => json_encode($data_arr), //encode it as it is array
    //    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}
