<?php 

// Redirect jika index.php ada di URL
$requestUri = $_SERVER['REQUEST_URI'];
if (strpos($requestUri, 'index.php') !== false) {
    $newUrl = str_replace('index.php', '', $requestUri);
    header('Location: ' . $newUrl);
    exit;
}

// Validasi dan sanitasi input
$order_id = isset($_GET['order_id']) ? $_GET['order_id'] : '';
$order_id = filter_var($order_id, FILTER_SANITIZE_STRING);

// Validasi agar order_id tidak kosong
if (empty($order_id)) {
    http_response_code(400); // Bad Request
    echo "Invalid order_id.";
    exit;
}

//encrypt_url
define('ENCRYPTION_KEY', hex2bin('9a307dfcf16ac2e4406b1a59a31c1d096eafe37e40c60ddee4bb827b6a947079'));
define('ENCRYPTION_METHOD', 'AES-256-CBC');

function encrypt_url($data) {
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($data, ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA, $iv);
    // Gabungkan IV hex + "::" + encrypted base64, lalu base64 encode seluruh string
    $result = base64_encode(bin2hex($iv) . "::" . base64_encode($encrypted));
    return $result;
}

// Include konfigurasi dengan perlindungan keamanan
include '../../config/connect.php';
include '../../list_data/sweetalert.php';
require_once ('api_control.php');

try {
    // Query untuk mengambil data dari tabel apk_payment
    $stmt = $pdo->prepare("SELECT status FROM apk_payment WHERE order_id = :order_id");
    $stmt->bindParam(':order_id', $order_id, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result === false) {
        http_response_code(404); // Not Found
        echo "Order not found.";
        exit;
    }

    if ($result['status'] == 'BELUM DIBAYAR') {
        include "pay.php";
    } elseif ($result['status'] == 'PENDING' || $result['status'] == 'LUNAS' || $result['status'] == 'CANCELED') {
        include "proses.php";
    } else {
        http_response_code(400); // Bad Request
        echo "Unknown status.";
        exit;
    }

} catch (PDOException $e) {
    // Tangani kesalahan database
    http_response_code(500); // Internal Server Error
    echo "Database error: " . htmlspecialchars($e->getMessage());
    exit;
}
?>
