<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

require_once __DIR__ . '/OrderKuota.php';

use YuF1Dev\OrderKuota;


function out($payload) {
    if (is_string($payload)) {
        // Try to decode JSON from upstream, otherwise wrap
        $decoded = json_decode($payload, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            echo json_encode($decoded, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(["raw" => $payload], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        }
    } else {
        echo json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    out(["error" => true, "message" => "Method not allowed. Use POST."]);
}

$action = $_POST['action'] ?? '';
if (!$action) {
    http_response_code(400);
    out(["error" => true, "message" => "Missing 'action'"]);
}

try {
    switch ($action) {
        case 'loginRequest': {
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            if (!$username || !$password) out(["error" => true, "message" => "username and password are required"]);
            $ok = new OrderKuota();
            out($ok->loginRequest($username, $password));
        }
        case 'getAuthToken': {
            $username = $_POST['username'] ?? '';
            $otp = $_POST['otp'] ?? '';
            if (!$username || !$otp) out(["error" => true, "message" => "username and otp are required"]);
            $ok = new OrderKuota();
            out($ok->getAuthToken($username, $otp));
        }
        case 'getTransactionQris': {
            $username = $_POST['username'] ?? '';
            $authToken = $_POST['authToken'] ?? '';
            if (!$username || !$authToken) out(["error" => true, "message" => "username and authToken are required"]);
            $ok = new OrderKuota($username, $authToken);
            out($ok->getTransactionQris());
        }
        case 'withdrawalQris': {
            $username = $_POST['username'] ?? '';
            $authToken = $_POST['authToken'] ?? '';
            $amount = $_POST['amount'] ?? '';
            if (!$username || !$authToken || !$amount) out(["error" => true, "message" => "username, authToken, and amount are required"]);
            $ok = new OrderKuota($username, $authToken);
            out($ok->withdrawalQris($amount));
        }
        default:
            http_response_code(400);
            out(["error" => true, "message" => "Unknown action: $action"]);
    }
} catch (Throwable $e) {
    http_response_code(500);
    out(["error" => true, "message" => $e->getMessage()]);
}
