<?php

try {
    $__RB_config = json_decode(file_get_contents(__DIR__ . '/config.ini'), true);

    if (!empty($_GET['showConfig']) && $_GET['showConfig'] == '123') {
        echo nl2br(str_replace(' ', '&nbsp;', json_encode($__RB_config, JSON_PRETTY_PRINT)));

        exit;
    }

    if (!defined('__RB_INSTALL') && empty($__RB_config)) {
        echo 'Server error 0x03';

        exit;
    }
}
catch (Exception $error) {
    echo 'Server error 0x02';

    exit;
}

$__RB_client_lng = 'en';

if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $__RB_client_lng      = explode(';', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $__RB_client_lng_full = strtolower(substr($__RB_client_lng[0], 0, 5));
    $__RB_client_lng      = strtolower(substr($__RB_client_lng[0], 0, 2));
}

if (!empty($_COOKIE['debug']) == 'w45v6mfoihup') {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

if (!empty($_GET['deleteServerCache']) == 'w45v6mfoihup') {
    unlink(__DIR__ . '/user/storage/apiCache.json');
}

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/check.php';
require_once __DIR__ . '/text.php';
require_once __DIR__ . '/message.php';
require_once __DIR__ . '/form.php';
require_once __DIR__ . '/lng/index.php';

if (empty($_SESSION['lng'])) {
    __RB_setLng('en');
}

if (file_exists(__DIR__ . '/../../__lang/' . $_SESSION['lng'] . '.php')) {
    require_once __DIR__ . '/../../__lang/' . $_SESSION['lng'] . '.php';
}

if (!empty($_POST['cid'])) {
    if ((empty($_SESSION['checkout']) || !empty($_SESSION['checkout']) && empty($_SESSION['checkout']['hard_block'])) && __RB_api_checkout(__RB_API_ACTION_CHECKOUT_CONFIG, ['cid' => $_POST['cid']], $json, __RB_API_SERVICE_CUSTOMER)) {
        if (empty($_SESSION['checkout'])) {
            $_SESSION['checkout'] = [
                'try'        => 0,
                'hard_block' => 0,
                //'redirect' => 1,
                'config' => $json
            ];
        }
        else {
            $_SESSION['checkout']['config'] = $json;
        }

        //header('location: /checkout');
        //header('location: '. strtok($_SERVER['REQUEST_URI'], '?'));

        //'. strtok($_SERVER['REQUEST_URI'], '?') .'

        echo '
        <form action="/checkout" method="post" id="formSubmit">
			<input type="hidden" name="firstname" value="' . $json['customer']['firstName'] . '">
			<input type="hidden" name="lastname" value="' . $json['customer']['lastName'] . '">
			<input type="hidden" name="email" value="' . $json['customer']['email'] . '">
			<input type="hidden" name="phone" value="' . $json['customer']['phone'] . '">
			<input type="hidden" name="address" value="' . $json['customer']['address'] . '">
			<input type="hidden" name="city" value="' . $json['customer']['city'] . '">
			<input type="hidden" name="zipcode" value="' . $json['customer']['postalCode'] . '">
			<input type="hidden" name="state" value="' . $json['customer']['state'] . '">
			<input type="hidden" name="terms" value="1">
		</form>
		<script>
		document.getElementById("formSubmit").submit();
		</script>
        ';

        exit;
    }

    exit;
}

if (!empty($_SESSION['checkout']) && !empty($_SESSION['checkout']['redirect'])) {
    $_SESSION['checkout']['redirect'] = 0;

    header('location: /checkout');

    exit;
}

if (!empty($_GET['dl']) && is_numeric($_GET['dl']) && $_GET['dl'] > 0 && __RB_signedIn()) {
    if (!empty($_SESSION['user_test']) && __RB_API_URL != 'https://api.amazpay.cc/__api') {
        echo 'File cannot be downloaded. This is a test account.';

        exit;
    }

    header('Content-type: application/pdf');
    header('Content-disposition: attachment; filename=filename.pdf');

    readfile($__RB_config['url']['cp'] . 'content/' . $_GET['dl'] . '.pdf');

    exit;
}

if (!empty($_GET['favorite']) && is_numeric($_GET['favorite']) && $_GET['favorite'] > 0 && __RB_signedIn()) {
    if (empty($_SESSION['favorites'])) {
        $_SESSION['favorites'] = [];
    }

    if (empty($_SESSION['favorites'][$_GET['favorite']])) {
        $_SESSION['favorites'][$_GET['favorite']] = true;

        __RB_success_alert('added', 'favorite');
    }

    echo '<script>window.history.go(-1);</script>';
    exit;
}

if (!empty($_GET['unfavorite']) && is_numeric($_GET['unfavorite']) && $_GET['unfavorite'] > 0 && __RB_signedIn()) {
    if (empty($_SESSION['favorites'])) {
        $_SESSION['favorites'] = [];
    }

    if (!empty($_SESSION['favorites'][$_GET['unfavorite']])) {
        $_SESSION['favorites'][$_GET['unfavorite']] = false;

        unset($_SESSION['favorites'][$_GET['unfavorite']]);

        __RB_success_alert('removed', 'favorite');
    }

    echo '<script>window.history.go(-1);</script>';
    exit;
}

if (!empty($_GET['shoppingListDelete']) && is_numeric($_GET['shoppingListDelete']) && $_GET['shoppingListDelete'] > 0 && __RB_signedIn()) {
    $list = __RB_getShoppingList();

    if (!empty($list[$_GET['shoppingListDelete']])) {
        unset($list[$_GET['shoppingListDelete']]);

        __RB_storeSession('shoppingList', $list);

        __RB_success_alert('removed', 'shopping_list_delete');
    }

    echo '<script>window.history.go(-1);</script>';
    exit;
}

if (!empty($_GET['idFile']) && !empty($_GET['vote']) && is_numeric($_GET['idFile']) && $_GET['idFile'] > 0 && is_numeric($_GET['vote']) && $_GET['vote'] > 0 && $_GET['vote'] < 6 && __RB_signedIn()) {
    if (empty($_SESSION['votes'])) {
        $_SESSION['votes'] = [];
    }

    if (in_array($_GET['idFile'], $_SESSION['votes'])) {
        $_SESSION['votes'][$_GET['idFile']] = false;

        unset($_SESSION['votes'][$_GET['idFile']]);

        __RB_success_alert('removed', 'vote');

        echo '<script>window.history.go(-1);</script>';
        exit;
    }

    if (!in_array($_GET['idFile'], $_SESSION['votes'])) {
        $_SESSION['votes'][$_GET['idFile']] = $_GET['vote'];

        __RB_success_alert('added', 'vote');

        echo '<script>window.history.go(-1);</script>';
        exit;
    }
}

if (!empty($_GET['cancelAccount']) && $_GET['cancelAccount'] == 1) {
    $data = [
        'idCustomer' => $_SESSION['id'],
        'cancel'     => 1
    ];

    $json = '';

    $cancelled = false;

    if (__RB_api_cloud(__RB_API_ACTION_CLOUD_UNSUBSCRIBE, $data, $json)) {
        $_SESSION['status'] = 4;

        foreach ($_SESSION['transactions'] as $key => $val) {
            if ($val['status'] == 0) {
                unset($_SESSION['transactions'][$key]);
            }
        }

        echo "
        <script>
            alert('{$__RB_LNG['success']['form']['unsubscribe']}');
        </script>";
    }
    else {
        if (!empty($json['code']) && $json['code'] == 1002) {
            echo "
            <script>
                alert('{$__RB_LNG['error']['form']['unsubscribe']['disabled_user']}');
            </script>";
        }
        else {
            echo "
                <script>
                    alert('{$__RB_LNG['error']['form']['unsubscribe']['cannot']}');
                </script>";
        }
    }

    echo "<script>window.location = '" . ($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . explode('?', $_SERVER['REQUEST_URI'], 2)[0]) . "';</script>";

    exit;
}

if (!empty($_GET['signout']) && __RB_signedIn()) {
    $lng = $_SESSION['lng'] ?? 'en';

    session_destroy();
    session_start();

    __RB_setLng($lng);

    header('location: /');
}

if (!empty($_POST['file_search'])) {
    header('location: ?file_search=' . htmlspecialchars($_POST['file_search']));

    exit;
}

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_POST) && !empty($_POST['action'])) {
    require_once __DIR__ . '/post.php';
}
