<?php

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

use \Firebase\JWT\JWT;

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

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

//here to continue after jwt check

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


##save
if ($do == "gatsave") {
    $id = (int) $_GET['id'];
    $userid = (int) $_GET['userid'];
    $onlydefult = (int) $_GET['onlydefult'];
    if ($id != 0) {//one save
        $retData = (object) R::getRow('select saveid,savename from save where  conditions = 0 and saveid = ' . $id);
    } else if ($userid != 0) {
        if ($onlydefult == 1) {//to choose default save only
            $retData = (object) R::getRow('select saveid,savename from save where  conditions = 0 and saveid = ( select saveid from user where userid = ' . $userid . ' ) ');
        } else {// to choose all saves of user
            $retData = R::getAll('  SELECT save.saveid,save.savename
                                FROM save
                                JOIN user ON (FIND_IN_SET(save.saveid, user.saveids) > 0 OR user.saveids = "0")
                                WHERE user.userid = ' . $userid);
            //array to object
            $retData = array_map(function($array) {
                return (object) $array;
            }, $retData);
        }
    } 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);
}
##user
if ($do == "useradd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->userid) && $row->userid > 0) {//this id is used cannot add it again
            exit();
        } else {
            //
            $_GET["do"] = "add";
            $control = "userController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "userupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['userid'] = $row->userid;
        $_POST['currentdate'] = $row->currentdate;
        //
        $_GET["do"] = "update";
        $control = "userController.php";
        CURL_WEB($control);
    }
} elseif ($do == "userdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('user', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['userid'] = $row->userid;
        $_GET['conditions'] = 0;
        //
        $_GET["do"] = "delete";
        $control = "userController.php";
        CURL_WEB($control);
    }
}
##client
if ($do == "clientadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    if ($_POST['webApiId'] > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->clientid) && $row->clientid > 0) {//this id is used cannot add it again
            exit();
        } else {
            $_POST['store_all'] = 1;
            //
            $_GET["do"] = "add";
            $control = "clientController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "clientupdate") {
    $webId = (int) $_POST['id'];
    if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['id'] = $row->clientid;
        $_POST['store_all'] = 1;
        //
        $_GET["do"] = "update";
        $control = "clientController.php";
        CURL_WEB($control);
    }
} elseif ($do == "clientdel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['id'] = $row->clientid;
        //
        $_GET["do"] = "deleteFinaly";
        $control = "clientController.php";
        CURL_WEB($control);
    }
}
##client
if ($do == "expenseadd") {
    $_POST['store_all'] = 1;
    //
    $_GET["do"] = "add";
    $control = "expensesController.php";
    CURL_WEB($control);
}

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



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

            $_POST['productItr'] = 1;
            //
            $_GET["do"] = "add";
            $control = "productController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "proupdate") {
    $webId = (int) $_POST['id'];
    $_POST['productCatId'] = (int) $_POST['productCatId'];
    if ($webId > 0) {
        if ($_POST['productCatId'] > 0) {
            $row = R::findOne('productcat', 'conditions = 0 and webApiId = ' . $_POST['productCatId']);
            //$_POST['productCatId'] = $row->productCatId;//not working as column name has capital lettes
            foreach ($row as $key => $value) {
                if ($key == "productCatId") {
                    $_POST['productCatId'] = $value;
                }
            }
        }
        $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $webId);
        //$_POST['productId'] = $row->productId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productId") {
                $_POST['productId'] = $value;
            }
        }
        $_POST['productItr'] = 1;
        $_POST['unitsItr1'] = 0;
        $_POST['Unitdone'] = 1;
        //
        $_GET["do"] = "update";
        $control = "productController.php";
        CURL_WEB($control);
    }
} elseif ($do == "prodel") {
    $webId = (int) $_GET['id'];
    if ($webId > 0) {
        $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $webId);
        //$_GET['id'] = $row->productId;//not working as column name has capital lettes
        foreach ($row as $key => $value) {
            if ($key == "productId") {
                $_GET['id'] = $value;
            }
        }
        //
        $_GET["do"] = "deleteFinaly";
        $control = "productController.php";
        CURL_WEB($control);
    }
}
##bill
elseif ($do == "billadd") {
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $itr = (int) $_POST['hidden_itr'];
    if ($_POST['webApiId'] > 0 && $_POST['supplier'] > 0 && $itr > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        if (isset($row->sellbillid) && $row->sellbillid > 0) {//this id is used cannot add it again
            exit();
        } else {
            $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
            $_POST['supplier'] = $row->clientid;
            $row = R::load('onlinestoresetting', 1);
            $_POST['storeid'] = $row->onlinestoreid;
            for ($i = 1; $i <= $itr; $i++) {
                $pid = (int) $_POST['product' . $i];
                if (isset($pid) && $pid > 0) {
                    $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $pid);
                    $_POST['parcode' . $i] = $row->parcode;
                    //$_POST['product'.$i] = $row->productId;//not working as column name has capital lettes
                    foreach ($row as $key => $value) {
                        if ($key == "productId") {
                            $_POST['product' . $i] = $value;
                        }
                    }

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

            $_POST["billnameid"] = 3;
            $_POST["settingdate"] = 1;
            $_POST["Costcenter"] = -1;
            $_POST["distype"] = 1; //constant => means direct discount
            $_POST["sellbillprice"] = $_POST["sellbilltotalbill"];
            //
            $_GET["do"] = "add";
            $control = "sellbillController.php";
            CURL_WEB($control);
        }
    }
} elseif ($do == "billupdate") {
    $_POST['webApiId'] = (int) $_POST['id'];
    $_POST['supplier'] = (int) $_POST['supplier'];
    $itr = (int) $_POST['hidden_itr'];
    if ($_POST['webApiId'] > 0 && $_POST['supplier'] > 0 && $itr > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $_POST['webApiId']);
        $_POST['oldid'] = $row->sellbillid;
        $_POST['bns'] = $row->sellbillserial;
        $_POST['dailyID'] = $row->dailyentryid;
        $row = R::findOne('client', 'conditions = 0 and webApiId = ' . $_POST['supplier']);
        $_POST['supplier'] = $row->clientid;
        $row = R::load('onlinestoresetting', 1);
        $_POST['storeid'] = $row->onlinestoreid;
        for ($i = 1; $i <= $itr; $i++) {
            $pid = (int) $_POST['product' . $i];
            if (isset($pid) && $pid > 0) {
                $row = R::findOne('product', 'conditions = 0 and webApiId = ' . $pid);
                $_POST['parcode' . $i] = $row->parcode;
                //$_POST['product'.$i] = $row->productId;//not working as column name has capital lettes
                foreach ($row as $key => $value) {
                    if ($key == "productId") {
                        $_POST['product' . $i] = $value;
                    }
                }

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

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

    CURL_WEB($control);
} elseif ($do == "billdel") {
    $webId = (int) $_GET['sellbillid'];
    if ($webId > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $webId);
        $_GET['sellbillid'] = $row->sellbillid;
        //
        $_GET["do"] = "delete";
        $control = "sellbillController.php";
        CURL_WEB($control);
    }
} elseif ($do == "paybill") {
    $webId = (int) $_POST['bill_id'];
    if ($webId > 0) {
        $row = R::findOne('sellbill', 'conditions = 0 and webApiId = ' . $webId);
        $_POST['bill_id'] = $row->sellbillid;
        $_POST['getFreshVames'] = 1;
        $id_pay[0] = $_POST;
        unset($_POST);
        $_POST['id_pay'] = json_encode($id_pay);
        $_POST['erpDB'] = ConnectionProperty::getDatabase();
        //
        $_GET["do"] = "makeSellBillPayment";
        $control = "sellbillAjaxController.php";
        CURL_WEB($control);
    }
} elseif ($do == "delpaybill") {
    //
    $_GET["do"] = "delMakeSellBillPayment";
    $control = "sellbillAjaxController.php";
    CURL_WEB($control);
}
##product quantities
elseif ($do == "productsquantity") {
    if (isset($_POST['proids']) && !empty($_POST['proids'])) {
        $row = R::load('onlinestoresetting', 1);
        $_POST['storeid'] = (int) $row->onlinestoreid;
        //
        $_GET["do"] = "productsquantity";
        $control = "storedetailAjaxController.php";
        $retData = CURL_WEB($control);
        var_dump($retData);
    }
}
/* -------------------------------------------------------------------------- */

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

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

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


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

    ## start sending
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

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

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

function setSessionVariables() {
    $_POST['curlpost'] = 1;
    //set them static may change later
    $_SESSION['dbname'] = ConnectionProperty::getDatabase(); //"erp";
    $_SESSION['attempt'] = 0;
    $_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['lic_dateto'] = date('Y-m-d');
    //
    $_SESSION['hidecat'] = 1;
    $_SESSION['clientnegative'] = 1;
    $_SESSION['suplliernegative'] = 1;
    $_SESSION['storenegative'] = 1;
}
