<?php
/*
 * AIWK Wallet Simple API MVP
 * 운영에서는 반드시 로그인 세션의 user_id 기준으로 검사해야 한다.
 */
require_once dirname(__FILE__) . '/wallet_lib.php';

header('Content-Type: application/json; charset=utf-8');

function wallet_json($arr)
{
    echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

try {
    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

    if ($action === 'balance') {
        $user_id = isset($_REQUEST['user_id']) ? (int)$_REQUEST['user_id'] : 0;
        wallet_json(array('ok' => true, 'data' => wallet_get_balances($user_id)));
    }

    if ($action === 'ledger') {
        $user_id = isset($_REQUEST['user_id']) ? (int)$_REQUEST['user_id'] : 0;
        $limit = isset($_REQUEST['limit']) ? (int)$_REQUEST['limit'] : 50;
        wallet_json(array('ok' => true, 'data' => wallet_ledger_list($user_id, $limit)));
    }

    if ($action === 'transfer') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new Exception('POST required');
        $from_user_id = isset($_POST['from_user_id']) ? (int)$_POST['from_user_id'] : 0;
        $to_user_id = isset($_POST['to_user_id']) ? (int)$_POST['to_user_id'] : 0;
        $amount = isset($_POST['amount']) ? (int)$_POST['amount'] : 0;
        $memo = isset($_POST['memo']) ? $_POST['memo'] : '';
        $tx_id = wallet_transfer($from_user_id, $to_user_id, $amount, $memo, 'api', 0);
        wallet_json(array('ok' => true, 'tx_id' => $tx_id));
    }

    wallet_json(array('ok' => false, 'message' => wallet_t('action_not_found')));
} catch (Exception $e) {
    wallet_json(array('ok' => false, 'message' => $e->getMessage()));
}
