<?php

function checkRequest($type) {

    $whiteList = array(
        "127.0.0.1",
        "::1",
        "52.77.99.245",
        "13.228.17.195",
        "18.136.241.16",
        "3.1.127.224",
        "52.76.48.59",
        "31.18.7.81",
        "31.18.149.107",
        "103.91.161.125"
    );

    $clientIpProxy = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $clientIp = $_SERVER['REMOTE_ADDR'];

    $postData = json_decode(file_get_contents('php://input'), true);

    $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew.txt", "a");
    fwrite($myfile, "------------".time()."--------------". $clientIp ."-------------". $type ."--------\n");
    fwrite($myfile, json_encode($postData));
    fwrite($myfile, "\n");
    fwrite($myfile, "\n");
    fclose($myfile);

    if(in_array($clientIpProxy, $whiteList) || in_array($clientIp, $whiteList)) {

        $methode = $_SERVER['REQUEST_METHOD'];
        $headers = apache_request_headers();

        if($headers['Content-Type'] == "application/json") {

            switch ($methode) {
                case 'GET':
                    echo "GET";
                    header(http_response_code(400));
                    break;
                case 'POST':

                    if($type == "orderUpdate") {

                        orderUpdate();

                    } else if($type == "orderAccepted") {

                        orderAccepted();

                    } else {

                        header(http_response_code(400));

                    }

                    break;
                case 'PUT':
                    echo 'PUT';
                    header(http_response_code(400));
                    break;
                case 'DELETE':
                    header(http_response_code(400));
                    break;
                default:
                    header(http_response_code(400));
                    break;
            }

        } else {

            header(http_response_code(400));

        }

    } else {

        header(http_response_code(401));

        $errorArray = array(
            "status" => 401,
            "message" => "Unauthorized"
        );

        echo json_encode($errorArray);

        die();

    }

}

function error($massage, $order_no = "") {

    $errorArray = array(
        "status" => 400,
        "message" => $massage
    );

    $myfile = fopen(dirname(__FILE__)."/"."webhookLogNew.txt", "a");
    fwrite($myfile, "---------". $order_no ."-------------------ERROR---------------------". gmdate("Y-m-d\TH:i:s\Z") ."--------------------");
    fwrite($myfile, json_encode($errorArray));
    fwrite($myfile, "\n");
    fwrite($myfile, "\n");
    fclose($myfile);

    echo json_encode($errorArray);

    die();
}