<?php

/* // cash setting
  header("Content-Type: application/json");
  // if u want to make certain do or function do cash , others no use those 2 lines inside it
  //note for good result for read use GET , for update,del use POST/PUT/DELETE
  header("Cache-Control: public, max-age=60"); // browser can cash for for 60 sec  before needing to get it again from server
  header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60) . " GMT"); */
// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, Open-Key');
//header('Access-Control-Max-Age: 86400'); // 24 hours
// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 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;
use \Firebase\JWT\ExpiredException;
use \Firebase\JWT\SignatureInvalidException;

require_once('../models/sql/ConnectionProperty.class.php');

//create default jwt
//$token = JWT::encode(array('username' => getenv('api_user'),'password' => getenv('api_password')), getenv('api_key'));



$do = $_GET["do"];
$tokenExpiration = 60 * 60 * 24; // in seconds
//check jwt
$allheaders = getallheaders();
$jwt = $allheaders["Open-Key"];
$lang = isset($allheaders["lang"]) ? $allheaders["lang"] : 'ar';

$p = R::getRow("select timezone FROM programsettings WHERE programsettingsid=1 limit 1");
//set time zone.It is important for ajax file because time zone is set in authintication which is not used in ajax files which makes it use time zone of php.ini
date_default_timezone_set($p["timezone"]);

if (isset($_REQUEST['useERPIDs']) && $_REQUEST['useERPIDs'] == 1) {
    //ok use it
    $_POST['useERPIDs'] = 1;
} else { // may be it its value = 1 in header
    $_POST['useERPIDs'] = (int) $allheaders["useERPIDs"]; //default
}




if ($_REQUEST['useERPIDs'] == 1 || $jwt == getenv('erpToken')) { // coming from erp chek key , value // or use fixed token
    if ($jwt !== getenv('erpToken')) {
        $data = array('status' => 'error', 'status_code' => 405, 'message' => $httpStatusCodes[405], 'errors' => ['HTTP/1.1 405 Method not NotAllowed']);
        echo json_encode($data);
        exit();
    }
} else { //ouside erp // no jwt needed
    ##user login create token
    if ($do == "userlogin") {
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        if (empty($email) && empty($username)) {
            $errorsArr = ['ar' => 'يرجى ادخال البريد الالكتروني او اسم المستخدم', 'en' => 'Please enter email or username'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        if (empty($password)) {
            $errorsArr = ['ar' => 'يرجى ادخال كلمة المرور', 'en' => 'Please enter password'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Build query based on email or username
        $query = 'SELECT * FROM user WHERE conditions = 0 AND (';
        //        if (!empty($email)) {
        //            $query .= " txtemail = '" . $email . "'";
        //        }
        //    if (!empty($email) && !empty($username)) {
        //        $query .= " OR ";
        //    }
        if (!empty($username)) {
            $query .= " username = '" . $username . "' ";
        }
        $query .= ")";
        $user = R::getRow($query);
        if (empty($user)) {
            $errorsArr = ['ar' => 'بيانات الدخول غير صحيحة', 'en' => 'Invalid login credentials'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Verify password - assuming passwords are stored with password_hash()
        //if (!password_verify($password, $user['password'])) {
        if ($password !== $user['password']) {
            $errorsArr = ['ar' => 'بيانات الدخول غير صحيحة', 'en' => 'Invalid login credentials'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Generate JWT token with expiration
        $data = createJWT($user, 'user');
        echo json_encode($data);
        exit();
    }
    ##
    elseif ($do == "clientlogin") {
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';

        if (empty($email) && empty($username)) {
            $errorsArr = ['ar' => 'يرجى ادخال البريد الالكتروني او اسم المستخدم', 'en' => 'Please enter email or username'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        if (empty($password)) {
            $errorsArr = ['ar' => 'يرجى ادخال كلمة المرور', 'en' => 'Please enter password'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Build query based on email or username
        $query = 'SELECT * FROM client WHERE conditions = 0 AND (';
        if (!empty($email)) {
            $query .= "txtemail = '" . $email . "'";
        }
        //    if (!empty($email) && !empty($username)) {
        //        $query .= " OR ";
        //    }
        //    if (!empty($username)) {
        //        $query .= "username = '" . $username . "'";
        //    }
        $query .= ")";
        $user = R::getRow($query);
        if (empty($user)) {
            $errorsArr = ['ar' => 'بيانات الدخول غير صحيحة', 'en' => 'Invalid login credentials'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }
        if ($user['email_verified'] != 1) {
            $errorsArr = ['ar' => 'يجب تفعيل البريد الالكتروني', 'en' => 'Email has to be verified'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Verify password - assuming passwords are stored with password_hash()
        //if (!password_verify($password, $user['password'])) {
        if ($password !== $user['password']) {
            $errorsArr = ['ar' => 'بيانات الدخول غير صحيحة', 'en' => 'Invalid login credentials'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        // Generate JWT token with expiration
        $data = createJWT($user, 'client');
        echo json_encode($data);
        exit();
    }
    ##clientadd
    else if ($do == "clientadd") {
        $_POST['webApiId'] = (int) $_POST['id'];
        $_POST['store_all'] = 1;
        $_POST['webStoreType'] = 1; //0 add from erp, 1 from webstore , 2 from web store & made bills
        
        if ($_POST['useERPIDs'] == 1) {
            //
            $_GET["do"] = "add";
            $control = "clientController.php";
            echo CURL_WEB($control);
        } else 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
                $errorsArr = ['ar' => 'تم ادخال  اسم العميل  من قبل', 'en' => 'This client name is used before'];
                $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                echo json_encode($data);
                exit();
            } else {

                //
                $_GET["do"] = "add";
                $control = "clientController.php";
                echo CURL_WEB($control);
            }
        }
    }
    ##clientforgetpassword
    else if ($do == "clientnewpassword") {
        $password = trim($_POST['password']);
        $confirmed = trim($_POST['password_confirmed']);
        $webId = (int) $_POST['clientwebApiId'];

        if (empty($password)) {
            $errorsArr = ['ar' => 'يرجى ادخال كلمة المرور', 'en' => 'Please enter password'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        if (empty($confirmed)) {
            $errorsArr = ['ar' => 'يرجى ادخال تاكيد كلمة المرور', 'en' => 'Please enter confirmed password'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        if (empty($webId) || $webId == 0) {
            $errorsArr = ['ar' => 'يرجى ادخال البيانات المطلوبة', 'en' => 'Please enter the required data'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }


        if ($password != $confirmed) {
            $errorsArr = ['ar' => 'تأكيد كلمة المرور غير متطابق', 'en' => 'Confirm password does not match'];
            $data = array(
                'status' => 'error',
                'status_code' => 400,
                'message' => $httpStatusCodes[400],
                'errors' => [$errorsArr[$lang]]
            );
            echo json_encode($data);
            exit();
        }

        try {

            $row = R::getRow('select * from client where conditions = 0 and webApiId = ?', [$webId]);
            if (!$row) {
                $errorsArr = ['ar' => 'لا يوجد عميل', 'en' => 'No client'];
                $data = array(
                    'status' => 'error',
                    'status_code' => 400,
                    'message' => $httpStatusCodes[400],
                    'errors' => [$errorsArr[$lang]]
                );
                echo json_encode($data);
                exit();
            } else if ($row['email_verified'] != 1) {
                $errorsArr = ['ar' => 'يجب تفعيل البريد الالكتروني', 'en' => 'Email has to be verified'];
                $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
                echo json_encode($data);
                exit();
            } else {
                $errorsArr = ['ar' => 'تم تحديث كلمة المرور بنجاح', 'en' => 'Password updated successfully'];
                R::exec("UPDATE `client` SET `password`='$password' WHERE clientid = ?", [$row['clientid']]);
                $data = array(
                    'status' => 'error',
                    'status_code' => 200,
                    'message' => $httpStatusCodes[200],
                    'errors' => [$errorsArr[$lang]]
                );
                echo json_encode($data);
                exit();
            }
        } catch (Exception $e) {
            $data = array(
                'status' => 'error',
                'status_code' => 500,
                'message' => $httpStatusCodes[500],
                'errors' => [$e->getMessage()]
            );
            echo json_encode($data);
            exit();
        }
    }
    ##verifyclientemail
    else if ($do == "sendClientOtpMail") {
        $email = filter_var($_POST['txtemail'], FILTER_SANITIZE_EMAIL);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // $email is valid and sanitized
            $clientId = R::getCell('SELECT clientid FROM client WHERE conditions = 0 AND txtemail = ?', [$email]);
            $_POST['id'] = $clientId;
            //
            $_GET["do"] = "sendEmailOtp";
            $control = "clientController.php";
            echo CURL_WEB($control);
        } else {
            $errorsArr = ['ar' => 'صيغة البريد الالكتروني غير صحيحة', 'en' => 'Invalid email format'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }
    } else if ($do == "verifyclientemail") {
        $otp = (int)$_POST['otp'];
        $email = filter_var($_POST['txtemail'], FILTER_SANITIZE_EMAIL);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // $email is valid and sanitized
            $clientId = R::getCell('SELECT clientid FROM client WHERE conditions = 0 AND txtemail = ?', [$email]);
            $_POST['id'] = $clientId;
            //
            $_GET["do"] = "verifyEmailOtp";
            $control = "clientController.php";
            echo CURL_WEB($control);
        } else {
            $errorsArr = ['ar' => 'صيغة البريد الالكتروني غير صحيحة', 'en' => 'Invalid email format'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }
    }
    ##product quantities
    elseif ($do == "productsquantity") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        //
        if (isset($_POST['proids']) && !empty($_POST['proids'])) {
            $row = R::load('onlinestoresetting', 1);
            $_POST['storeid'] = (int) $row->onlinestoreid;

            //
            $ids = '';
            foreach (explode(',', $_POST['proids']) as $value) {
                $ids .= (int) $value . ',';
            }
            $ids = rtrim($ids, ',');
            //
            $results = R::getAll('SELECT storedetail.*,product.webApiId
                 from storedetail
                 join product on(product.productId = storedetail.productid and product.webApiId > 0 and product.conditions = 0)
                 where storeid =' . $_POST['storeid'] . ' and product.webApiId in(' . $ids . ') ' . $pagingString);
            //cast to object
            $results = array_map(function ($item) {
                return (object) $item;
            }, $results);

            // get total records
            $totalRecords = count(R::getAll('SELECT storedetail.*,product.webApiId
                 from storedetail
                 join product on(product.productId = storedetail.productid and product.webApiId > 0 and product.conditions = 0)
                 where storeid =' . $_POST['storeid'] . ' and product.webApiId in(' . $ids . ') '));
            $data = array(
                'status' => 'success',
                'status_code' => 200,
                'message' => $httpStatusCodes[200],
                'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
                'data' => $results
            );
            echo json_encode($data);
            //        //
            //        $_GET["do"] = "productsquantity";
            //        $control = "storedetailAjaxController.php";
            //        echo CURL_WEB($control);
        }
    }
    ##product quantities
    elseif ($do == "productsdata") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        //order
        switch ($_POST['orderBy']) {
            case "lastProducts":
                $orderBy = ' order by productId desc';
                break;
            case "mostViewed":
                $orderBy = '';
                break;
            default:
                $orderBy = '';
                break;
        }

        $productname = $_POST['productname'];
        $pricefrom = (float) $_POST['pricefrom'];
        $priceto = (float) $_POST['priceto'];
        $priceequal = (float) $_POST['priceequal'];
        $size = $_POST['size'];
        $color = $_POST['color'];
        $rate = $_POST['rate'];
        $discount = $_POST['discount'];

        ##prepare query
        $queryString = '';
        if (isset($_POST['proids']) && !empty($_POST['proids'])) {
            //
            $ids = '';
            foreach (array_unique(explode(',', $_POST['proids'])) as $value) {
                $ids .= (int) $value . ',';
            }
            $ids = rtrim($ids, ',');

            $queryString .= ' and product.webApiId in (' . $ids . ') ';
        }
        if (isset($_POST['catid']) && !empty($_POST['catid'])) {
            $catid = (int) $_POST['catid'];
            $queryString .= ' and productcat.webApiId in (' . $catid . ') ';
        }
        if (isset($productname) && !empty($productname)) {
            $queryString .= ' and product.productName like "%' . $productname . '%" ';
        }
        if ($priceequal != 0) {
            $queryString .= ' and product.productSellUnitPrice = ' . $priceequal . ' ';
        } else {
            if ($pricefrom != 0) {
                $queryString .= ' and product.productSellUnitPrice >= ' . $pricefrom . ' ';
            }
            if ($priceto != 0) {
                $queryString .= ' and product.productSellUnitPrice <= ' . $priceto . ' ';
            }
        }


        #################### store will be online store
        ## get data
        $query = 'select product.*,productcat.productCatName
        from product
        join productcat on productcat.productCatId = product.productCatId
        left join sizecolorstoredetail on (sizecolorstoredetail.productid = product.productId and sizecolorstoredetail.sizeId = ' . $size . ' and sizecolorstoredetail.colorId = ' . $color . ' and sizecolorstoredetail.storeid=1)
        where 1 ';
        //    left join sizecolor as size on size.id = sellbilldetail.sizeid
        //        left join sizecolor as color on color.id = sellbilldetail.colorid
        $results = R::getAll($query . $queryString . $orderBy . $pagingString);
        //cast to object
        $results = array_map(function ($item) {
            return (object) $item;
        }, $results);


        // get total records
        $totalRecords = count(R::getAll($query));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    }

    ##webstore
    #slider
    elseif ($do == "getslider") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;

        $results = R::getAll('select * from slider where isdel=0 and isActive=0 ' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from slider where isdel=0 and isActive=0 '));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    }
    #page
    elseif ($do == "getpage") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $id = (int) $_GET['id'];
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        if (!$id) {
            $results = R::getAll('select * from pages where isdel=0 and isActive=0 ' . $pagingString); //webApiId in (' . $ids . ') '
            //cast to object
            $results = array_map(function ($item) {
                return (object) $item;
            }, $results);

            // get total records
            $totalRecords = count(R::getAll('select * from pages where isdel=0 and isActive=0 '));
            $data = array(
                'status' => 'success',
                'status_code' => 200,
                'message' => $httpStatusCodes[200],
                'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
                'data' => $results
            );
        } else {
            $results = R::getRow('select * from pages where isdel=0 and isActive=0 and id = ?', [$id]); //webApiId in (' . $ids . ') '
            $data = array(
                'status' => 'success',
                'status_code' => 200,
                'message' => $httpStatusCodes[200],
                'meta' => [],
                'data' => $results
            );
        }
        echo json_encode($data);
    }
    #onlineproductcat
    elseif ($do == "getonlineproductcat") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;

        $results = R::getAll('select * from onlineproductcat where isdel=0 ' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from onlineproductcat where isdel=0 '));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    }
    #boarding
    elseif ($do == "getboarding") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;

        $results = R::getAll('select * from boarding where isdel=0 and isActive=0 ' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            $item['image'] = '../upload/boarding/' . $item['image'];
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from boarding where isdel=0 and isActive=0 '));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    } elseif ($do == "categoriesParent") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $parentid = isset($_GET['parentid']) ? (int) $_GET['parentid'] : 0;
        $offset = ($page - 1) * $limit;
        $pagingString = ' and parentid ' . $parentid;
        $pagingString .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        $results = R::getAll('select * from onlineproductcat where isdel=0 ' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            $item['image'] = '../views/default/images/cat_image' . $item['image'];
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from onlineproductcat where isdel=0 '));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    } elseif ($do == "categoriesTree") {
        $parentid = isset($_GET['parentid']) ? (int) $_GET['parentid'] : 0;
        $send_data = buildTree($parentid);
        echo json_encode($send_data, JSON_NUMERIC_CHECK);
    }
    #ads
    elseif ($do == "getads") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;

        $results = R::getAll('select * from ads where isdel=0 and isActive=0 ' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            if (isset($item['image']) && !empty($item['image'])) {
                $item['image'] = Host_URL.'../upload/adFile/' . $item['image'];
            } else {
                $item['image'] = '';
            }
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from ads where isdel=0 and isActive=0 '));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    } elseif ($do == "getadsByLocation") {
        //paging
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        $location = isset($_GET['location']) ? $_GET['location'] : '';
        $results = R::getAll('select * from ads where isdel=0 and isActive=0 and location = "' . $location . '"' . $pagingString); //webApiId in (' . $ids . ') '
        //cast to object
        $results = array_map(function ($item) {
            if (isset($item['image']) && !empty($item['image'])) {
                $item['image'] = Host_URL.'../upload/adFile/' . $item['image'];
            } else {
                $item['image'] = '';
            }
            return (object) $item;
        }, $results);

        // get total records
        $totalRecords = count(R::getAll('select * from ads where isdel=0 and isActive=0  and location = "' . $location . '"'));
        $data = array(
            'status' => 'success',
            'status_code' => 200,
            'message' => $httpStatusCodes[200],
            'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
            'data' => $results
        );
        echo json_encode($data);
    }

    ##check token
    else {
        if (!$jwt) {
            $errorsArr = ['ar' => 'الرمز مفقود', 'en' => 'Token is missing'];
            $data = array('status' => 'error', 'status_code' => 401, 'message' => $httpStatusCodes[401], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        }

        $tokenVerification = verifyUserJWT($jwt);
        if (!$tokenVerification['valid']) {
            $errorsArr = ['ar' => $tokenVerification['error'], 'en' => $tokenVerification['error_en']];
            $data = array(
                'status' => 'error',
                'status_code' => $tokenVerification['code'],
                'message' => $httpStatusCodes[$tokenVerification['code']],
                'errors' => [
                    $errorsArr[$lang]
                ]
            );
            echo json_encode($data);
            exit();
        }
    }
}

//here to continue after jwt check
##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
            $errorsArr =  ['ar' => 'تم اضافه هذه الخزنه من قبل', 'en' => 'This save has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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
            $errorsArr =  ['ar' => 'تم اضافه هذا البنك من قبل', 'en' => 'This bank has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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
            $errorsArr =  ['ar' => 'تم اضافه هذا الحساب البنكى من قبل', 'en' => 'This bank account has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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
            $errorsArr =  ['ar' => 'تم اضافه هذا المستخدم من قبل', 'en' => 'This user has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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
            $errorsArr =  ['ar' => 'تم اضافه هذا النوع من قبل', 'en' => 'This client type has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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);
    }
} elseif ($do == "getclient") {
    $webId = (int) $_POST['webId'];
    $id = (int) $_POST['id'];
    $results = R::getRow('select * from client where conditions = 0 and ( webApiId = ? or clientid = ? )', [$webId, $id]);
    $data = array(
        'status' => 'success',
        'status_code' => 200,
        'message' => $httpStatusCodes[200],
        'meta' => [],
        'data' => $results
    );
    echo json_encode($data);
}
##client
elseif ($do == "clientupdate") {
    $webId = (int) $_POST['id'];
    $_POST['webStoreType'] = 1; //0 add from erp, 1 from webstore , 2 from web store & made bills
    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
            $errorsArr =  ['ar' => 'تم اضافه هذا المورد من قبل', 'en' => 'This supplier has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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") {
    if ($_POST['useERPIDs'] == 1) {
    } else {
        //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
            $errorsArr =  ['ar' => 'تم اضافه هذا المخزن من قبل', 'en' => 'This store has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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);
    }
} else if ($do == "storemoveadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::getRow('select * from storemovement where conditions = 0 and operationnum = ' . $_POST['operationnum']);
        if (isset($row['transferproductid']) && $row['transferproductid'] > 0) { //this id is used cannot add it again
            $errorsArr =  ['ar' => 'تم اضافه هذا التحويل من قبل', 'en' => 'This store movement has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "storemovementController.php";
            echo CURL_WEB($control);
        }
    }
} else if ($do == "storemovedel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        //
        $_GET["do"] = "tempdelete2";
        $_GET["operationnum"] = $webId;
        $control = "storemovementController.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
            $errorsArr =  ['ar' => 'تم اضافه هذا المصروف من قبل', 'en' => 'This expense has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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);
        }
    }
}


##income cat
if ($do == "incomecatadd") {
    if ((int) $_POST['parent'] > 0) {
        $parentid = R::getCell('select incomeTypeId from incometype where webApiId=' . (int) $_POST['parent']);
        $_POST['parent'] = $parentid;
    }
    $_POST['webApiId'] = (int) $_POST['id'];
    //
    $_GET["do"] = "add";
    $control = "incomeTypeController.php";
    echo CURL_WEB($control);
} elseif ($do == "incomecatupdate") {
    $id = R::getCell('select incomeTypeId from incometype where webApiId=' . (int) $_POST['id']);
    $_POST['incomeTypeId'] = $id;
    if ((int) $_POST['parent'] > 0) {
        $parentid = R::getCell('select incomeTypeId from incometype where webApiId=' . (int) $_POST['parent']);
        $_POST['parent'] = $parentid;
    }
    //
    $_GET["do"] = "update";
    $control = "incomeTypeController.php";
    echo CURL_WEB($control);
} elseif ($do == "incomecatdel") {
    $id = R::getCell('select incomeTypeId from incometype where webApiId=' . (int) $_GET['id']);
    $_GET['id'] = $id;
    //
    $_GET["do"] = "delete";
    $control = "incomeTypeController.php";
    echo CURL_WEB($control);
}
##income
if ($do == "incomeadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ((($_POST['webApiId'] > 0 && $_POST['useERPIDs'] != 1) || $_POST['useERPIDs'] == 1) && $_POST['saveid'] > 0 && $_POST['Value'] > 0) {
        $incomeId = (int) R::getCell('SELECT incomeId FROM income where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if ($incomeId > 0 && $_POST['useERPIDs'] != 1) { //this id is used cannot add it again
            $errorsArr =  ['ar' => 'تم اضافه هذا الايراد من قبل', 'en' => 'This income has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            echo json_encode($data);
            exit();
        } else {
            if ((int) $_POST['parent'] > 0 && $_POST['useERPIDs'] != 1) {
                $parentid = R::getCell('select incomeTypeId from incometype where webApiId=' . (int) $_POST['expensetype']);
                $_POST['parent'] = $parentid;
                $_POST['saveid'] = (int) R::getCell('select saveid from save where  webApiId = 0 and webApiId = ' . (int) $_POST['saveid']);
            }

            $_POST['Costcenterid'] = -1;
            $_POST['clientid'] = 0;
            //
            $_GET["do"] = "add";
            $control = "incomeController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "incomedel") {
    $_POST['webApiId'] = (int) $_GET['id'];
    if ($_POST['webApiId'] > 0) {
        $incomeData = R::getRow('SELECT incomeId,dailyentryid FROM income where conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($incomeData) && $incomeData['incomeId'] > 0) { //this id exist , can del it
            //
            $_GET["do"] = "delete";
            $_GET["id"] = $incomeData['incomeId'];
            $_GET["action"] = $incomeData['dailyentryid'];
            $control = "incomeController.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
            $errorsArr =  ['ar' => 'تم اضافه هذا التصنيف من قبل', 'en' => 'This category type has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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);
    }
} elseif ($do == "catsdata") {
    if (isset($_POST['catsids']) && !empty($_POST['catsids'])) {
        //
        $ids = '';
        foreach (array_unique(explode(',', $_POST['catsids'])) as $value) {
            $ids .= (int) $value . ',';
        }
        $ids = rtrim($ids, ',');
        $results = R::getAll('select * from productcat where webApiId in (' . $ids . ')');
        //cast to object
        $results = array_map(function ($item) {
            return (object) $item;
        }, $results);

        echo json_encode($results);
    }
}
##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
            $errorsArr =  ['ar' => 'تم اضافه هذا المنتج من قبل', 'en' => 'This product type has been added before'];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            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
        $row = $row->export();
        $_POST['productId'] = $row['productId'];// or $_POST['productId'] = $row->export()['productId']; if didnot use $row = $row->export();
        $_POST['parcode1'] = $row['parcode'];
        $_POST['webApiId'] = $row['webApiId'];
        $_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);
    }
}

##bill
elseif ($do == "billadd") {
    $ret = array();
    //
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $_POST['sellToSupplier'] = (int) $_POST['sellToSupplier'];
    $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
            $errorsArr =  ['ar' => "هذه الفاتورة رقم " . $_POST['webApiId'] . " تم اضافتها من قبل", 'en' => "this bill with id " . $_POST['webApiId'] . " has been added before"];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            // $ret = array("errorNo" => 1, "errorMsg" => "this bill with id " . $_POST['webApiId'] . " has been added before");
            echo json_encode($data);
            exit();
        } else {
            $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
            if (!isset($row->clientid) || empty($row->clientid)) {
                ## try to add client
                if (isset($_POST['txtName']) && !empty($_POST['txtName'])) {
                    $clientData = [
                        'txtName' => $_POST['txtName'],
                        'txtPhone' => $_POST['txtPhone'],
                        'txtMobile' => $_POST['txtMobile'],
                        'txtDetails' => $_POST['txtDetails'],
                        'webApiId' => $_POST['supplier'],
                        'store_all' => 1,
                        'webStoreType' => 1
                    ];

                    // Temporarily store the main $_POST array
                    $originalPost = $_POST;
                    // Set $_POST to the client data for the controller
                    $_POST = $clientData;

                    $_GET["do"] = "add";
                    $control = "clientController.php";
                    $addClientResult = CURL_WEB($control);
                    $addClientResult = json_decode($addClientResult, true);
                    // Restore the original $_POST array
                    $_POST = $originalPost;

                    if ($addClientResult['status_code'] == 200 || $addClientResult['status'] == 1) {
                        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
                    } else {
                        $errorsArr = ['ar' => "خطأ في إضافة العميل: " . $addClientResult['message'], 'en' => "Error adding client: " . $addClientResult['message']];
                        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                        echo json_encode($data);
                        exit();
                    }
                } else {
                    $errorsArr =  ['ar' => "هذا العميل بالمعرف " . $_POST['supplier'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first"];
                    $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                // $ret = array("errorNo" => 2, "errorMsg" => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
                    echo json_encode($data);
                    exit();
                }
            }
            $_POST['supplier'] = $row->clientid;
            $row = R::load('onlinestoresetting', 1);
            if (!isset($row->onlinestoreid) || empty($row->onlinestoreid)) {
                $row->onlinestoreid = 1;
            }
            $_POST['storeid'] = $row->onlinestoreid;
            
            $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $_POST['sellToSupplier']);
            $_POST['sellToSupplier'] = (int) $row->supplierid;
            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])) {
                        $errorsArr =  ['ar' => "هذا المنتج  بالمعرف  " . $_POST['product' . $i] . "غير موجود تاكد من اضافته اولا", 'en' => "this product  with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first"];
                        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                        // $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($data);
                        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'];
    $_POST['sellToSupplier'] = (int) $_POST['sellToSupplier'];
    $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)) {
            $errorsArr =  ['ar' => "هذا العميل بالمعرف " . $_POST['supplier'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first"];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            // $ret = array("errorNo" => 2, "errorMsg" => "this client with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
            echo json_encode($data);
            exit();
        }
        $_POST['supplier'] = $row->clientid;
        $row = R::load('onlinestoresetting', 1);
        $_POST['storeid'] = $row->onlinestoreid;

        $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $_POST['sellToSupplier']);
        $_POST['sellToSupplier'] = (int) $row->supplierid;

        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['product' . $i] = null; // reset to get its val from erp
                $_POST['parcode' . $i] = $row->parcode;
                //$_POST['product'.$i] = $row->productId;//not working as column name has capital lettes// ***** $row->export() fix this ***** ex: $_POST['product'.$i] = $row->export()['productId'];
                foreach ($row as $key => $value) {
                    if ($key == "productId") {
                        $_POST['product' . $i] = $value;
                    }
                }

                if (!isset($_POST['product' . $i]) || empty($_POST['product' . $i])) {
                    $errorsArr =  ['ar' => "هذا المنتج  بالمعرف  " . $_POST['product' . $i] . "غير موجود تاكد من اضافته اولا", 'en' => "this product  with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first"];
                    $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                    // $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($data);
                    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;
    }
} elseif ($do == "addProductToOrder") {
    //
    $row = R::load('onlinestoresetting', 1);
    if (!isset($row->onlinestoreid) || empty($row->onlinestoreid)) {
        $row->onlinestoreid = 1;
    }
    $_POST['storeid'] = $row->onlinestoreid;
    //
    $_GET["do"] = "addProductToOrder";
    $control = "sellbillController.php";
    echo CURL_WEB($control);
} elseif ($do == "removeProductFromOrder") {
    //
    $row = R::load('onlinestoresetting', 1);
    if (!isset($row->onlinestoreid) || empty($row->onlinestoreid)) {
        $row->onlinestoreid = 1;
    }
    $_POST['storeid'] = $row->onlinestoreid;
    //
    $_GET["do"] = "removeProductFromOrder";
    $control = "sellbillController.php";
    echo CURL_WEB($control);
} elseif ($do == "saveOrderAsBill") {
    $clientId = (int) $_POST['clientId'];
    $offerId = (int) $_POST['offerId'];
    if ($offerId < 1 && $clientId > 0) {
        //loadSellBillByClientIdSimple
        $offerId = (int) R::getCell('SELECT sellbillid
         FROM sellbilloffer
         WHERE conditions=0 and orderSavedBillId=0 and sellbillclientid= ' . $clientId . ' order by sellbillid desc limit 1');
    }

    $_GET['offerId'] = $offerId;
    //
    $_GET["do"] = "saveOfferAsBill";
    $control = "sellbillController.php";
    echo CURL_WEB($control);
} elseif ($do == "saveOrderAdress") {
    $clientId = (int) $_POST['clientId'];
    $offerId = (int) $_POST['offerId'];
    $clientaddress =  $_POST['clientaddress'];
    if ($offerId < 1 && $clientId > 0) {
        //loadSellBillByClientIdSimple
        $offerId = (int) R::getCell('SELECT sellbillid
         FROM sellbilloffer
         WHERE conditions=0 and orderSavedBillId=0 and sellbillclientid= ' . $clientId . ' order by sellbillid desc limit 1');
    }
    //
    R::exec("UPDATE sellbilloffer SET clientaddress='" . $clientaddress . "' WHERE sellbillid = $offerId");
    $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200]);
    echo json_encode($data);
} elseif ($do == "saveorderpayment") {
    $offerId = (int) $_POST['offerId'];
    $clientId = (int) $_POST['clientId'];
    $cashPayed = (float) $_POST['genpay'];
    $visaPayed = (float) $_POST['genpayvisa'];
    $visaAccountId = (int) $_POST['visaAccount'];
    if ($offerId < 1 && $clientId > 0) {
        //loadSellBillByClientIdSimple
        $offerId = (int) R::getCell('SELECT sellbillid
         FROM sellbilloffer
         WHERE conditions=0 and orderSavedBillId=0 and sellbillclientid= ' . $clientId . ' order by sellbillid desc limit 1');
    }

    $totalPayed = $cashPayed + $visaPayed;
    $offerData = (object) R::getRow('SELECT sellbillclientid,sellbillaftertotalbill FROM sellbilloffer WHERE sellbillid = ' . $offerId);
    $clientDebtBefore = R::getCell('SELECT clientdebt FROM client WHERE clientid = ' . $offerData->sellbillclientid);
    $remain = $offerData->sellbillaftertotalbill - $totalPayed;
    $clientDebtafter = $clientDebtBefore + $remain;

    R::exec("UPDATE sellbilloffer SET cashPayed=$cashPayed,visaPayed=$visaPayed,visaAccountId=$visaAccountId,sellbilltotalpayed=$totalPayed,sellbilltotaldeptbefor=$clientDebtBefore,sellbilltotaldeptafter = $clientDebtafter,sellbillfinalbill=$remain WHERE sellbillid = $offerId");
    $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200]);
    echo json_encode($data);
} elseif ($do == "orderdetail") {

    $offerId = (int) $_GET['orderid'];
    $clientId = (int) $_GET['clientid'];
    $sellbillid = 0;
    if ($offerId > 0) {
        $sellbillid = $offerId;
    } else if ($clientId > 0) {
        $sellbillid = R::getCell('SELECT sellbillid
         FROM sellbilloffer
         WHERE conditions=0 and orderSavedBillId=0 and sellbillclientid= ' . $clientId . ' order by sellbillid desc limit 1');
    }
    $sellbillData = (object) R::getRow('SELECT * FROM sellbilloffer WHERE sellbillid = ' . $sellbillid);

    $sellbilldetailData = R::getAll('SELECT sellbilldetail.*, product.productName,productcat.productCatName
                ,size.name as sizeName,color.name as colorName
         FROM sellbilldetailoffer as sellbilldetail
                 JOIN product ON sellbilldetail.sellbilldetailproductid = product.productId
         join productcat on productcat.productCatId=product.productCatId
                 left join sizecolor as size on size.id = sellbilldetail.sizeid
                 left join sizecolor as color on color.id = sellbilldetail.colorid
         WHERE sellbilldetail.sellbillid = ' . $sellbillid . '
                 order by sellbilldetail.sellbilldetailid asc');
    //cast to object
    $sellbilldetailData = array_map(function ($item) {
        return (object) $item;
    }, $sellbilldetailData);


    $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200], 'data' => array($sellbillData, $sellbilldetailData));
    echo json_encode($data);
}
##bill
elseif ($do == "buybilladd") {
    $ret = array();
    //SETTING
    $billnameid = (int) $_POST['billnameid'];
    #queryWithBillnameId
    $billSetting = R::getAll("SELECT billsettings.*, billproperty.billpropertyname
         FROM billsettings JOIN billproperty
         ON billsettings.billpropertyid = billproperty.billpropertyid JOIN billname
         ON billsettings.billnameid = billname.billnameid
         where billproperty.conditions = 0 AND billname.conditions = 0
         and billsettings.billnameid =$billnameid
         order by billsettings.billpropertyid ASC");
    $billSettingArr = [];
    foreach ($billSetting as $value) {
        $billSettingArr[] = $value;
    }

    //
    $_POST['returnBillSetting'] = $billSettingArr[0]['billsettingsvalue'];
    $_POST['storeSetting'] = $billSettingArr[2]['billsettingsvalue'];
    $_POST['dateSetting'] = $billSettingArr[5]['billsettingsvalue'];
    $_POST['noteSetting'] = $billSettingArr[7]['billsettingsvalue'];
    $_POST['productDiscountSetting'] = $billSettingArr[8]['billsettingsvalue'];
    #
    $_POST['pay_num'] = uniqid("0");
    //###############


    $_POST['useERPIDs'] = (int) $_POST['useERPIDs'];
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $_POST['storeId'] = (int) $_POST['storeId'];
    $itr = (int) $_POST['hidden_itr'];
    if ((($_POST['webApiId'] > 0 && $_POST['useERPIDs'] == 0) || ($_POST['webApiId'] == 0 && $_POST['useERPIDs'] == 1)) && $_POST['supplier'] > 0 && $itr > 0) {

        $row = R::findOne('buybill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->buybillid) && $row->buybillid > 0 && $_POST['useERPIDs'] == 0) { //this id is used cannot add it again
            $errorsArr =  ['ar' => "هذا الفاتورة بالمعرف " . $_POST['webApiId'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this bill with id " . $_POST['webApiId'] . " doesnot exist on erp , make sure to add it first"];
            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
            // $ret = array("errorNo" => 1, "errorMsg" => "this bill with id " . $_POST['webApiId'] . " has been added before");
            echo json_encode($data);
            exit();
        } else {
            if ($_POST['useERPIDs'] == 0) {
                $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
                if (!isset($row->supplierid) || empty($row->supplierid)) {
                    $errorsArr =  ['ar' => "هذا المورد بالمعرف " . $_POST['supplier'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this supplier with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first"];
                    $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                    // $ret = array("errorNo" => 2, "errorMsg" => "this supplier with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
                    echo json_encode($data);
                    exit();
                }
                $_POST['supplier'] = $row->supplierid;
                ##
                $row = R::getRow('select * from store where conditions = 0 and webApiId = ' . $_POST['storeId']);
                if (!isset($row['storeId']) || empty($row['storeId'])) {
                    $errorsArr =  ['ar' => "هذا المخزن بالمعرف " . $_POST['storeId'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this Store with id " . $_POST['storeId'] . " doesnot exist on erp , make sure to add it first"];
                    $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                    // $ret = array("errorNo" => 2, "errorMsg" => "this Store with id " . $_POST['storeId'] . " doesnot exist on erp , make sure to add it first");
                    echo json_encode($data);
                    exit();
                }
                $_POST['storeId'] = $row['storeId'];
                //            $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) {
                    if ($_POST['useERPIDs'] == 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])) {
                            $errorsArr =  ['ar' => "هذا المنتج  بالمعرف  " . $_POST['product' . $i] . "غير موجود تاكد من اضافته اولا", 'en' => "this product  with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first"];
                            $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                            // $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($data);
                            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;
                    }
                }
            }

            //
            $_GET["do"] = "add";
            $control = "buyBillController.php";
            echo CURL_WEB($control);
        }
    }
} elseif ($do == "buybillupdate") {
    $_POST['webApiId'] = (int) $_POST['id'];
    $ret = array();
    $row = R::findOne('buybill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
    $_POST['billidnor'] = $row->buybillid;
    $_POST['norbuyBillTotal'] = $row->buybilltotalbill;
    $_POST["controlname"] = "buyBillController.php";
    //SETTING
    $billnameid = (int) $_POST['billnameid'];
    #queryWithBillnameId
    $billSetting = R::getAll("SELECT billsettings.*, billproperty.billpropertyname
         FROM billsettings JOIN billproperty
         ON billsettings.billpropertyid = billproperty.billpropertyid JOIN billname
         ON billsettings.billnameid = billname.billnameid
         where billproperty.conditions = 0 AND billname.conditions = 0
         and billsettings.billnameid =$billnameid
         order by billsettings.billpropertyid ASC");
    $billSettingArr = [];
    foreach ($billSetting as $value) {
        $billSettingArr[] = $value;
    }

    //
    $_POST['returnBillSetting'] = $billSettingArr[0]['billsettingsvalue'];
    $_POST['storeSetting'] = $billSettingArr[2]['billsettingsvalue'];
    $_POST['dateSetting'] = $billSettingArr[5]['billsettingsvalue'];
    $_POST['noteSetting'] = $billSettingArr[7]['billsettingsvalue'];
    $_POST['productDiscountSetting'] = $billSettingArr[8]['billsettingsvalue'];
    #
    $_POST['pay_num'] = uniqid("0");
    //###############


    $_POST['useERPIDs'] = (int) $_POST['useERPIDs'];
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $_POST['storeId'] = (int) $_POST['storeId'];
    $itr = (int) $_POST['hidden_itr'];
    if ($_POST['webApiId'] > 0 && $_POST['supplier'] > 0 && $itr > 0) {
        if ($_POST['useERPIDs'] == 0) {
            $row = R::findOne('supplier', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
            if (!isset($row->supplierid) || empty($row->supplierid)) {
                $errorsArr =  ['ar' => "هذا المورد بالمعرف " . $_POST['supplier'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this supplier with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first"];
                $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                // $ret = array("errorNo" => 2, "errorMsg" => "this supplier with id " . $_POST['supplier'] . " doesnot exist on erp , make sure to add it first");
                echo json_encode($data);
                exit();
            }
            $_POST['supplier'] = $row->supplierid;
            ##
            $row = R::getRow('select * from store where conditions = 0 and webApiId = ' . $_POST['storeId']);
            if (!isset($row['storeId']) || empty($row['storeId'])) {
                $errorsArr =  ['ar' => "هذا المخزن بالمعرف " . $_POST['storeId'] . " غير موجود على erp، تأكد من إضافته أولاً", 'en' => "this Store with id " . $_POST['storeId'] . " doesnot exist on erp , make sure to add it first"];
                $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                // $ret = array("errorNo" => 2, "errorMsg" => "this Store with id " . $_POST['storeId'] . " doesnot exist on erp , make sure to add it first");
                echo json_encode($data);
                exit();
            }
            $_POST['storeId'] = $row['storeId'];
            //            $row = R::load('onlinestoresetting', 1);
            //            if (!isset($row->onlinestoreid) || empty($row->onlinestoreid)) {
            //                $row->onlinestoreid = 1;
            //            }
            //            $_POST['storeid'] = $row->onlinestoreid;
        } else { //useERPIDs = 1
            $_POST['billidnor'] = $_POST['webApiId'];
            $oldbill = R::findOne('buybill', 'conditions = 0 and buybillid = ' . $_POST['webApiId']);
            $_POST['norbuyBillTotal'] = $oldbill->buybilltotalbill;
        }
        for ($i = 1; $i <= $itr; $i++) {
            $pid = (int) $_POST['product' . $i];
            if (isset($pid) && $pid > 0) {

                if ($_POST['useERPIDs'] == 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])) {
                        $errorsArr =  ['ar' => "هذا المنتج  بالمعرف  " . $_POST['product' . $i] . "غير موجود تاكد من اضافته اولا", 'en' => "this product  with id " . $_POST['product' . $i] . " doesnot exist on erp , make sure to add it first"];
                        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
                        // $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($data);
                        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;
                }
            }
        }

        //
        $_GET["do"] = "update";
        $control = "buyBillController.php";
        echo CURL_WEB($control);
    }
} elseif ($do == "buybilldel") {
    $webId = (int) $_GET['id'];
    $_GET['useERPIDs'] = (int) $_GET['useERPIDs'];
    if ($webId > 0) {
        if ($_GET['useERPIDs'] == 0) {
            $row = R::findOne('buybill', 'conditions = 0 and webApiId = ' . $webId);
            $_GET['id'] = $row->buybillid;
        } else {
            //use id coming its billid
        }
        //
        $_GET["do"] = "delete";
        $control = "buyBillController.php";
        echo CURL_WEB($control);
    }
}
/* -------------------------------------------------------------------------- */
##webstore
#wishList add
elseif ($do == "addtowishlist") {
    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $pId = R::getCell('select * from product where conditions = 0 and webApiId = ' . $productid);
    if ($pId > 0) {
        $_POST['productid'] = $pId;
    } else {
        $errorsArr =  ['ar' => "هذا المنتج غير موجود تاكد من اضافته اولا", 'en' => "this product doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }


    //
    $_GET["do"] = "add";
    $control = "wishList.php";
    echo CURL_WEB($control);
}
#wishList del
elseif ($do == "delfromwishlist") {
    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $pId = R::getCell('select * from product where conditions = 0 and webApiId = ' . $productid);
    if ($pId > 0) {
        $_POST['productid'] = $pId;
    } else {
        $errorsArr =  ['ar' => "هذا المنتج غير موجود تاكد من اضافته اولا", 'en' => "this product doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $_GET["do"] = "deletebyclientandproduct";
    $control = "wishList.php";
    echo CURL_WEB($control);
}
#wishList check
elseif ($do == "checkwishlist") {
    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $pId = R::getCell('select * from product where conditions = 0 and webApiId = ' . $productid);
    if ($pId > 0) {
        $_POST['productid'] = $pId;
    } else {
        $errorsArr =  ['ar' => "هذا المنتج غير موجود تاكد من اضافته اولا", 'en' => "this product doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    $id = R::getCell('select id from wishlist where clientid=' . $_POST['clientid'] . ' and productid=' . $_POST['productid']);
    $results = false;
    if ($id > 0) {
        $results = true;
    }
    $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200], 'data' => $results);
    echo json_encode($data);
} elseif ($do == "getwishlist") {
    $clientid = (int) $_POST['clientid'];
    $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 100;
    $offset = ($page - 1) * $limit;
    $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
    $row = R::findOne('client', 'conditions = 0 and ( webApiId = ? or clientid = ? ) ', [$clientid, $clientid]);
    if (!$row) {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    $results = R::getAll("select * from wishlist  where clientid = ? and $pagingString ", [$row->clientid]);
    //cast to object
    $results = array_map(function ($item) {
        return (object) $item;
    }, $results);

    // get total records
    $totalRecords = count(R::getAll('select * from wishlist where clientid = ? ', [$row->clientid]));
    $data = array(
        'status' => 'success',
        'status_code' => 200,
        'message' => $httpStatusCodes[200],
        'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
        'data' => $results
    );
    echo json_encode($data);
}
#productreview add , update
elseif ($do == "productreview") {
    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $pId = R::getCell('select * from product where conditions = 0 and webApiId = ' . $productid);
    if ($pId > 0) {
        $_POST['productid'] = $pId;
    } else {
        $errorsArr =  ['ar' => "هذا المنتج غير موجود تاكد من اضافته اولا", 'en' => "this product doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $_GET["do"] = "add";
    $control = "productreview.php";
    echo CURL_WEB($control);
}
#getproductreview
elseif ($do == "getproductreview") {
    $clientid = (int) $_POST['clientid'];
    $productid = (int) $_POST['productid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    //
    $pId = R::getCell('select * from product where conditions = 0 and webApiId = ' . $productid);
    if ($pId > 0) {
        $_POST['productid'] = $pId;
    } else {
        $errorsArr =  ['ar' => "هذا المنتج غير موجود تاكد من اضافته اولا", 'en' => "this product doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }

    $results = (object) R::getRow('select * from clientproductreview where clientid=' . $_POST['clientid'] . ' and productid=' . $_POST['productid'] . ' limit 1');
    $data = array('status' => 'success', 'status_code' => 200, 'message' => $httpStatusCodes[200], 'data' => $results);
    echo json_encode($data);
}
#clientwishlist
elseif ($do == "clientwishlist") {
    //paging
    $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;
    $pagingString = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
    //
    $clientid = (int) $_POST['clientid'];

    $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $clientid);
    if (isset($row->clientid) && $row->clientid > 0) {
        $_POST['clientid'] = $row->clientid;
    } else {
        $errorsArr =  ['ar' => "هذا العميل غير موجود تاكد من اضافته اولا", 'en' => "this client doesnot exist on erp , make sure to add it first"];
        $data = array('status' => 'error', 'status_code' => 400, 'message' => $httpStatusCodes[400], 'errors' => [$errorsArr[$lang]]);
        echo json_encode($data);
        exit();
    }
    $results = R::getAll('select * from product where productId in (select productid from wishlist where clientid= ' . $_POST['clientid'] . ')' . $pagingString);
    //cast to object
    $results = array_map(function ($item) {
        return (object) $item;
    }, $results);

    // get total records
    $totalRecords = count(R::getAll('select * from product where productId in (select productid from wishlist where clientid= ' . $_POST['clientid'] . ')'));
    $data = array(
        'status' => 'success',
        'status_code' => 200,
        'message' => $httpStatusCodes[200],
        'meta' => ['total_records' => $totalRecords, 'current_page' => $page, 'per_page' => $limit, 'total_pages' => ceil($totalRecords / $limit)],
        'data' => $results
    );
    echo json_encode($data);
}

function buildTree($parentid)
{
    $categories = R::getAll('select * from onlineproductcat where isdel=0 and parentid = ?', [$parentid]);
    $branch = array();
    foreach ($categories as $category) {
        if ($category['parentid'] == $parentid) {
            $children = buildTree($category['parentid']);
            $category["image"] = '../views/default/images/cat_image' . $children['image'];
            if ($children) {
                $category['children'] = $children;
            }
            $branch[] = $category;
        }
    }
    return $branch;
}

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); //
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Set to false
    //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);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $location = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
    if ($http_code == 301 || $http_code == 302 || $http_code == 307 || $http_code == 308) {
        if ($location) {
            curl_close($ch);
            $ch = curl_init($location);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
            //setting them to false.
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $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($user, $type)
{
    global $tokenExpiration, $httpStatusCodes;
    $issuedAt = time();
    $expirationTime = $issuedAt + $tokenExpiration;

    switch ($type) {
        case "user":
            $tokenPayload = array(
                'id' => $user['userid'],
                'name' => $user['employeename'],
                'username' => $user['username'],
                'email' => '',
                'type' => $type,
                'iat' => $issuedAt,
                'exp' => $expirationTime
            );

            break;
        case "client":
            $tokenPayload = array(
                'id' => $user['clientid'],
                'name' => $user['clientname'],
                'username' => '',
                'email' => $user['txtemail'],
                'type' => $type,
                'clientphone' => $user['clientphone'],
                'clientmobile' => $user['clientmobile'],
                'iat' => $issuedAt,
                'exp' => $expirationTime
            );

            break;

        default:
            break;
    }

    $token = JWT::encode($tokenPayload, getenv('api_key'));
    $dataArr = $tokenPayload;
    $dataArr['token'] = $token;
    $dataArr['expires_in'] = $tokenExpiration;

    $data = array(
        'status' => 'success',
        'status_code' => 200,
        'message' => $httpStatusCodes[200],
        'data' => $dataArr
    ); //'token_type' => 'Bearer'

    return $data;
}

// Function to verify user JWT token
function verifyUserJWT($token)
{
    try {
        $decoded = JWT::decode($token, getenv('api_key'), array('HS256'));
        // Check if token is expired
        if (isset($decoded->exp) && $decoded->exp < time()) {
            return array(
                'valid' => false,
                'error' => 'انتهت صلاحية الرمز',
                'error_en' => 'Token has expired',
                'code' => 401
            );
        }

        // Get user data from database
        switch ($decoded->type) {
            case 'user':
                $user = R::getRow('SELECT * FROM user WHERE conditions = 0 AND userid = ?', [$decoded->userid]);
                if (!$user) {
                    return array(
                        'valid' => false,
                        'error' => 'المستخدم غير موجود',
                        'error_en' => 'User not found',
                        'code' => 401
                    );
                } else if ($decoded->userid !== $user['userid'] || $decoded->username !== $user['username']) {
                    return array(
                        'valid' => false,
                        'error' => 'الرمز خطأ',
                        'error_en' => 'Invalid user data in token',
                        'code' => 401
                    );
                }

                break;
            case 'client':
                $user = R::getRow('SELECT * FROM client WHERE conditions = 0 AND clientid = ?', [$decoded->userid]);
                if (!$user) {
                    return array(
                        'valid' => false,
                        'error' => 'المستخدم غير موجود',
                        'error_en' => 'User not found',
                        'code' => 401
                    );
                } else if ($decoded->userid !== $user['clientid'] || $decoded->email !== $user['txtemail']) {
                    return array(
                        'valid' => false,
                        'error' => 'الرمز خطأ',
                        'error_en' => 'Invalid user data in token',
                        'code' => 401
                    );
                }
                break;
            default:
                break;
        }


        // Store verified user data in session
        //    $_SESSION['userid'] = $tokenVerification['user']['userid'];
        //    $_SESSION['username'] = $tokenVerification['user']['username'];
        //    $_SESSION['usergroupid'] = $tokenVerification['user']['usergroupid'];
        //    $_SESSION['usergroupname'] = $tokenVerification['user']['usergroupname'];
        //    $_SESSION['saveid'] = $tokenVerification['user']['saveid'];
        //    $_SESSION['employeename'] = $tokenVerification['user']['employeename'];
        return array(
            'valid' => true,
            'data' => $decoded,
            'user' => $user
        );
    } catch (ExpiredException $e) {
        return array(
            'valid' => false,
            'error' => 'انتهت صلاحية الرمز',
            'error_en' => 'Token has expired',
            'code' => 401
        );
    } catch (SignatureInvalidException $e) {
        return array(
            'valid' => false,
            'error' => 'توقيع الرمز غير صالح',
            'error_en' => 'Invalid token signature',
            'code' => 401
        );
    } catch (Exception $e) {
        return array(
            'valid' => false,
            'error' => 'رمز غير صالح',
            'error_en' => 'Invalid token',
            'code' => 401
        );
    }
}

function setSessionVariables()
{
    global $jwt, $do, $lang;

    $_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;

    $skipVerificationClientDO = array("clientadd", "sendClientOtpMail", "verifyclientemail");
    $decoded = new stdClass();
    if (in_array($do, $skipVerificationClientDO) || $jwt == getenv('erpToken')) {
        $decoded->type = 'client'; //force it to be client
    } else {
        $decoded = JWT::decode($jwt, getenv('api_key'), array('HS256'));
    }
    // Get user data from database
    switch ($decoded->type) {
        case 'user':
            $userData = R::getRow('SELECT * FROM user WHERE conditions = 0 AND userid = ?', [$decoded->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'], ',');
            $_SESSION['erp_lang'] = $lang;

            break;
        case 'client':
            //$user = R::getRow('SELECT * FROM client WHERE conditions = 0 AND clientid = ?', [$decoded->userid]);
            ## assume admin is doing it till asked to be changed
            $userData = R::getRow('select * from user where userid = 1');
            $_SESSION['userid'] = 1;
            $_SESSION['usergroupid'] = 1;
            $_SESSION['username'] = "admin";
            $_SESSION['usergroupname'] = "admin";
            $_SESSION['saveid'] = 1;
            $_SESSION['employeename'] = "admin";
            $_SESSION['searchinonesave'] = 0;
            $_SESSION['branchId'] = 1;
            $_SESSION['erp_lang'] = $lang;

            break;
        default:
            break;
    }
}
