<?php

// generate json web token
include_once '../public/apiConfig.php';
include_once '../library/php-jwt-master/src/BeforeValidException.php';
include_once '../library/php-jwt-master/src/ExpiredException.php';
include_once '../library/php-jwt-master/src/SignatureInvalidException.php';
include_once '../library/php-jwt-master/src/JWT.php';

use \Firebase\JWT\JWT;

//check jwt
$jwt = null;
foreach (getallheaders() as $name => $value) {
    if ($name == "Open-Key") {
        $jwt = $value;
    }
}

try {
    $decoded_key = JWT::decode($jwt, getenv('api_key'), array('HS256'));
    if ($decoded_key->username === getenv('api_user')) {
        if ($decoded_key->password === getenv('api_password')) {
            //continue below
        } elseif ($decoded_key->password !== getenv('api_password')) {
            //echo "e1";
            header("HTTP/1.1 405 Method not NotAllowed");
            exit();
        }
    } else {
        //echo "e2";
        header("HTTP/1.1 405 Method not NotAllowed");
        exit();
    }
} catch (Exception $e) {
    //echo "e3";
    //echo $e->getTraceAsString();
    header("HTTP/1.1 405 Method not NotAllowed");
    exit();
}

//here to continue after jwt check

require_once('../models/sql/ConnectionProperty.class.php');
$do = $_GET["do"];


##save
if ($do == "gatsave") {
    $id = (int) $_GET['id'];
    $userid = (int) $_GET['userid'];
    $onlydefult = (int) $_GET['onlydefult'];
    if ($id != 0) {//one save
        $retData = (object) R::getRow('select saveid,savename from save where  conditions = 0 and saveid = ' . $id);
    } else if ($userid != 0) {
        if ($onlydefult == 1) {//to choose default save only
            $retData = (object) R::getRow('select saveid,savename from save where  conditions = 0 and saveid = ( select saveid from user where userid = ' . $userid . ' )');
        } else {
            // to choose all saves of user
            $retData = R::getAll('SELECT save.saveid,save.savename
                                FROM save
                                JOIN user ON (FIND_IN_SET(save.saveid, user.saveids) > 0 OR user.saveids = "0")
                                WHERE user.userid = ' . $userid);
            //array to object
            $retData = array_map(function($array) {
                return (object) $array;
            }, $retData);
            //
            $defaultSaveid = (int) R::getCell('select saveid from save where  conditions = 0 and saveid = ( select saveid from user where userid = ' . $userid . ' )');
            $defaultSaveid = ($defaultSaveid > 0) ? $defaultSaveid : 1;
            foreach ($retData as $value) {
                $value->default = 0;
                if ($value->saveid == $defaultSaveid) {
                    $value->default = 1;
                }
            }
        }
    } else {
        $retData = R::getAll('select saveid,savename from save where conditions = 0 ');
        //array to object
        $retData = array_map(function($array) {
            return (object) $array;
        }, $retData);
    }

    echo json_encode($retData);
} elseif ($do == "savedaily") {
    $userid = (int) $_POST['userId'];
    $useridRoyal = (int) $_POST['royalid'];
    if ($userid > 0) {
        //its id on erp use it
    } elseif ($useridRoyal > 0) {
        $row = R::findOne('user', 'conditions = 0 and obygyDoctorId = ' . $useridRoyal);
        $_POST['userId'] = $userid = $row->userid;
    }

    //
    $_POST['search'] = "dateOnly";


    $_GET["do"] = "show";
    $control = "savedailyController.php";
    $response = CURL_WEB($control);
    echo $response;
}
##user
if ($do == "useradd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->userid) && $row->userid > 0) {//this id is used cannot add it again
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "userController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "userupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['userid'] = $row->userid;
        $_POST['currentdate'] = $row->currentdate;
        //
        $_GET["do"] = "update";
        $control = "userController.php";
        CURL_WEB($control);
    }
} elseif ($do == "userdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['userid'] = $row->userid;
        $_GET['conditions'] = 0;
        //
        $_GET["do"] = "delete";
        $control = "userController.php";
        CURL_WEB($control);
    }
}
##client
if ($do == "clientadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->clientid) && $row->clientid > 0) {//this id is used cannot add it again
            exit();
        } else {
            $_POST['store_all'] = 1;
            //
            $_GET["do"] = "add";
            $control = "clientController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "clientupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['id'] = $row->clientid;
        $_POST['store_all'] = 1;
        //
        $_GET["do"] = "update";
        $control = "clientController.php";
        CURL_WEB($control);
    }
} elseif ($do == "clientdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['id'] = $row->clientid;
        //
        $_GET["do"] = "deleteFinaly";
        $control = "clientController.php";
        CURL_WEB($control);
    }
} elseif ($do == "clientdept") {
    $webId = (int) $_GET['id'];
    $clientid = (int) $_GET['erpid'];
    $obygyPatientId = (int) $_GET['royalid'];
    if ($clientid > 0) {
        $row = R::findOne('client', 'conditions = 0 and clientid = ' . $clientid);
    } else if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
    } else if ($obygyPatientId > 0) {
        $row = R::findOne('client', 'conditions = 0 and obygyPatientId = ' . $obygyPatientId);
    }
    echo $row->clientdebt;
} elseif ($do == "clientPayedDept") {
    $webId = (int) $_POST['id'];
    $clientid = (int) $_POST['erpid'];
    $obygyPatientId = (int) $_POST['royalid'];
    if ($clientid > 0) {
        $row = R::findOne('client', 'conditions = 0 and clientid = ' . $clientid);
    } else if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
    } else if ($obygyPatientId > 0) {
        $row = R::findOne('client', 'conditions = 0 and obygyPatientId = ' . $obygyPatientId);
    }

    $_POST["clientid"] = $row->clientid;
    //
    $_GET["do"] = "showallajax";
    $control = "clientPayedDeptController.php";
    $response = CURL_WEB($control);
    echo $response;
}
##expense cat
if ($do == "expenscatadd") {
    if ((int) $_POST['parent'] > 0) {
        $parentid = R::getCell('select expensestypeid from expensestype where webApiId=' . (int) $_POST['parent']);
        $_POST['parent'] = $parentid;
    }
    $_POST['webApiId'] = (int) $_POST['id'];
    //
    $_GET["do"] = "add";
    $control = "expensesTypeController.php";
    CURL_WEB($control);
} elseif ($do == "expenscatupdate") {
    $id = R::getCell('select expensestypeid from expensestype where webApiId=' . (int) $_POST['id']);
    $_GET['id'] = $id;
    if ((int) $_POST['parent'] > 0) {
        $parentid = R::getCell('select expensestypeid from expensestype where webApiId=' . (int) $_POST['parent']);
        $_POST['parent'] = $parentid;
    }
    //
    $_GET["do"] = "update";
    $control = "expensesTypeController.php";
    CURL_WEB($control);
} elseif ($do == "expenscatdel") {
    $id = R::getCell('select expensestypeid from expensestype where webApiId=' . (int) $_POST['id']);
    $_GET['id'] = $id;
    //
    $_GET["do"] = "delete";
    $control = "expensesTypeController.php";
    CURL_WEB($control);
}
##expense
if ($do == "expenseadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $expensesid = (int) R::getCell('SELECT expensesid FROM expenses where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if ($expensesid > 0) {//this id is used cannot add it again
            exit();
        } else {
            if ((int) $_POST['expensetype'] > 0) {
                $parentid = R::getCell('select expensestypeid from expensestype where webApiId=' . (int) $_POST['expensetype']);
                $_POST['expensetype'] = $parentid;
            }

            $_POST['store_all'] = 1;
            //
            $_GET["do"] = "add";
            $control = "expensesController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "expensedel") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $expensesData = R::getRow('SELECT expensesid,dailyentryid FROM expenses where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($expensesData) && $expensesData['expensesid'] > 0) {//this id exist , can del it
            //
            $_GET["do"] = "delete";
            $_GET["id"] = $expensesData['expensesid'];
            $_GET["dailyentryid"] = $expensesData['dailyentryid'];
            $control = "expensesController.php";
            CURL_WEB($control);
        }
    }
}

##cat
elseif ($do == "catadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        //$_POST['productCatId'] = $row->productCatId;//not working as column name has capital lettes
        $catId = 0;
        foreach ($row as $key => $value) {
            if ($key == "productCatId") {
                $catId = $value;
            }
        }
        if ($catId > 0) {//this id is used cannot add it again
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "productCatController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "catupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $webId);
        //$_POST['productCatId'] = $row->productCatId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productCatId") {
                $_POST['productCatId'] = $value;
            }
        }
        //
        $_GET["do"] = "update";
        $control = "productCatController.php";
        CURL_WEB($control);
    }
} elseif ($do == "catdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $webId);
        //$_GET['id'] = $row->productCatId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productCatId") {
                $_GET['id'] = $value;
            }
        }
        //
        $_GET["do"] = "deleteFinaly";
        $control = "productCatController.php";
        CURL_WEB($control);
    }
}



##product
elseif ($do == "proadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['productCatId'] = (int) $_POST['productCatId'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        //$_POST['productId'] = $row->productId;//not working as column name has capital lettes
        $proid = 0;
        foreach ($row as $key => $value) {
            if ($key == "productId") {
                $proid = $value;
            }
        }
        if ($proid > 0) {//this id is used cannot add it again
            exit();
        } else {
            if ($_POST['productCatId'] > 0) {
                $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $_POST['productCatId']);
                //$_POST['productCatId'] = $row->productCatId;//not working as column name has capital lettes
                foreach ($row as $key => $value) {
                    if ($key == "productCatId") {
                        $_POST['productCatId'] = $value;
                    }
                }
            }

            $_POST['productItr'] = 1;
            //
            $_GET["do"] = "add";
            $control = "productController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "proupdate") {
    $webId = (int) $_POST['id'];
    $_POST['productCatId'] = (int) $_POST['productCatId'];
    if ($webId > 0) {
        if ($_POST['productCatId'] > 0) {
            $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $_POST['productCatId']);
            //$_POST['productCatId'] = $row->productCatId;//not working as column name has capital lettes
            foreach ($row as $key => $value) {
                if ($key == "productCatId") {
                    $_POST['productCatId'] = $value;
                }
            }
        }
        $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $webId);
        //$_POST['productId'] = $row->productId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productId") {
                $_POST['productId'] = $value;
            }
        }
        $_POST['parcode1'] = $row->parcode;
        $_POST['productItr'] = 1;
        $_POST['unitsItr1'] = 0;
        $_POST['Unitdone'] = 1;
        //
        $_GET["do"] = "update";
        $control = "productController.php";
        CURL_WEB($control);
    }
} elseif ($do == "prodel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $webId);
        //$_GET['id'] = $row->productId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productId") {
                $_GET['id'] = $value;
            }
        }
        //
        $_GET["do"] = "deleteFinaly";
        $control = "productController.php";
        CURL_WEB($control);
    }
}
##bill
elseif ($do == "billadd") {
    $ret = array();
    //
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $itr = (int) $_POST['hidden_itr'];
    if ($_POST['webApiId'] > 0 && $_POST['supplier'] > 0 && $itr > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->sellbillid) && $row->sellbillid > 0) {//this id is used cannot add it again
            $ret = array("errorNo" => 1, "errorMsg" => "this bill with id " . $_POST['webApiId'] . " has been added before");
            echo json_encode($ret);
            exit();
        } else {
            $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
            if (!isset($row->clientid) || empty($row->clientid)) {
                $ret = array("errorNo" => 2, "errorMsg" => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
                echo json_encode($ret);
                exit();
            }
            $_POST['supplier'] = $row->clientid;
            $row = R::load('onlinestoresetting', 1);
            if (!isset($row->onlinestoreid) || empty($row->onlinestoreid)) {
                $row->onlinestoreid = 1;
            }
            $_POST['storeid'] = $row->onlinestoreid;
            for ($i = 1; $i <= $itr; $i++) {
                $pid = (int) $_POST['product' . $i];
                if (isset($pid) && $pid > 0) {
                    $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $pid);
                    $_POST['parcode' . $i] = $row->parcode;
                    //$_POST['product'.$i] = $row->productId;//not working as column name has capital lettes
                    foreach ($row as $key => $value) {
                        if ($key == "productId") {
                            $_POST['product' . $i] = $value;
                        }
                    }

                    if (!isset($_POST['product' . $i]) || empty($_POST['product' . $i])) {
                        $ret = array("errorNo" => 3, "errorMsg" => "this product with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first");
                        echo json_encode($ret);
                        exit();
                    }

                    $punit = (int) $_POST['productunit' . $i];
                    if (isset($punit) && $punit > 0) {
                        //product unit is passed
                        //handle it later it dont exist in adding product here till now
                    } else {
                        $row = R::findOne('productunit', 'productnumber = 1 and conditions = 0 and productid = ' . $_POST['product' . $i]);
                        $_POST['productunit' . $i] = $row->productunitid;
                    }
                }
            }
            //update client
            updateClientData();

            $_POST["billnameid"] = 3;
            $_POST["settingdate"] = 1;
            $_POST["Costcenter"] = -1;
            $_POST["distype"] = 1; //constant => means direct discount
            $_POST["sellbillprice"] = $_POST["sellbilltotalbill"];
            //
            $_GET["do"] = "add";
            $control = "sellbillController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "billupdate") {
    $ret = array();
    //
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $itr = (int) $_POST['hidden_itr'];
    if ($_POST['webApiId'] > 0 && $_POST['supplier'] > 0 && $itr > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        $_POST['oldid'] = $row->sellbillid;
        $_POST['bns'] = $row->sellbillserial;
        $_POST['dailyID'] = $row->dailyentryid;
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
        if (!isset($row->clientid) || empty($row->clientid)) {
            $ret = array("errorNo" => 2, "errorMsg" => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
            echo json_encode($ret);
            exit();
        }
        $_POST['supplier'] = $row->clientid;
        $row = R::load('onlinestoresetting', 1);
        $_POST['storeid'] = $row->onlinestoreid;
        for ($i = 1; $i <= $itr; $i++) {
            $pid = (int) $_POST['product' . $i];
            if (isset($pid) && $pid > 0) {
                $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $pid);
                $_POST['parcode' . $i] = $row->parcode;
                //$_POST['product'.$i] = $row->productId;//not working as column name has capital lettes
                foreach ($row as $key => $value) {
                    if ($key == "productId") {
                        $_POST['product' . $i] = $value;
                    }
                }

                if (!isset($_POST['product' . $i]) || empty($_POST['product' . $i])) {
                    $ret = array("errorNo" => 3, "errorMsg" => "this product with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first");
                    echo json_encode($ret);
                    exit();
                }

                $punit = (int) $_POST['productunit' . $i];
                if (isset($punit) && $punit > 0) {
                    //product unit is passed
                    //handle it later it dont exist in adding product here till now
                } else {
                    $row = R::findOne('productunit', 'productnumber = 1 and conditions = 0 and productid = ' . $_POST['product' . $i]);
                    $_POST['productunit' . $i] = $row->productunitid;
                }
            }
        }
        //update client
        updateClientData();

        $_POST["billnameid"] = 3;
        $_POST["settingdate"] = 1;
        $_POST["Costcenter"] = -1;
        $_POST["distype"] = 1; //constant => means direct discount
        $_POST["sellbillprice"] = $_POST["sellbilltotalbill"];
        $_POST["controlname"] = "sellbillController";
        //
        $_GET["do"] = "update";
        $control = "sellbillController.php";
    }

    CURL_WEB($control);
} elseif ($do == "billdel") {
    $webId = (int) $_GET['sellbillid'];
    if ($webId > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['sellbillid'] = $row->sellbillid;
        //
        $_GET["do"] = "delete";
        $control = "sellbillController.php";
        CURL_WEB($control);
    }
} elseif ($do == "paybill") {
    $webId = (int) $_POST['bill_id'];
    if ($webId > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['bill_id'] = $row->sellbillid;
        $_POST['getFreshVames'] = 1;
        $id_pay[0] = $_POST;
        unset($_POST);
        $_POST['id_pay'] = json_encode($id_pay);
        $_POST['erpDB'] = ConnectionProperty::getDatabase();
        //
        $_GET["do"] = "makeSellBillPayment";
        $control = "sellbillAjaxController.php";
        CURL_WEB($control);
    }
} elseif ($do == "delpaybill") {
    //
    $_GET["do"] = "delMakeSellBillPayment";
    $control = "sellbillAjaxController.php";
    CURL_WEB($control);
} elseif ($do == "clientBillsWithPayments") {
    $clientid = (int) $_POST['clientid'];
    $obygyPatientId = (int) $_POST['royalid'];
    if ($clientid > 0) {
        //its id on erp use it
    } elseif ($obygyPatientId > 0) {
        $row = R::findOne('client', 'conditions = 0 and obygyPatientId = ' . $obygyPatientId);
        $_POST["clientid"] = $clientid = $row->clientid;
    }

    if ($clientid > 0) {
        $_POST['erpDB'] = ConnectionProperty::getDatabase();
        //
        $_GET["do"] = "clientBills";
        $control = "reportprovinces.php";
        $retData = CURL_WEB($control);
        print_r($retData);
    }
} elseif ($do == "updatebillstripdata") {
    //
    $tripid = (int) $_POST['tripid'];
    $dateid = (int) $_POST['dateid'];
    $busid = (int) $_POST['busid'];
    $driverid = (int) $_POST['driverid'];

    if ($tripid > 0 && $dateid > 0 && ($busid > 0 || $driverid > 0)) {
        $sql = 'update sellbill set ';
        if ($busid > 0) {
            $sql .= ' travelBusId = ' . $busid . ',';
        }
        if ($driverid > 0) {
            $sql .= ' travelDriverId = ' . $driverid . ',';
        }
        $sql = trim($sql, ',');
        $sql .= ' where travelTripId = ' . $tripid . ' and travelTripDateId = ' . $dateid;

        R::exec($sql);
        echo 1;
    }
}
##product quantities
elseif ($do == "productsquantity") {
    if (isset($_POST['proids']) && !empty($_POST['proids'])) {
        $row = R::load('onlinestoresetting', 1);
        $_POST['storeid'] = (int) $row->onlinestoreid;
        //
        $_GET["do"] = "productsquantity";
        $control = "storedetailAjaxController.php";
        $retData = CURL_WEB($control);
        var_dump($retData);
    }
}
/* -------------------------------------------------------------------------- */

function updateClientData() {
    //update client
    $sql = "update client set clientid = " . $_POST['supplier'];
    if (isset($_POST['address']) && !empty($_POST['address'])) {
        $sql .= " ,clientaddress = '" . $_POST['address'] . "' ";
    }
    if (isset($_POST['phone']) && !empty($_POST['phone'])) {
        $sql .= " ,clientphone = '" . $_POST['phone'] . "' ";
    }
    if (isset($_POST['mobile']) && !empty($_POST['mobile'])) {
        $sql .= " ,clientmobile = '" . $_POST['mobile'] . "' ";
    }

    if ($sql != "update client set clientid = " . $_POST['supplier']) {
        R::exec($sql . " where clientid = " . $_POST['supplier']);
    }
}

function CURL_WEB($control) {
    ##preparing url
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $control;
    $i = 0;
    foreach ($_GET as $key => $value) {
        if ($i == 0) {
            $url .= "?$key=$value";
        } else {
            $url .= "&$key=$value";
        }
        $i++;
    }


    $data_arr = array();
    ##preparing req. session
    setSessionVariables();
    $data_arr['sessionlist'] = json_encode($_SESSION);
    ##appending data
    foreach ($_POST as $key => $value) {
        $data_arr[$key] = $value;
    }

    ## start sending
    $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;
}

function createJWT() {
    $payLoad = array(
        'username' => getenv('api_user'),
        'password' => getenv('api_password'),
    );
    return JWT::encode($payLoad, getenv('api_key'));
}

function setSessionVariables() {

    $_POST['curlpost'] = 1;
    //set them static may change later
    $_SESSION['dbname'] = ConnectionProperty::getDatabase(); //"erp";
    $_SESSION['lic_dateto'] = date('Y-m-d');
    //
    $_SESSION['attempt'] = 0;
    $_SESSION['hidecat'] = 1;
    $_SESSION['clientnegative'] = 1;
    $_SESSION['suplliernegative'] = 1;
    $_SESSION['storenegative'] = 1;


    ## get user data
    $userid = (int) $_POST['userid'];
    if (isset($userid) && !empty($userid)) {
        $userData = R::getRow('select * from user where webApiId = ' . $userid);
    } else {
        $userData = R::getRow('select * from user where userid = 1');
    }

    if (isset($userData['userid']) && !empty($userData['userid'])) {
        $_SESSION['userid'] = $userData['userid'];
        $_SESSION['usergroupid'] = $userData['usergroupid'];
        $_SESSION['username'] = $userData['username'];
        $_SESSION['usergroupname'] = $userData['usergroupname'];
        $_SESSION['saveid'] = $userData['saveid'];
        $_SESSION['employeename'] = $userData['employeename'];
        $_SESSION['searchinonesave'] = $userData['searchinonesave'];
        $_SESSION['saveids'] = trim($userData['saveids'], ',');
        $_SESSION['bankids'] = trim($userData['bankids'], ',');
        $_SESSION['projectids'] = $userData['projectids'];
        $_SESSION['searchinonestorebalance'] = $userData['searchinonestorebalance'];
        $_SESSION['viewbills'] = $userData['viewbills'];
        $_SESSION['branchId'] = $userData['branchId'];
        $_SESSION['storeids'] = $userData['storeids'];
        $_SESSION['storeid'] = $userData['userstoreidDef'];
        $_SESSION['searchinonestore'] = $userData['userstoreid'];
        $_SESSION['userstore'] = ($userData['userstoreid'] == 0) ? $userData['userstoreidDef'] : $userData['userstoreid'];
        $_SESSION['charityids'] = trim($userData['charityids'], ',');
    } else {

        $_SESSION['userid'] = 1;
        $_SESSION['usergroupid'] = 1;
        $_SESSION['username'] = "admin";
        $_SESSION['usergroupname'] = "admin";
        $_SESSION['saveid'] = 1;
        $_SESSION['employeename'] = "admin";
        $_SESSION['searchinonesave'] = 0;
        $_SESSION['branchId'] = 1;
    }
}
