<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| GAME WALLET STATUS
|--------------------------------------------------------------------------
| Halaman diagnosis milik user login. Tidak menampilkan token/signature API.
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/bootstrap.php';

header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if (!$isLoggedIn || $userId <= 0) {
    header(
        'Location: login.php?next=' .
        rawurlencode(
            'game-wallet-status.php'
        )
    );

    exit;
}

$serviceFile = defined('APP_SRC_PATH')
    ? APP_SRC_PATH . '/GameWalletService.php'
    : __DIR__ . '/_app/src/GameWalletService.php';

if (!is_file($serviceFile)) {
    http_response_code(500);
    exit('GameWalletService.php belum dipasang.');
}

require_once $serviceFile;

if (empty($_SESSION['game_wallet_status_csrf'])) {
    $_SESSION['game_wallet_status_csrf'] =
        bin2hex(
            random_bytes(32)
        );
}

$csrfToken = (string)
    $_SESSION['game_wallet_status_csrf'];

$flash = $_SESSION[
    'game_wallet_status_flash'
] ?? null;

unset(
    $_SESSION[
        'game_wallet_status_flash'
    ]
);

$walletService = null;
$pageError = '';

try {
    GameWalletService::bootApi();

    $walletService =
        new GameWalletService($pdo);
} catch (Throwable $exception) {
    $pageError =
        $exception->getMessage();
}

/*
|--------------------------------------------------------------------------
| Rekonsiliasi manual
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'reconcile'
) {
    $postedCsrf = (string) (
        $_POST['csrf_token'] ?? ''
    );

    if (
        $postedCsrf === '' ||
        !hash_equals(
            $csrfToken,
            $postedCsrf
        )
    ) {
        $_SESSION[
            'game_wallet_status_flash'
        ] = [
            'type' => 'error',
            'message' =>
                'Token keamanan tidak valid.',
        ];
    } elseif (
        !$walletService instanceof
            GameWalletService
    ) {
        $_SESSION[
            'game_wallet_status_flash'
        ] = [
            'type' => 'error',
            'message' =>
                'Game wallet belum siap.',
        ];
    } else {
        try {
            $results =
                $walletService
                    ->exitOpenSessions(
                        $userId,
                        'closed'
                    );

            $returned = 0.0;

            foreach ($results as $result) {
                $returned += (float) (
                    $result[
                        'returned_amount'
                    ] ?? 0
                );
            }

            $_SESSION[
                'game_wallet_status_flash'
            ] = [
                'type' => 'success',
                'message' =>
                    $returned > 0
                        ? (
                            'Berhasil mengembalikan IDR ' .
                            number_format(
                                $returned,
                                0,
                                ',',
                                '.'
                            ) .
                            ' ke saldo lokal.'
                        )
                        : 'Tidak ada saldo provider yang perlu dikembalikan.',
            ];
        } catch (Throwable $exception) {
            $_SESSION[
                'game_wallet_status_flash'
            ] = [
                'type' => 'error',
                'message' =>
                    $exception->getMessage(),
            ];
        }
    }

    header(
        'Location: game-wallet-status.php',
        true,
        303
    );

    exit;
}

/*
|--------------------------------------------------------------------------
| Data user dan provider
|--------------------------------------------------------------------------
*/

$userStatement = $pdo->prepare(
    "SELECT *
     FROM users
     WHERE id = :user_id
     LIMIT 1"
);

$userStatement->execute([
    ':user_id' => $userId,
]);

$user = $userStatement->fetch();

if (!$user) {
    http_response_code(404);
    exit('User tidak ditemukan.');
}

$providerBalances = [];

foreach (['nexus', 'sgx'] as $apiName) {
    $providerBalances[$apiName] = [
        'player_code' => '-',
        'balance' => null,
        'error' => '',
    ];

    if (
        !$walletService instanceof
            GameWalletService
    ) {
        $providerBalances[
            $apiName
        ]['error'] = $pageError;

        continue;
    }

    try {
        $playerCode =
            $walletService
                ->resolvePlayerCode(
                    $user,
                    $apiName
                );

        $result =
            GameApi::adapter(
                $apiName
            )->getBalance(
                $playerCode
            );

        $providerBalances[
            $apiName
        ] = [
            'player_code' =>
                $playerCode,
            'balance' => (float) (
                $result['balance'] ??
                $result[
                    'user_balance'
                ] ??
                0
            ),
            'error' => '',
        ];
    } catch (Throwable $exception) {
        $providerBalances[
            $apiName
        ]['error'] =
            $exception->getMessage();
    }
}

$openSessions = [];
$operations = [];
$walletLedger = [];

try {
    $sessionStatement = $pdo->prepare(
        "SELECT *
         FROM game_sessions
         WHERE user_id = :user_id
         ORDER BY id DESC
         LIMIT 20"
    );

    $sessionStatement->execute([
        ':user_id' => $userId,
    ]);

    $openSessions =
        $sessionStatement->fetchAll();

    $operationStatement =
        $pdo->prepare(
            "SELECT *
             FROM game_wallet_operations
             WHERE user_id = :user_id
             ORDER BY id DESC
             LIMIT 20"
        );

    $operationStatement->execute([
        ':user_id' => $userId,
    ]);

    $operations =
        $operationStatement->fetchAll();

    $ledgerStatement =
        $pdo->prepare(
            "SELECT *
             FROM balance_transactions
             WHERE user_id = :user_id
               AND transaction_type IN (
                    'GAME_TRANSFER_OUT',
                    'GAME_TRANSFER_IN',
                    'GAME_TRANSFER_ROLLBACK',
                    'GAME_ORPHAN_RETURN'
               )
             ORDER BY id DESC
             LIMIT 20"
        );

    $ledgerStatement->execute([
        ':user_id' => $userId,
    ]);

    $walletLedger =
        $ledgerStatement->fetchAll();
} catch (Throwable $exception) {
    if ($pageError === '') {
        $pageError =
            $exception->getMessage();
    }
}

function walletStatusMoney($value): string
{
    return number_format(
        (float) $value,
        0,
        ',',
        '.'
    );
}

function walletStatusDate($value): string
{
    if (empty($value)) {
        return '-';
    }

    $timestamp = strtotime(
        (string) $value
    );

    return $timestamp !== false
        ? date(
            'd-m-Y H:i:s',
            $timestamp
        )
        : '-';
}

?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta
        name="viewport"
        content="width=device-width,initial-scale=1"
    >
    <title>Status Game Wallet</title>

    <style>
        *{box-sizing:border-box}
        body{
            margin:0;
            color:#eaf4ff;
            background:#020817;
            font-family:Arial,Helvetica,sans-serif
        }
        .page{
            width:min(1180px,100%);
            margin:0 auto;
            padding:18px
        }
        h1{
            margin:0;
            color:#ffd34e;
            font-size:26px
        }
        .lead{
            margin:8px 0 18px;
            color:#91a8c2;
            font-size:13px;
            line-height:1.6
        }
        .alert{
            margin-bottom:14px;
            padding:12px;
            border-radius:10px;
            font-size:13px;
            line-height:1.55
        }
        .success{
            color:#a1f2c7;
            border:1px solid rgba(52,211,153,.35);
            background:rgba(6,78,59,.52)
        }
        .error{
            color:#ffb1b1;
            border:1px solid rgba(248,113,113,.35);
            background:rgba(91,18,24,.52)
        }
        .cards{
            display:grid;
            grid-template-columns:
                repeat(3,minmax(0,1fr));
            gap:11px;
            margin-bottom:14px
        }
        .card,.panel{
            border:1px solid rgba(0,159,255,.24);
            border-radius:13px;
            background:
                linear-gradient(
                    180deg,
                    #092750,
                    #031127
                )
        }
        .card{
            padding:15px
        }
        .card span,.card small{
            display:block
        }
        .card span{
            color:#8fd5ff;
            font-size:11px;
            font-weight:900
        }
        .card strong{
            display:block;
            margin-top:8px;
            color:#fff;
            font-size:23px;
            overflow-wrap:anywhere
        }
        .card small{
            margin-top:6px;
            color:#7890ac;
            font-size:11px;
            line-height:1.5
        }
        .panel{
            margin-top:13px;
            overflow:hidden
        }
        .panel-head{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            padding:14px
        }
        .panel-head h2{
            margin:0;
            color:#fff;
            font-size:18px
        }
        button,a.button{
            display:inline-flex;
            min-height:39px;
            align-items:center;
            justify-content:center;
            padding:0 13px;
            border:1px solid #ffe382;
            border-radius:8px;
            color:#2b1600;
            background:
                linear-gradient(
                    180deg,
                    #ffe987,
                    #f3ab16
                );
            font-size:11px;
            font-weight:1000;
            text-decoration:none;
            cursor:pointer
        }
        .table-wrap{
            overflow:auto
        }
        table{
            width:100%;
            min-width:880px;
            border-collapse:collapse
        }
        th,td{
            padding:11px 10px;
            border-top:
                1px solid rgba(255,255,255,.07);
            text-align:left;
            vertical-align:top
        }
        th{
            color:#8fd5ff;
            background:#082653;
            font-size:10px
        }
        td{
            color:#dce8f5;
            font-size:11px;
            line-height:1.5
        }
        code{
            color:#ffd34e;
            overflow-wrap:anywhere
        }
        .open{color:#ffd34e}
        .closed,.completed{color:#68e9a5}
        .failed{color:#ff9292}
        .footer-actions{
            display:flex;
            gap:8px;
            margin-top:15px
        }
        @media(max-width:760px){
            .cards{
                grid-template-columns:1fr
            }
            .page{padding:11px}
        }
    </style>
</head>
<body>
<main class="page">
    <h1>Status Game Wallet</h1>

    <p class="lead">
        Pemeriksaan saldo lokal, saldo Nexus/SGX, session game,
        jurnal operasi, dan ledger milik akun login.
    </p>

    <?php if (is_array($flash)): ?>
        <div class="alert <?= e(
            ($flash['type'] ?? '') ===
                'success'
                ? 'success'
                : 'error'
        ); ?>">
            <?= e(
                $flash['message'] ?? ''
            ); ?>
        </div>
    <?php endif; ?>

    <?php if ($pageError !== ''): ?>
        <div class="alert error">
            <?= e($pageError); ?>
        </div>
    <?php endif; ?>

    <section class="cards">
        <article class="card">
            <span>SALDO LOKAL</span>
            <strong>
                IDR <?= e(
                    walletStatusMoney(
                        $user[
                            'balance_local'
                        ] ?? 0
                    )
                ); ?>
            </strong>
            <small>
                Sumber utama saldo website
            </small>
        </article>

        <?php foreach (
            $providerBalances
            as $apiName => $provider
        ): ?>
            <article class="card">
                <span>
                    <?= e(
                        strtoupper($apiName)
                    ); ?>
                </span>

                <strong>
                    <?= $provider['balance'] !== null
                        ? (
                            'IDR ' .
                            e(
                                walletStatusMoney(
                                    $provider['balance']
                                )
                            )
                        )
                        : 'TIDAK TERBACA'; ?>
                </strong>

                <small>
                    Player:
                    <?= e(
                        $provider[
                            'player_code'
                        ]
                    ); ?>

                    <?php if (
                        $provider['error'] !== ''
                    ): ?>
                        <br>
                        Error:
                        <?= e(
                            $provider['error']
                        ); ?>
                    <?php endif; ?>
                </small>
            </article>
        <?php endforeach; ?>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Game Sessions</h2>

            <form method="post">
                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= e($csrfToken); ?>"
                >
                <input
                    type="hidden"
                    name="action"
                    value="reconcile"
                >
                <button type="submit">
                    REKONSILIASI SEKARANG
                </button>
            </form>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>ID / Session</th>
                    <th>Provider</th>
                    <th>Game</th>
                    <th>Transfer</th>
                    <th>Saldo Provider</th>
                    <th>Status</th>
                    <th>Waktu</th>
                </tr>
                </thead>
                <tbody>
                <?php if (empty($openSessions)): ?>
                    <tr>
                        <td colspan="7">
                            Belum ada game session.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach (
                        $openSessions
                        as $session
                    ): ?>
                        <tr>
                            <td>
                                #<?= (int) $session['id']; ?>
                                <br>
                                <code>
                                    <?= e(
                                        $session[
                                            'session_code'
                                        ]
                                    ); ?>
                                </code>
                            </td>
                            <td>
                                <?= e(
                                    strtoupper(
                                        (string) $session[
                                            'provider'
                                        ]
                                    )
                                ); ?>
                                <br>
                                <?= e(
                                    $session[
                                        'provider_username'
                                    ] ?? '-'
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    $session[
                                        'game_name'
                                    ] ?? '-'
                                ); ?>
                                <br>
                                <code>
                                    <?= e(
                                        $session[
                                            'game_code'
                                        ] ?? '-'
                                    ); ?>
                                </code>
                            </td>
                            <td>
                                IDR <?= e(
                                    walletStatusMoney(
                                        $session[
                                            'transfer_amount'
                                        ] ?? 0
                                    )
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    walletStatusMoney(
                                        $session[
                                            'provider_balance_before'
                                        ] ?? 0
                                    )
                                ); ?>
                                →
                                <?= e(
                                    walletStatusMoney(
                                        $session[
                                            'provider_balance_after'
                                        ] ?? 0
                                    )
                                ); ?>
                            </td>
                            <td class="<?= e(
                                strtolower(
                                    (string) $session[
                                        'status'
                                    ]
                                )
                            ); ?>">
                                <?= e(
                                    strtoupper(
                                        (string) $session[
                                            'status'
                                        ]
                                    )
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    walletStatusDate(
                                        $session[
                                            'opened_at'
                                        ] ?? null
                                    )
                                ); ?>
                                <br>
                                <?= e(
                                    walletStatusDate(
                                        $session[
                                            'closed_at'
                                        ] ?? null
                                    )
                                ); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Game Wallet Operations</h2>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>Kode</th>
                    <th>Operasi</th>
                    <th>Provider</th>
                    <th>Nominal</th>
                    <th>Saldo Provider</th>
                    <th>Status</th>
                    <th>Error / Waktu</th>
                </tr>
                </thead>
                <tbody>
                <?php if (empty($operations)): ?>
                    <tr>
                        <td colspan="7">
                            Belum ada operasi wallet.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach (
                        $operations
                        as $operation
                    ): ?>
                        <tr>
                            <td>
                                <code>
                                    <?= e(
                                        $operation[
                                            'operation_code'
                                        ]
                                    ); ?>
                                </code>
                            </td>
                            <td>
                                <?= e(
                                    $operation[
                                        'operation_type'
                                    ]
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    strtoupper(
                                        (string) $operation[
                                            'api_provider'
                                        ]
                                    )
                                ); ?>
                                <br>
                                <?= e(
                                    $operation[
                                        'player_code'
                                    ]
                                ); ?>
                            </td>
                            <td>
                                IDR <?= e(
                                    walletStatusMoney(
                                        $operation[
                                            'amount'
                                        ]
                                    )
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    walletStatusMoney(
                                        $operation[
                                            'provider_balance_before'
                                        ]
                                    )
                                ); ?>
                                →
                                <?= e(
                                    walletStatusMoney(
                                        $operation[
                                            'provider_balance_after'
                                        ]
                                    )
                                ); ?>
                            </td>
                            <td class="<?= e(
                                strtolower(
                                    (string) $operation[
                                        'status'
                                    ]
                                )
                            ); ?>">
                                <?= e(
                                    $operation[
                                        'status'
                                    ]
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    $operation[
                                        'error_message'
                                    ] ?? '-'
                                ); ?>
                                <br>
                                <?= e(
                                    walletStatusDate(
                                        $operation[
                                            'updated_at'
                                        ] ?? null
                                    )
                                ); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Ledger Saldo Lokal</h2>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Jenis</th>
                    <th>Arah</th>
                    <th>Nominal</th>
                    <th>Saldo</th>
                    <th>Referensi</th>
                    <th>Waktu</th>
                </tr>
                </thead>
                <tbody>
                <?php if (empty($walletLedger)): ?>
                    <tr>
                        <td colspan="7">
                            Belum ada ledger game wallet.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach (
                        $walletLedger
                        as $ledger
                    ): ?>
                        <tr>
                            <td>
                                #<?= (int) $ledger['id']; ?>
                            </td>
                            <td>
                                <?= e(
                                    $ledger[
                                        'transaction_type'
                                    ]
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    $ledger[
                                        'direction'
                                    ]
                                ); ?>
                            </td>
                            <td>
                                IDR <?= e(
                                    walletStatusMoney(
                                        $ledger['amount']
                                    )
                                ); ?>
                            </td>
                            <td>
                                <?= e(
                                    walletStatusMoney(
                                        $ledger[
                                            'balance_before'
                                        ]
                                    )
                                ); ?>
                                →
                                <?= e(
                                    walletStatusMoney(
                                        $ledger[
                                            'balance_after'
                                        ]
                                    )
                                ); ?>
                            </td>
                            <td>
                                <code>
                                    <?= e(
                                        $ledger[
                                            'reference_code'
                                        ] ?? '-'
                                    ); ?>
                                </code>
                            </td>
                            <td>
                                <?= e(
                                    walletStatusDate(
                                        $ledger[
                                            'created_at'
                                        ] ?? null
                                    )
                                ); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <div class="footer-actions">
        <a
            class="button"
            href="index.php"
        >
            KEMBALI KE WEBSITE
        </a>
    </div>
</main>
</body>
</html>
