HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/api_web.php
<?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 == "saveadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from save where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row['saveid']) && $row['saveid'] > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذه الخزنه من قبل', 'message_en' => 'This save has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "saveController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "saveupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from save where conditions = 0 and webApiId = ' . $webId);
        $_POST['saveid'] = $row['saveid'];
        //
        $_GET["do"] = "update";
        $control = "saveController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "savedel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from save where conditions = 0 and webApiId = ' . $webId);
        $_GET['saveid'] = $row['saveid'];
        $_GET['condition'] = 0;
        //
        $_GET["do"] = "delete";
        $control = "saveController.php";
        echo CURL_WEB($control);
    }
} else 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";
    echo CURL_WEB($control);
}
##Bank
if ($do == "bankadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row['bankid']) && $row['bankid'] > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذا البنك من قبل', 'message_en' => 'This bank has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "bankController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "bankupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $webId);
        $_POST['bankid'] = $row['bankid'];
        //
        $_GET["do"] = "update";
        $control = "bankController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "bankdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $webId);
        $_GET['bankid'] = $row['bankid'];
        //
        $_GET["do"] = "delete";
        $control = "bankController.php";
        echo CURL_WEB($control);
    }
}
##Bank Account
if ($do == "bankaccountadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from bankaccount where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row['accountid']) && $row['accountid'] > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذا الحساب البنكى من قبل', 'message_en' => 'This bank account has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $rowBank = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $_POST['bankid']);
            $_POST['bankid'] = $rowBank['bankid'];
            //
            $_GET["do"] = "add";
            $control = "bankaccountController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "bankaccountupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from bankaccount where conditions = 0 and webApiId = ' . $webId);
        $_POST['accountid'] = $row['accountid'];
        //
        $rowBank = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $_POST['bankid']);
        $_POST['bankid'] = $rowBank['bankid'];
        //
        $_GET["do"] = "update";
        $control = "bankaccountController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "bankaccountdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from bankaccount where conditions = 0 and webApiId = ' . $webId);
        $_GET['accountid'] = $row['accountid'];
        //
        $_GET["do"] = "deletetemp";
        $control = "bankaccountController.php";
        echo CURL_WEB($control);
    }
}
##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
            $data = array('status' => 2, 'message' => 'تم اضافه هذا المستخدم من قبل', 'message_en' => 'This user has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "userController.php";
            echo 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";
        echo 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";
        echo CURL_WEB($control);
    }
}
##client type
if ($do == "clienttypeadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from typeclient where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row['typeId']) && $row['typeId'] > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذا النوع من قبل', 'message_en' => 'This client type has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "typeClientController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "clienttypeupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from typeclient where conditions = 0 and webApiId = ' . $webId);
        $_POST['typeid'] = $row['typeId'];
        //
        $_GET["do"] = "update";
        $control = "typeClientController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "clienttypedel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from typeclient where conditions = 0 and webApiId = ' . $webId);
        $_GET['id'] = $row['typeId'];
        //
        $_GET["do"] = "delete";
        $control = "typeClientController.php";
        echo 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
            $data = array('status' => 2, 'message' => 'تم اضافه هذا العميل من قبل', 'message_en' => 'This client has been added before');
            echo json_encode($data);
            exit();
        } else {
            $_POST['store_all'] = 1;
            //
            $_GET["do"] = "add";
            $control = "clientController.php";
            echo 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";
        echo 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";
        echo 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";
    echo CURL_WEB($control);
} elseif ($do == "clientPayedDeptAdd") {
    //client
    $webId = (int) $_POST['clientid'];
    if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["clientid"] = $row->clientid;
    //save
    $webId = (int) $_POST['saveid'];
    if ($webId > 0) {
        $row = R::findOne('save', 'conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["saveid"] = $row->saveid;
    //bank
    $webId = (int) $_POST['ddlBank'];
    if ($webId > 0) {
        $row = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["ddlBank"] = $row['bankid'];
    //accountid
    $webId = (int) $_POST['accountid'];
    if ($webId > 0) {
        $row = R::getRow('select * from bankaccount where conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["accountid"] = $row['accountid'];



    if ($_POST["saveorbank"] == 1) {//save
    } elseif ($_POST["saveorbank"] == 2) {//bank
        $_POST['txtAmount'] = $_POST['payedDept'];
        $_POST['textNote'] = $_POST['comment'];
    }


    $_POST['voucher'] = $_POST['premiumid'] = ((int) R::getCell('SELECT clientdebtchangeid FROM clientdebtchange order by clientdebtchangeid desc limit 1')) + 1;
    $_POST['notPremium'] = 'notPremium';
    $_POST['currentDate'] = date('Y-m-d H:i:s');
    //
    $_GET["do"] = "add";
    $control = "clientPayedDeptController.php";
    echo CURL_WEB($control);
    echo $response;
} elseif ($do == "clientPayedDeptDel") {
    //
    $_GET["do"] = "remove";
    $control = "clientPayedDeptController.php";
    echo CURL_WEB($control);
}
##supplier
if ($do == "supplieradd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->supplierid) && $row->supplierid > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذا المورد من قبل', 'message_en' => 'This supplier has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "supplierController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "supplierupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['id'] = $row->supplierid;
        //
        $_GET["do"] = "update";
        $control = "supplierController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "supplierdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['id'] = $row->supplierid;
        //
        $_GET["do"] = "deleteFinaly";
        $control = "supplierController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "supplierdept") {
    $webId = (int) $_GET['id'];
    $supplierid = (int) $_GET['erpid'];
//    $obygyPatientId = (int) $_GET['royalid'];
    if ($supplierid > 0) {
        $row = R::getRow('select suppliercurrentDebt from supplier where conditions = 0 and supplierid = ' . $webId);
    } else if ($webId > 0) {
        $row = R::getRow('select suppliercurrentDebt from supplier where conditions = 0 and webApiId = ' . $webId);
    }
    echo $row['suppliercurrentDebt'];
}
#
elseif ($do == "supplierPayedDept") {
    //supplier
    $webId = (int) $_POST['supplierId'];
    if ($webId > 0) {
        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['supplierId'] = $row->supplierid;
    }

    //
    $_GET["do"] = "showallajax";
    $control = "supplierReportsController.php";
    echo CURL_WEB($control);
} elseif ($do == "supplierPayedDeptAdd") {
    //supplier
    $webId = (int) $_POST['supplierid'];
    if ($webId > 0) {
        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['supplierid'] = $row->supplierid;
    }
    //save
    $webId = (int) $_POST['saveid'];
    if ($webId > 0) {
        $row = R::findOne('save', 'conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["saveid"] = $row->saveid;
    //bank
    $webId = (int) $_POST['ddlBank'];
    if ($webId > 0) {
        $row = R::getRow('select * from bank where conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["ddlBank"] = $row['bankid'];
    //accountid
    $webId = (int) $_POST['accountid'];
    if ($webId > 0) {
        $row = R::getRow('select * from bankaccount where conditions = 0 and webApiId = ' . $webId);
    }
    $_POST["accountid"] = $row['accountid'];



    if ($_POST["saveorbank"] == 1) {//save
    } elseif ($_POST["saveorbank"] == 2) {//bank
        $_POST['txtAmount'] = $_POST['payedDept'];
        $_POST['textNote'] = $_POST['comment'];
    }


    $_POST['voucher'] = $_POST['premiumid'] = ((int) R::getCell('SELECT clientdebtchangeid FROM clientdebtchange order by clientdebtchangeid desc limit 1')) + 1;
    $_POST['notPremium'] = 'notPremium';
    $_POST['currentDate'] = date('Y-m-d H:i:s');
    //
    $_GET["do"] = "add";
    if ($_POST["saveid"] > 0) {
        $control = "supplierPayedDeptController.php";
    } elseif ($_POST["ddlBank"] > 0 && $_POST["accountid"] > 0) {
        $control = "checkwithdrawalController.php";
    }

    echo CURL_WEB($control);
} elseif ($do == "supplierPayedDeptDel") {
    //
    $_GET["do"] = "remove";
    $control = "supplierReportsController.php";
    echo CURL_WEB($control);
}
##store
if ($do == "storeadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from store where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row['storeId']) && $row['storeId'] > 0) {//this id is used cannot add it again
            $data = array('status' => 2, 'message' => 'تم اضافه هذا المخزن من قبل', 'message_en' => 'This store has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "storeController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "storeupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from store where conditions = 0 and webApiId = ' . $webId);
        $_POST['storeId'] = $row['storeId'];
        //
        $_GET["do"] = "update";
        $control = "storeController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "storedel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::getRow('select * from store where conditions = 0 and webApiId = ' . $webId);
        $_GET['storeId'] = $row['storeId'];
        //
        $_GET["do"] = "delete";
        $control = "storeController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "storedetailshow") {//رصيد المخازن
    $productIdwebId = (int) $_POST['productId'];
    $storeIdwebId = (int) $_POST['storeId'];
    $catIdwebId = (int) $_POST['productCatId'];
    if ($productIdwebId > 0 || $storeIdwebId > 0 || $catIdwebId > 0) {
        ## get erp ids
        if ($storeIdwebId > 0)
            $_POST['storeId'] = (int) R::getCell('select storeId from store where conditions = 0 and webApiId = ' . $storeIdwebId);
        if ($catIdwebId > 0)
            $_POST['productCatId0'] = (int) R::getCell('select productCatId from productcat where conditions = 0 and webApiId = ' . $catIdwebId);
        if ($productIdwebId > 0)
            $_POST['productId'] = (int) R::getCell('select productId from product where conditions = 0 and webApiId = ' . $productIdwebId);
        //
        $_GET["do"] = "show";
        $control = "storedetailController.php";
        echo CURL_WEB($control);
    }
}
##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";
    echo 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";
    echo 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";
    echo 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
            $data = array('status' => 2, 'message' => 'تم اضافه هذا المصروف من قبل', 'message_en' => 'This expense has been added before');
            echo json_encode($data);
            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";
            echo 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";
            echo 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
            $data = array('status' => 2, 'message' => 'تم اضافه هذا التصنيف من قبل', 'message_en' => 'This category type has been added before');
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "productCatController.php";
            echo 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";
        echo 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";
        echo 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
            $data = array('status' => 2, 'message' => 'تم اضافه هذا المنتج من قبل', 'message_en' => 'This product type has been added before');
            echo json_encode($data);
            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";
            echo 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";
        echo 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";
        echo CURL_WEB($control);
    }
}
##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";
        echo 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";
            echo 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";
    }

    echo 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";
        echo 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";
        echo CURL_WEB($control);
    }
} elseif ($do == "delpaybill") {
    //
    $_GET["do"] = "delMakeSellBillPayment";
    $control = "sellbillAjaxController.php";
    echo 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";
        echo CURL_WEB($control);
    }
} 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;
    }
}
/* -------------------------------------------------------------------------- */

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