<?php

declare(strict_types=1);

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

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ncoin_transfer.php';

fate_public_session_start();

$member = fate_public_member_current();
if ($member === null) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'message' => '請先登入。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = null;
try {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    $pdo = null;
}

if (!$pdo instanceof PDO) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'message' => '系統暫時無法使用。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$selfId = (int) $member['id'];
$targetRaw = isset($_GET['member_id']) ? trim((string) $_GET['member_id']) : '';
$targetId = (int) preg_replace('/\D/', '', $targetRaw);

$result = fate_ncoin_transfer_lookup_member($pdo, $targetId, $selfId);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
