<?php

require_once explode('modules', __FILE__)[0] . 'config/config.inc.php';

$dateAPI = date("Y-m-d\TH:i:s.v\Z");

function dd()
{
    echo '<pre>';
    foreach (func_get_args() as $param) {
        var_dump($param);
    }
    echo '</pre>';

    die();
}

function webhookURL()
{
    $ShopUrl = Tools::getHttpHost(true) . __PS_BASE_URI__;

    return str_replace('/shop', '', $ShopUrl) . 'sibs/webhook';
}

function mLogApp($text, $type = 'INFO')
{
    if (is_array($text)) {
        $text = serialize($text);
    }

    $msgLog  = '[SIBS-API][' . $type . '] ' . $text;
    $showLog = true;

    if (! $showLog) {
        echo $msgLog . '<br/>';
    }

    return true;
}

function hideLoginPass($json)
{
    $bodyArr    = json_decode($json, true);
    $blockWords = '*****';

    if (isset($bodyArr['LgnUsrReq']['LgnUsr']['UsrCrdntls']['Usrnm'])) {
        $bodyArr['LgnUsrReq']['LgnUsr']['UsrCrdntls']['Usrnm'] = $blockWords;
        $bodyArr['LgnUsrReq']['LgnUsr']['UsrCrdntls']['Pwd']   = $blockWords;
    } elseif (isset($bodyArr['request']['detail']['userEmail'])) {
        $bodyArr['request']['detail']['userEmail'] = $blockWords;
        $bodyArr['request']['detail']['pwd']       = $blockWords;
    }

    return json_encode($bodyArr);
}

function sibs_call_curl($url, $body, $authorization = null)
{
    mLogApp('curl URL: ' . $url);
    //remove User as pass for log
    $bodyWithoutUserPass = hideLoginPass($body);
    mLogApp('curl body: ' . $bodyWithoutUserPass);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    $headers = [
        'Accept: application/json',
        'Content-Type: application/json',
    ];

    if (! empty($authorization)) {
        $headers[] = 'Authorization: Bearer ' . $authorization;
    }
    mLogApp('curl HEADER: ' . \Sibs\SibsLogger::prettify($headers));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        mLogApp('curl Error: ' . curl_error($ch), 'ERROR');

        return false;
    }
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    mLogApp('curl HTTP: ' . $http_code, 'ERROR');
    curl_close($ch);
    mLogApp('curl result: ' . $result);

    return json_decode($result, true);
}

function getURL($environment)
{
    $aux = null; // LIVE or PRD
    $URL = [
        'DEV'  => 'https://stargate-dev.qly.sibs.pt',
        'TST'  => 'https://stargate-tst.qly.sibs.pt',
        'CER'  => 'https://stargate-cer.qly.sibs.pt',
        'QLY'  => 'https://stargate.qly.sibs.pt',
        'LIVE' => 'https://stargate.qly.sibs.pt',

    ];

    switch ($environment) {
        case 'DEV':
            $aux = 'https://stargate-dev.qly.sibs.pt'; // QLY

            break;
        case 'TST':
            $aux = 'https://stargate-tst.qly.sibs.pt'; // CER

            break;
        case 'CER':
            $aux = 'https://stargate-cer.qly.sibs.pt'; // DEV

            break;
        case 'QLY':
            $aux = 'https://stargate.qly.sibs.pt'; // DEV

            break;
        case 'LIVE':
            $aux = 'https://stargate.qly.sibs.pt'; // DEV

            break;
    }
    $baseURL = 'https://stargate.qly.sibs.pt';

    if ($aux) {
        $baseURL = $aux;
    }

    $url = [
        'login'                   => $baseURL . '/api/1/management/user/login',
        'activationCode'          => $baseURL . '/api/1/management/app/activation',
        'resendappactivationcode' => $baseURL . '/api/1/management/app/resendappactivationcode',
        'merchantID'              => $baseURL . '/api/1/management/user/acceptor/list',
        'terminalList'            => $baseURL . '/api/1/management/user/terminallist',
        'webhooksList'            => $baseURL . '/api/1/management/spg/webhooks/list',
    ];

    return $url;
}

function returnResponse($data, $code = 200)
{
    global $dateAPI;
    $status    = 'INFO';
    $msgreturn = [
        'success' => 'true',
        'return'  => $data,
        'date'    => $dateAPI,
    ];

    if ($code != 200) {
        $msgreturn['success'] = 'false';
        $status               = 'ERROR';
        http_response_code($code);
    }
    mLogApp($msgreturn, $status);
    echo json_encode($msgreturn);
}

function GetMerchantID($url, $authorization = null)
{
    global $dateAPI, $deviceID;

    $curl = curl_init();

    $jayParsedAry = [
        'UsrAccptrLstReq' => [
            'Hdr' => [
                'XchgId'        => 'D31896D480674526A9194C0A03C5D9C1',
                'DtTm'          => $dateAPI,
                'AppLabl'       => 'WEBMRCHPRT',
                'Vrsn'          => '1.0.0',
                'CrrntMrchntCd' => null,
            ],
            'UsrAccptrLstReq' => [
                'LstUpdtDt' => '1970-01-01T00:00:00.000Z',
            ],
            'Trlr' => [
                'TchnclTrlrData' => [
                    'Device' => [
                        'DeviceID' => $deviceID,
                    ],
                    'Sys' => [
                        'SysFmly'     => 'Windows',
                        'SysArchtctr' => 'x64',
                        'SysVrsn'     => '10',
                    ],
                    'Brwsr' => [
                        'BrwsrNm'        => 'Firefox',
                        'BrwsrVrsn'      => '116.0.0.0',
                        'BrwsrFgrPrtcol' => $deviceID,
                    ],
                    'Lctn' => [
                        'Lt'          => 0,
                        'Ln'          => 0,
                        'LctnDataSrc' => 'BROWSER',
                    ],
                ],
            ],
        ],
        'Trlr' => [
            'XchgId'     => '614D882471154A74A364657E0AB8BF5E',
            'Tmstmp'     => $dateAPI,
            'AppLabl'    => 'WEBMRCHPRT',
            'PltfrmData' => [
                'DeviceId' => $deviceID,
                'Device'   => 'Firefox',
                'OS'       => 'Windows',
                'OSVrsn'   => '10',
                'Lctn'     => [
                    'Lt'          => 0,
                    'Ln'          => 0,
                    'LctnDataSrc' => 'BROWSER',
                ],
                'URL' => $url,
            ],
        ],
    ];

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => '',
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => json_encode($jayParsedAry),
        CURLOPT_HTTPHEADER     => [
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $authorization,
        ],
    ]);

    $response = curl_exec($curl);

    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $id        = json_decode($response, true);
    curl_close($curl);

    return strval($id['UsrAccptrLstRspn']['UsrAccptrLstRspn']['MrchntCd']);
}

function generatePostData($url, $index, $data = null, $CrrntMrchntCd = 'null')
{
    global $dateAPI, $deviceID;
    $auxData = null;

    if (! empty($data) && is_array($data)) {
        $auxData = ', ' . substr(trim(json_encode($data, JSON_UNESCAPED_SLASHES), '{'), 0, -1);
    }
    $returnData = '{"' . $index . '":{"Hdr":{"XchgId":"D31896D480674526A9194C0A03C5D9C1","DtTm":"' . $dateAPI . '","AppLabl":"WEBMRCHPRT","Vrsn":"1.0.0","CrrntMrchntCd":' . $CrrntMrchntCd . '}' . $auxData . ',"Trlr":{"TchnclTrlrData":{"Device":{"DeviceID":"' . $deviceID . '"},"Sys":{"SysFmly":"Windows","SysArchtctr":"x64","SysVrsn":"10"},"Brwsr":{"BrwsrNm":"Firefox","BrwsrVrsn":"92.0","BrwsrFgrPrtcol":"' . $deviceID . '"},"Lctn":{"Lt":0,"Ln":0,"LctnDataSrc":"BROWSER"}}}},"Trlr":{"XchgId":"614D882471154A74A364657E0AB8BF5E","Tmstmp":"' . $dateAPI . '","AppLabl":"WEBMRCHPRT","PltfrmData":{"DeviceId":"' . $deviceID . '","Device":"Firefox","OS":"Windows","OSVrsn":"10","Lctn":{"Lt":0,"Ln":0,"LctnDataSrc":"BROWSER"},"URL":"' . $url . '"}}}';

    return $returnData;
}

mLogApp('START REQUEST SIBS API');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // extract all info form post and header
    extract($_POST);
    extract(getallheaders());
    //check url for curl
    $urlSibs     = getURL($ambiente);
    $merchant_id = null;
    //check if action is set
    if (isset($action) && ! empty($action)) {
        mLogApp('ACTION: ' . $action);
        //try to make login
        if ($action == 'LoginSBO') { /// Try to login
            $data       = ['LgnUsr'=>['UsrCrdntls'=>['Usrnm'=>$login, 'Pwd'=>$pass]]];
            $url        = $urlSibs['login'];
            $postData   = generatePostData($url, 'LgnUsrReq', $data);
            $resultCurl = sibs_call_curl($url, $postData);
            //if got any response or 500 error
            if ($resultCurl) {
                $LgnUsrRspn = $resultCurl['LgnUsrRspn']['LgnUsr'];
                // if is set token and it is approved
                if (isset($LgnUsrRspn['Rslt']['RsltStts']) && $LgnUsrRspn['Rslt']['RsltStts'] == 'APPR') {
                    $nextFlow = null;

                    if (isset($LgnUsrRspn['Hdr']['NxtFlow']) && ! empty($LgnUsrRspn['Hdr']['NxtFlow'])) {
                        //$nextFlow = $LgnUsrRspn['Hdr']['NxtFlow'];
                    }
                    returnResponse(['token'=> $LgnUsrRspn['TknData']['AccsTkn'], 'NxtFlow'=> $nextFlow]);
                } else {
                    returnResponse('Login not approved on SBO', 400);
                }
            } else {
                returnResponse("haven't received a json from curl result", 400);
            }
        } elseif ($action == 'ActivateCode') { /// Try to activate login
            $data       = ['AppAct'=>['Act'=>['ActCd'=>$code]]];
            $url        = $urlSibs['activationCode'];
            $postData   = generatePostData($url, 'AppActReq', $data);
            $resultCurl = sibs_call_curl($url, $postData, $Authorization);

            //if got any response or 500 error
            if ($resultCurl) {
                // if is approved
                if (isset($resultCurl['AppActRspn']['AppAct']['Rslt']['RsltStts']) && $resultCurl['AppActRspn']['AppAct']['Rslt']['RsltStts'] == 'APPR') {
                    returnResponse('Request aproved on SBO');
                } else {
                    returnResponse('Request not approved on SBO', 400);
                }
            } else {
                returnResponse("haven't received a json from curl result", 400);
            }
        } elseif ($action == 'ReSendCode') { /// resend activation code
            $url        = $urlSibs['resendappactivationcode'];
            $postData   = generatePostData($url, 'RsndAppActCdReq');
            $resultCurl = sibs_call_curl($url, $postData, $Authorization);
            //if got any response or 500 error
            if ($resultCurl) {
                // if is approved
                if (isset($resultCurl['RsndAppActCdRspn']['RsndAppActCd']['Rslt']['RsltStts']) && $resultCurl['RsndAppActCdRspn']['RsndAppActCd']['Rslt']['RsltStts'] == 'APPR') {
                    returnResponse('Request aproved on SBO');
                } else {
                    returnResponse('Request not approved on SBO', 400);
                }
            } else {
                returnResponse("haven't received a json from curl result", 400);
            }
        } elseif ($action == 'terminalList') {
            $url                 = $urlSibs['terminalList'];
            $terminalList        = [
                'UsrTermnlLstReq' => [
                    'UsrTermnlFltr' => [
                        'MrchntCd' => null,
                    ],
                    'OrgnFltr' => 'MRPRTL',
                ],
            ];
            $postData   = generatePostData($url, 'UsrTermnlLstReq', $terminalList);

            //die($postData . '---' . $Authorization);
            $resultCurl = sibs_call_curl($url, $postData, $Authorization);
            //if got any response or 500 errort

            if ($resultCurl) {
                // if is approved
                $UsrTermnlLstRspn = $resultCurl['UsrTermnlLstRspn']['UsrTermnlLst'];

                if (isset($UsrTermnlLstRspn['Rslt']['RsltStts']) && $UsrTermnlLstRspn['Rslt']['RsltStts'] == 'APPR') {
                    if (isset($UsrTermnlLstRspn['UsrTermnlLstRspnItm']) && is_array($UsrTermnlLstRspn['UsrTermnlLstRspnItm']) && ! empty($UsrTermnlLstRspn['UsrTermnlLstRspnItm'])) {
                        $terminalList = [];
                        foreach ($UsrTermnlLstRspn['UsrTermnlLstRspnItm'] as $list) {
                            $terminalList[] = [
                                'terminal'    => $list['TermnlCd'],
                                'AccptrCd'    => $list['AccptrCd'],
                                'MrchntCd'    => $list['MrchntCd'],
                                'optionData'  => $list['TermnlCd'] . '-' . $list['AccptrCd'] . '-' . $list['MrchntCd'],
                                'description' => 'Terminal: ' . $list['TermnlCd'] . ' - ' . $list['MrchntDsc'] . ' - MrchntCode: ' . $list['MrchntCd'],
                            ];
                        }
                        returnResponse(['terminalList' => $terminalList]);
                    } else {
                        returnResponse('None terminal was found for this user', 400);
                    }
                } else {
                    returnResponse('Request not approved on SBO', 400);
                }
            } else {
                returnResponse("haven't received a json from curl result", 400);
            }
        } elseif ($action == 'webhooksList') { /// check all webhook's availables
            $url  = $urlSibs['webhooksList'];
            $data =
               [
                   'SPGWbHksLst' => [
                       'Ntty' => [
                           'MrchntCd' => $mrchntcd,
                           'AccptrCd' => $AccptrCd ?? null,
                           'TermnlCd' => $TermnlCd ?? null,
                       ],
                   ],
               ];
            $postData   = generatePostData($url, 'SPGWbHksLstReq', $data, $mrchntcd);
            $resultCurl = sibs_call_curl($url, $postData, $Authorization);
            //if got any response or 500 error

            if ($resultCurl) {
                // if is approved
                $SPGWbHksLstRspn = $resultCurl['SPGWbHksLstRspn']['SPGWbHksLstRspn'];

                if (isset($SPGWbHksLstRspn['Rslt']['RsltStts']) && $SPGWbHksLstRspn['Rslt']['RsltStts'] == 'APPR') {
                    //if exist list of webhook
                    if (isset($SPGWbHksLstRspn['PmtsNtfctn']) && is_array($SPGWbHksLstRspn['PmtsNtfctn']) && ! empty($SPGWbHksLstRspn['PmtsNtfctn'])) {
                        $terminalList = [];
                        $clientID     = $SPGWbHksLstRspn['PmtsNtfctn']['clientId'] ?? null;
                        $webhookToken = $SPGWbHksLstRspn['PmtsNtfctn']['tknData']['AccsTkn'] ?? null;

                        if (empty($webhookToken)) {
                            $webhookToken = $SPGWbHksLstRspn['PmtsNtfctn']['tknData']['RfrshTkn'] ?? null;
                        }
                        foreach ($SPGWbHksLstRspn['PmtsNtfctn'][0]['ChnnlstpNtfctn'] as $list) {
                            $terminalCode       = $list['Ntty']['TermnlCd'] ?? null;
                            $webhookSecret      = $list['ChnnlstpNtfctn'][0]['Scty']['Key'] ?? null;
                            $optionDesctiption  = $list['ChnnlstpNtfctn'][0]['Vl'] ?? 'Client ID: ' . $clientID . ' Webhook Secret: ' . $webhookSecret;

                            if (! empty($clientID) || ! empty($terminalCode) || ! empty($webhookSecret)) {
                                $terminalList[] = [
                                    'clientID'      => $clientID,
                                    'terminalCode'  => $terminalCode,
                                    'webhookSecret' => $webhookSecret,
                                    'optionData'    => $clientID . '(DivSepSIBS)' . $webhookSecret . '(DivSepSIBS)' . $webhookToken,
                                    'description'   => $optionDesctiption,
                                ];
                            }
                        }
                        returnResponse(['terminalList' => $terminalList]);
                    } else {
                        returnResponse('None Webhook was found for this user', 400);
                    }
                } else {
                    returnResponse('Request not approved on SBO', 400);
                }
            } else {
                returnResponse("haven't received a json from curl result", 400);
            }
        }
    } else {
        mLogApp('ACTION not defined', 'ERROR');
        returnResponse('ACTION not defined', 401);
    }
} else {
    mLogApp('Request is not a POST', 'ERROR');
    returnResponse('Request is not a POST', 401);
}
mLogApp('END REQUEST SIBS API');
