<?php
$sub_menu = '400905';
include_once('./_common.php');
auth_check($auth[$sub_menu], 'r');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dn_id       = (int)($_POST['dn_id'] ?? 0);
    $act         = preg_replace('/[^a-z_]/i', '', $_POST['act'] ?? '');
    $adm_memo    = $_POST['adm_memo'] ?? '';
    $back_status = preg_replace('/[^가-힣a-z]/u', '', $_POST['back_status'] ?? '');
    if ($dn_id > 0 && in_array($act, ['complete', 'complete_cancel', 'hold', 'cancel'])) {
        $safe_memo = sql_real_escape_string($adm_memo);
        $now       = date('Y-m-d H:i:s');

        // 입금승인취소: 포인트 차감 + 주문 취소
        if ($act === 'complete_cancel') {
            sql_query("UPDATE g5_deposit_notify
                       SET dn_status='취소', dn_admin_memo='{$safe_memo}',
                           dn_processed_at='{$now}', dn_processed_by='{$member['mb_id']}'
                       WHERE dn_id={$dn_id}", false);
            $dn_row2 = sql_fetch("SELECT od_id, mb_id FROM g5_deposit_notify WHERE dn_id={$dn_id}", false);
            if ($dn_row2 && !empty($dn_row2['od_id'])) {
                $safe_od2 = sql_real_escape_string($dn_row2['od_id']);
                $od2 = sql_fetch("SELECT * FROM g5_shoppoint_order WHERE od_id='{$safe_od2}'", false);
                if ($od2 && $od2['od_id'] && $od2['mb_id']) {
                    delete_point($od2['mb_id'], '@buyshoppoints', $od2['mb_id'], $od2['od_id']);
                    sql_query("UPDATE g5_shoppoint_order SET od_status='취소' WHERE od_id='{$safe_od2}'", false);
                }
            }
            header('Location: deposit_notify_list.php?dn_status=' . urlencode($back_status));
            exit;
        }

        $shortage_amount   = max(0.0, (float)($_POST['shortage_amount']   ?? 0));
        $shortage_currency = strtoupper(preg_replace('/[^A-Za-z]/', '', $_POST['shortage_currency'] ?? ''));

        $label_map  = ['complete' => '처리완료', 'hold' => '보류', 'cancel' => '취소'];
        $new_status = $label_map[$act];

        // 보류 사유 → 메모 앞에 자동 추가
        $hold_reason_raw = trim($_POST['hold_reason'] ?? '');
        if ($act === 'hold' && $hold_reason_raw !== '') {
            $safe_reason = mb_substr(preg_replace('/[\r\n<>]/', '', $hold_reason_raw), 0, 60);
            $adm_memo    = '[보류 사유: ' . $safe_reason . ']' .
                           (trim($adm_memo) !== '' ? "\n" . $adm_memo : '');
            $safe_memo   = sql_real_escape_string($adm_memo);
        }

        // 보류 + 부족액 입력 시 메모에 자동 보완
        if ($act === 'hold' && $shortage_amount > 0 && $shortage_currency !== '') {
            $fmt_s = rtrim(rtrim(number_format($shortage_amount, 4, '.', ''), '0'), '.');
            $auto_note = "추가 입금 필요: {$fmt_s} {$shortage_currency}";
            $adm_memo  = trim($adm_memo) !== '' ? trim($adm_memo) . "
" . $auto_note : $auto_note;
            $safe_memo = sql_real_escape_string($adm_memo);
        }

        $safe_sh  = (float)$shortage_amount;
        $safe_shc = sql_real_escape_string($shortage_currency);

        if ($act === 'hold') {
            sql_query("UPDATE g5_deposit_notify
                       SET dn_status='{$new_status}', dn_admin_memo='{$safe_memo}',
                           dn_shortage_amount={$safe_sh}, dn_shortage_currency='{$safe_shc}',
                           dn_processed_at='{$now}', dn_processed_by='{$member['mb_id']}'
                       WHERE dn_id={$dn_id}", false);
        } else {
            sql_query("UPDATE g5_deposit_notify
                       SET dn_status='{$new_status}', dn_admin_memo='{$safe_memo}',
                           dn_processed_at='{$now}', dn_processed_by='{$member['mb_id']}'
                       WHERE dn_id={$dn_id}", false);
        }

        // 입금승인 시 포인트 충전
        if ($act === 'complete') {
            $dn_row = sql_fetch("SELECT od_id, mb_id FROM g5_deposit_notify WHERE dn_id={$dn_id}", false);
            if ($dn_row && !empty($dn_row['od_id'])) {
                $safe_od_id = sql_real_escape_string($dn_row['od_id']);
                $od = sql_fetch("SELECT * FROM g5_shoppoint_order WHERE od_id='{$safe_od_id}'", false);
                if ($od && $od['od_id'] && $od['mb_id'] && (int)$od['od_cart_price'] > 0) {
                    $safe_mb   = sql_real_escape_string($od['mb_id']);
                    $safe_oid  = sql_real_escape_string($od['od_id']);
                    // 중복 충전 방지: 이미 @buyshoppoints 태그로 충전된 내역 확인
                    $chk = sql_fetch("SELECT COUNT(*) AS cnt FROM g5_point
                                      WHERE mb_id='{$safe_mb}'
                                      AND po_rel_table='@buyshoppoints'
                                      AND po_rel_id='{$safe_mb}'
                                      AND po_rel_action='{$safe_oid}'", false);
                    if ((int)($chk['cnt'] ?? 0) === 0) {
                        // 주문 상태 → 입금, 미수금 0, 입금확인일시 기록
                        sql_query("UPDATE g5_shoppoint_order
                                   SET od_status='입금', od_receipt_time='{$now}', od_misu=0
                                   WHERE od_id='{$safe_oid}'", false);
                        // 포인트 충전
                        $od_fx_rate  = (double)($od['od_fx_rate'] ?: 1);
                        $raw_fx_type = strtoupper(trim($od['od_fx_type'] ?? ''));
                        $fx_currency = (strlen($raw_fx_type) > 3) ? substr($raw_fx_type, 3, 3) : ($raw_fx_type ?: 'KRW');
                        $po_point    = (int)$od['od_cart_price'];
                        if ($fx_currency === 'KRW') {
                            $po_content = sprintf('포인트 충전 (주문번호:%s, %s KRW = %s P)',
                                $od['od_id'], number_format($po_point), number_format($po_point));
                        } else {
                            $rate_pu = ($od_fx_rate > 0) ? (1 / $od_fx_rate) : 0;
                            $po_content = sprintf('포인트 충전 (주문번호:%s, 입금액:%s %s × 환율 1 %s=%s P = %s P)',
                                $od['od_id'], $od['od_fx_amount'],
                                $fx_currency, $fx_currency,
                                number_format($rate_pu, 2), number_format($po_point));
                        }
                        insert_point($od['mb_id'], $po_point, $po_content, '@buyshoppoints', $od['mb_id'], $od['od_id']);
                    }
                }
            }
        }

        header('Location: deposit_notify_list.php?dn_status=' . urlencode($back_status));
        exit;
    }
}

$g5['title'] = '입금신고 (포인트충전) 내역';
include_once(G5_ADMIN_PATH . '/admin.head.php');

$status_filter = isset($_GET['dn_status']) ? preg_replace('/[^가-힣a-z]/u', '', $_GET['dn_status']) : '';
$page          = max(1, (int)($_GET['page'] ?? 1));
$rows          = 20;
$offset        = ($page - 1) * $rows;

$where = '';
if ($status_filter !== '')
    $where = "WHERE dn.dn_status='" . sql_real_escape_string($status_filter) . "'";

$total       = sql_fetch("SELECT COUNT(*) AS cnt FROM g5_deposit_notify dn {$where}", false);
$total_cnt   = (int)($total['cnt'] ?? 0);
$total_pages = max(1, ceil($total_cnt / $rows));

$list = [];
$res  = sql_query("SELECT dn.*, o.od_status AS order_status, o.od_deposit_name,
                          o.od_fx_type, o.od_fx_amount, o.od_cart_price, o.od_time,
                          m.mb_name, m.mb_nick, m.mb_email, m.mb_hp, m.mb_datetime,
                          m.mb_today_login, m.mb_login_ip, m.mb_point,
                          m.mb_intercept_date, m.mb_leave_date,
                          (SELECT COUNT(*) FROM g5_shoppoint_order so
                           WHERE so.mb_id=dn.mb_id
                           AND so.od_status NOT IN ('취소','주문취소')) AS mb_ord_cnt,
                          (SELECT COALESCE(SUM(so2.od_cart_price),0) FROM g5_shoppoint_order so2
                           WHERE so2.mb_id=dn.mb_id
                           AND so2.od_status NOT IN ('취소','주문취소')) AS mb_ord_total,
                          (SELECT COUNT(*) FROM g5_login gl WHERE gl.mb_id=dn.mb_id) AS mb_login_cnt
                   FROM g5_deposit_notify dn
                   LEFT JOIN g5_shoppoint_order o ON o.od_id = dn.od_id
                   LEFT JOIN g5_member m ON m.mb_id = dn.mb_id
                   {$where}
                   ORDER BY dn.dn_id DESC
                   LIMIT {$offset}, {$rows}", false);
while ($row = sql_fetch_array($res)) $list[] = $row;

// 플랫폼 계좌 로딩
$shop_default   = sql_fetch("SELECT de_bank_account FROM g5_shop_default LIMIT 1", false);
$raw_accounts   = $shop_default['de_bank_account'] ?? '';
$currency_codes = ['KRW', 'CNY', 'USD', 'EUR', 'JPY', 'VND'];
$platform_accts = [];
foreach ($currency_codes as $c) $platform_accts[$c] = [];
$fallback_accts = [];
foreach (explode("\n", trim($raw_accounts)) as $line) {
    $line = trim($line);
    if ($line === '') continue;
    $matched = false;
    foreach ($currency_codes as $c) {
        if (stripos($line, '[' . $c . ']') !== false) {
            $platform_accts[$c][] = trim(str_ireplace('[' . $c . ']', '', $line));
            $matched = true; break;
        }
    }
    if (!$matched) $fallback_accts[] = $line;
}
if (empty($platform_accts['KRW']) && !empty($fallback_accts))
    $platform_accts['KRW'] = $fallback_accts;

// 환율 테이블 로딩
$admin_fx_rates = [];
$fx_res2 = sql_query("SELECT fx_type, fx_rate, fx_from_amount FROM fx_data", false);
while ($fx_row2 = sql_fetch_array($fx_res2)) {
    $admin_fx_rates[$fx_row2['fx_type']] = [
        'rate'     => (float)$fx_row2['fx_rate'],
        'from_amt' => (float)$fx_row2['fx_from_amount'],
    ];
}

$status_labels = ['' => '전체', '대기' => '대기', '처리완료' => '처리완료', '보류' => '보류', '취소' => '취소'];
$status_colors = ['대기' => '#E87020', '처리완료' => '#2E8B57', '보류' => '#888', '취소' => '#CC3333'];

function dn_format_dt_with_tz($datetime, $tz = 'Asia/Seoul') {
    if (empty($datetime)) return '';
    $tz_safe = (@timezone_open($tz) !== false && $tz !== '') ? $tz : 'Asia/Seoul';
    $dt = new DateTime($datetime, new DateTimeZone($tz_safe));
    $offset_sec = (new DateTimeZone($tz_safe))->getOffset($dt);
    $h = (int)(abs($offset_sec) / 3600);
    $m = (int)((abs($offset_sec) % 3600) / 60);
    $offset_str = sprintf('UTC%s%02d:%02d', $offset_sec >= 0 ? '+' : '-', $h, $m);
    $display = htmlspecialchars($dt->format('Y-m-d H:i'));
    $tz_display = htmlspecialchars($tz_safe . ' (' . $offset_str . ')');
    if ($tz_safe !== 'Asia/Seoul') {
        $dt_kst = clone $dt;
        $dt_kst->setTimezone(new DateTimeZone('Asia/Seoul'));
        $kst_str = htmlspecialchars($dt_kst->format('Y-m-d H:i'));
        return $display
             . ' <small style="color:#7799bb">(' . $tz_display . ')</small>'
             . '<br><small style="color:#55aacc">&#8627; KST: ' . $kst_str . '</small>';
    } else {
        return $display . ' <small style="color:#999">(KST)</small>';
    }
}
function fmt_amount($val) {
    if ((float)$val == (int)(float)$val) return number_format((int)(float)$val);
    return rtrim(rtrim(number_format((float)$val, 4), '0'), '.');
}
function dn_elapsed_str($datetime) {
    $ts = strtotime($datetime);
    if (!$ts) return '';
    $diff = time() - $ts;
    if ($diff < 60)          return '방금';
    if ($diff < 3600)        return (int)($diff/60) . '분 전';
    if ($diff < 86400)       return (int)($diff/3600) . '시간 전';
    if ($diff < 86400*30)    return (int)($diff/86400) . '일 전';
    if ($diff < 86400*365)   return (int)($diff/86400/30) . '개월 전';
    return (int)($diff/86400/365) . '년 전';
}
?>
<style>
.dn-table { width:100%; border-collapse:collapse; font-size:13px; }
.dn-table th { background:#2d2d2d; color:#cccccc; padding:8px 6px; border-bottom:1px solid #454545; text-align:left; }
.dn-table td { padding:8px 6px; border-bottom:1px solid #454545; vertical-align:top; color:#cccccc; transition:background .28s ease, box-shadow .28s ease; }
.dn-table tbody tr { transition: box-shadow .28s ease; }
.dn-table tr:hover td { background:#3c3c3c !important; box-shadow:inset 0 1px 0 rgba(255,255,255,.06), inset 0 -1px 0 rgba(255,255,255,.04); }
.badge { display:inline-block; padding:2px 8px; border-radius:10px; font-size:11px; font-weight:bold; }
.btn-sm { padding:4px 11px; font-size:12px; border:none; border-radius:4px; cursor:pointer; }
.btn-approve { background:#2E8B57; color:#fff; }
.btn-hold    { background:#555; color:#fff; }
.btn-cancel         { background:#993333; color:#fff; }
.btn-approve-cancel { background:#7a4800; color:#ffe0a0; border:1px solid #c07800; }
.btn-approve-cancel:hover { background:#9a5c00; }
/* 매뉴얼 */
.dn-manual-wrap { margin-bottom:14px; }
.dn-manual-toggle {
    background:#3c3c3c; color:#cccccc; border:1px solid #454545;
    padding:5px 14px; border-radius:6px; font-size:12px; cursor:pointer;
    margin-bottom:6px;
}
.dn-manual-toggle:hover { background:#094771; color:#cccccc; }
#dn-manual-body { background:#252526; border:1px solid #454545; border-radius:8px; padding:14px 16px; margin-top:4px; }
.dn-manual-table { width:100%; border-collapse:collapse; font-size:12px; }
.dn-manual-table th { background:#2d2d2d; color:#888888; padding:6px 8px; border-bottom:1px solid #454545; text-align:left; }
.dn-manual-table td { padding:6px 8px; border-bottom:1px solid #3c3c3c; color:#cccccc; vertical-align:top; }
.dn-manual-table tr:last-child td { border-bottom:none; }
.mn-badge { display:inline-block; padding:2px 8px; border-radius:4px; font-size:11px; font-weight:bold; white-space:nowrap; }
.mn-approve        { background:#2E8B5722; color:#4de080; border:1px solid #2E8B57; }
.mn-cancel-approve { background:#7a480022; color:#ffe0a0; border:1px solid #c07800; }
.mn-hold           { background:#55555522; color:#bbbbbb; border:1px solid #888; }
.mn-reject         { background:#99333322; color:#ff9090; border:1px solid #993333; }
.mn-point { font-weight:bold; white-space:nowrap; }
.mn-plus  { color:#4de080; }
.mn-minus { color:#f06060; }
.mn-none  { color:#666666; }
.mn-note  { color:#888888; font-size:11px; margin-top:8px; margin-bottom:0; line-height:1.6; }
.filter-bar { margin-bottom:12px; }
.filter-bar a {
    margin-right:8px; padding:4px 14px; border-radius:14px; text-decoration:none;
    background:#3c3c3c; color:#cccccc; font-size:12px; border:1px solid #454545;
    display:inline-block; transition:background .15s,color .15s,border-color .15s;
}
.filter-bar a:hover  { background:#094771; color:#cccccc; border-color:#0e639c; text-decoration:none; }
.filter-bar a.active { background:#094771; color:#fff; border-color:#0e639c; font-weight:bold; }
/* 당초/신고 2단 블록 */
.cmp-wrap { display:flex; flex-direction:column; gap:3px; }
.cmp-orig { background:#1e2a3e; border-left:3px solid #3794ff; border-radius:3px; padding:4px 8px; transition:background .25s ease; }
.cmp-rep  { background:#2e1e04; border-left:3px solid #d4a030; border-radius:3px; padding:4px 8px; transition:background .25s ease; }
.cmp-lbl-o { font-size:10px; color:#3794ff; display:block; margin-bottom:2px; letter-spacing:.5px; font-weight:bold; }
.cmp-lbl-r { font-size:10px; color:#e8b840; display:block; margin-bottom:2px; letter-spacing:.5px; font-weight:bold; }
.cmp-ok   { color:#4de080; }
.cmp-ng   { color:#f06060; }
.dn-table tr:hover .cmp-orig { background:#094771; }
.dn-table tr:hover .cmp-rep  { background:#573810; }
/* col11 상태: 너비는 저해상도 블록에서 통합 관리 */
/* min-width: 9컬럼 블록에서 통합 관리 */
/* ════ 9컬럼 레이아웃 + 가로 스크롤 + Sticky ════ */
.dn-table-wrap { overflow-x:auto; -webkit-overflow-scrolling:touch; }
.dn-table      { min-width:1260px; table-layout:fixed; }
.dn-table tbody td { background:#1e1e1e; }
.dn-table th:nth-child(1), .dn-table td:nth-child(1) { width:168px; position:sticky; left:0; z-index:2; }
.dn-table th:nth-child(1) { background:#2d2d2d; box-shadow:3px 0 7px rgba(0,0,0,.4); }
.dn-table td:nth-child(1) { background:#1e1e1e; box-shadow:3px 0 7px rgba(0,0,0,.4); }
.dn-table th:nth-child(2), .dn-table td:nth-child(2) { width:82px; }
.dn-table th:nth-child(3), .dn-table td:nth-child(3) { width:155px; word-break:break-all; overflow-wrap:break-word; overflow:hidden; }
.dn-table th:nth-child(4), .dn-table td:nth-child(4) { width:108px; }
.dn-table th:nth-child(5), .dn-table td:nth-child(5) { width:96px; }
.dn-table th:nth-child(6), .dn-table td:nth-child(6) { width:110px; }
.dn-table th:nth-child(7), .dn-table td:nth-child(7) { width:70px; word-break:break-all; overflow:hidden; }
.dn-table th:nth-child(8), .dn-table td:nth-child(8) { width:150px; word-break:break-word; }
.dn-table th:nth-child(9), .dn-table td:nth-child(9) { width:220px; position:sticky; right:0; z-index:2; }
.dn-table th:nth-child(9) { background:#2d2d2d; box-shadow:-3px 0 7px rgba(0,0,0,.4); }
.dn-table td:nth-child(9) { background:#1e1e1e; box-shadow:-3px 0 7px rgba(0,0,0,.4); }
.dn-table tbody tr:hover td:nth-child(1),
.dn-table tbody tr:hover td:nth-child(9) { background:#3c3c3c !important; }
/* 처리 컬럼 */
.adm-memo-wrap { margin-bottom:5px; }
.adm-memo-hint { font-size:10px; color:#888888; display:block; margin-bottom:3px; }
.adm-memo-wrap input[type=text] { width:160px; font-size:11px; padding:3px 5px;
    background:#252526; border:1px solid #454545; color:#cccccc; border-radius:3px; }
.btn-row { display:flex; gap:4px; flex-wrap:wrap; }
/* 회원 셀 */
.mb-cell { cursor:default; }
/* 회원 플로팅 툴팁 */
#mb-floating-tip {
    display:none; position:fixed; z-index:9999;
    background:#252526; border:1px solid #454545;
    border-radius:8px; padding:10px 14px; min-width:290px;
    font-size:12px; color:#cccccc;
    box-shadow:0 6px 24px rgba(0,0,0,.65);
}
.mb-tr { display:flex; align-items:center; gap:6px; padding:4px 0; border-bottom:1px solid #3c3c3c; }
.mb-tr:last-child { border-bottom:none; }
.mb-tl { color:#888888; font-size:11px; min-width:82px; flex-shrink:0; }
.mb-tv { flex:1; word-break:break-all; }
.mb-cp { cursor:pointer; color:#3794ff; font-size:10px; padding:1px 5px;
         border:1px solid #454545; border-radius:2px; background:transparent; flex-shrink:0; }
.mb-cp:hover { background:#094771; color:#3794ff; }
/* ════ 주문정보 통합 셀 ════ */
.col-oi { vertical-align:top; }
.oi-top { display:flex; align-items:baseline; gap:5px; flex-wrap:wrap; margin-bottom:4px; }
.oi-num { color:#666666; font-size:11px; min-width:16px; flex-shrink:0; }
.oi-od  { color:#3794ff; font-size:12px; display:block; overflow:hidden; text-overflow:ellipsis;
          white-space:nowrap; max-width:128px; direction:rtl; unicode-bidi:plaintext; text-align:left; }
.oi-os  { color:#666666; font-size:10px; padding:1px 5px; background:rgba(255,255,255,.06);
          border-radius:3px; white-space:nowrap; }
.oi-dt  { color:#888888; font-size:11px; margin-top:4px; white-space:nowrap; }
.th-sub { font-size:10px; color:#aaaaaa; font-weight:normal; }
/* ════ 검색 행 ════ */
.dn-search-row th { padding:4px 6px !important; background:#2d2d2d !important; border-bottom:2px solid #2d2d2d !important; }
.dn-search-row th:nth-child(1) { background:#2d2d2d !important; }
.dn-search-row th:nth-child(9) { background:#2d2d2d !important; }
.dn-sf { width:100%; box-sizing:border-box; background:#3c3c3c; border:1px solid #454545;
         border-radius:4px; color:#cccccc; font-size:11px; padding:3px 6px; outline:none; }
.dn-sf::placeholder { color:#666666; }
.dn-sf:focus { border-color:#0e639c; background:#094771; }
/* ════ 정렬 인디케이터 ════ */
#dn-hdr th[data-sort] { cursor:pointer; user-select:none; }
#dn-hdr th[data-sort]:hover { background:#094771 !important; }
.sort-ic { font-size:10px; color:#888888; margin-left:3px; }
.sort-asc  .sort-ic { color:#3794ff; }
.sort-desc .sort-ic { color:#e8b840; }

/* ════════════════════════════════════════════════
   라이트 모드 오버라이드  [data-theme="light"]
   ════════════════════════════════════════════════ */
[data-theme="light"] .dn-table th {
    background: #2a5080; color: #fff; border-bottom-color: #1e3a6a;
}
[data-theme="light"] .dn-table td {
    color: #333; border-bottom-color: #d0dde8;
}
[data-theme="light"] .dn-table tbody td { background: #fff; }
[data-theme="light"] .dn-table tr:hover td {
    background: #d8eaf8 !important;
    box-shadow: inset 0 1px 0 rgba(0,80,160,.06), inset 0 -1px 0 rgba(0,80,160,.04) !important;
}
/* sticky 열 배경 */
[data-theme="light"] .dn-table th:nth-child(1) { background: #2a5080; box-shadow: 3px 0 7px rgba(0,0,0,.12); }
[data-theme="light"] .dn-table td:nth-child(1) { background: #fff;    box-shadow: 3px 0 7px rgba(0,0,0,.12); }
[data-theme="light"] .dn-table th:nth-child(9) { background: #2a5080; box-shadow:-3px 0 7px rgba(0,0,0,.12); }
[data-theme="light"] .dn-table td:nth-child(9) { background: #fff;    box-shadow:-3px 0 7px rgba(0,0,0,.12); }
[data-theme="light"] .dn-table tbody tr:hover td:nth-child(1),
[data-theme="light"] .dn-table tbody tr:hover td:nth-child(9) { background: #d8eaf8 !important; }

/* 당초/신고 2단 블록 */
[data-theme="light"] .cmp-orig { background: #ddeeff; border-left-color: #2a80c0; }
[data-theme="light"] .cmp-rep  { background: #fff4d8; border-left-color: #c08000; }
[data-theme="light"] .cmp-lbl-o { color: #1a5a90; }
[data-theme="light"] .cmp-lbl-r { color: #996600; }
[data-theme="light"] .cmp-ok   { color: #1a7a3a; }
[data-theme="light"] .cmp-ng   { color: #c03020; }
[data-theme="light"] .dn-table tr:hover .cmp-orig { background: #c8e4ff; }
[data-theme="light"] .dn-table tr:hover .cmp-rep  { background: #ffe8b0; }

/* 필터바 */
[data-theme="light"] .filter-bar a {
    background: #e8f0f8; color: #336699; border-color: #b0c8e0;
}
[data-theme="light"] .filter-bar a:hover  { background: #c8e0f8; color: #1a4a80; border-color: #80aacc; }
[data-theme="light"] .filter-bar a.active { background: #2a5080; color: #fff; border-color: #1a3860; }

/* 버튼 안내 (manual) */
[data-theme="light"] .dn-manual-toggle {
    background: #f0f5fa; color: #336699; border-color: #b0c8e0;
}
[data-theme="light"] .dn-manual-toggle:hover { background: #ddeeff; }
[data-theme="light"] #dn-manual-body { background: #f8fafb; border-color: #c0d0e0; }
[data-theme="light"] .dn-manual-table th { background: #e8f0f8; color: #336699; border-bottom-color: #c0d0e0; }
[data-theme="light"] .dn-manual-table td { color: #333; border-bottom-color: #d8e4f0; }

/* 소수점 +/- */
[data-theme="light"] .mn-plus  { color: #1a7a3a; }
[data-theme="light"] .mn-minus { color: #c03020; }
[data-theme="light"] .mn-none  { color: #666; }
[data-theme="light"] .mn-note  { color: #336699; }
[data-theme="light"] .mn-approve        { background: #d8f5e8; color: #1a6a3a; border-color: #2a8a4a; }
[data-theme="light"] .mn-cancel-approve { background: #fff3d8; color: #886000; border-color: #cc9000; }
[data-theme="light"] .mn-hold           { background: #f0f0f0; color: #666; border-color: #aaa; }
[data-theme="light"] .mn-reject         { background: #fde8e8; color: #aa2222; border-color: #cc4444; }

/* 검색 행 */
[data-theme="light"] .dn-search-row th,
[data-theme="light"] .dn-search-row th:nth-child(1),
[data-theme="light"] .dn-search-row th:nth-child(9) {
    background: #dce8f4 !important; border-bottom-color: #a0bcd8 !important;
}
[data-theme="light"] .dn-sf {
    background: #fff !important; border-color: #aabccc !important; color: #333 !important;
}
[data-theme="light"] .dn-sf::placeholder { color: #aaa !important; }
[data-theme="light"] .dn-sf:focus { border-color: #4a80b0 !important; background: #f4f8ff !important; }

/* 주문 정보 셀 내 텍스트 */
[data-theme="light"] .oi-od  { color: #1a5a9a !important; }
[data-theme="light"] .oi-num { color: #777 !important; }
[data-theme="light"] .oi-os  { color: #555 !important; background: rgba(0,0,0,.06) !important; }
[data-theme="light"] .oi-dt  { color: #666 !important; }
[data-theme="light"] .th-sub { color: #4a6a8a !important; }

/* 정렬 인디케이터 */
[data-theme="light"] .sort-ic          { color: #8090a8 !important; }
[data-theme="light"] .sort-asc  .sort-ic { color: #1a60aa !important; }
[data-theme="light"] .sort-desc .sort-ic { color: #8a5e00 !important; }
[data-theme="light"] #dn-hdr th[data-sort]:hover { background: #1e3a60 !important; }

/* 처리 메모 입력창 */
[data-theme="light"] .adm-memo-hint { color: #6a7a8a !important; }
[data-theme="light"] .adm-memo-wrap input[type=text] {
    background: #fff !important; border-color: #aabccc !important; color: #333 !important;
}

/* ── 라이트/다크 공용 색상 클래스 ── */
.cv-val      { color:#cccccc; }
.cv-sub      { color:#7a9ab0; }
.cv-accent   { color:#3794ff; }
.cv-rate-res { color:#e8c060; }
.cv-dt-rep   { color:#d0dcea; font-size:12px; }
.cv-dt-ok    { color:#a0c8a0; font-size:12px; }
.cv-dt-err   { color:#e05555; font-size:12px; }
.cv-mb-name  { color:#8a9eb0; }
.cv-mb-nick  { color:#6a8898; }
.cv-acct-ok  { color:#4a9a6a; }
.cv-alt-acct { color:#E8A040; font-size:11px; }

[data-theme="light"] .cv-val      { color:#1a3a5a !important; }
[data-theme="light"] .cv-sub      { color:#4a6070 !important; }
[data-theme="light"] .cv-accent   { color:#1a5a9a !important; }
[data-theme="light"] .cv-rate-res { color:#7a5000 !important; }
[data-theme="light"] .cv-dt-rep   { color:#333 !important; }
[data-theme="light"] .cv-dt-ok    { color:#1a6a2a !important; }
[data-theme="light"] .cv-dt-err   { color:#c03020 !important; }
[data-theme="light"] .cv-mb-name  { color:#444 !important; }
[data-theme="light"] .cv-mb-nick  { color:#5a6a78 !important; }
[data-theme="light"] .cv-acct-ok  { color:#1a6a3a !important; }
[data-theme="light"] .cv-alt-acct { color:#8a5000 !important; }
/* PHP 변수 색상 (#cccccc 회원 ID - 라이트에서 너무 연함) */
[data-theme="light"] .col-oi b[style*="9BB8CC"] { color:#1a4a7a !important; }
/* null-match span (#cccccc - 라이트에서 거의 안 보임) */
[data-theme="light"] .dn-table td span[style*="c8d8e8"] { color:#444 !important; }
/* 기한 미초과 날짜 (#a0c8a0 - 라이트에서 연한 녹색) */
[data-theme="light"] .cmp-orig span[style*="a0c8a0"] { color:#1a6a2a !important; }

</style>
<script>
var _tip=null, _tipHide=null;
function showMbTip(ev,el){
    clearTimeout(_tipHide);
    if(!_tip){ _tip=document.getElementById('mb-floating-tip');
        _tip.onmouseenter=function(){clearTimeout(_tipHide);};
        _tip.onmouseleave=function(){_tipHide=setTimeout(function(){_tip.style.display='none';},200);}; }
    var d=el.dataset;
    var rows=[
        ['아이디',       d.mbId,                    true],
        ['이름',         d.mbName,                  true],
        ['닉네임',       d.mbNick,                  true],
        ['이메일',       d.mbEmail,                 true],
        ['전화번호',     d.mbHp,                    true],
        ['가입일시',     d.mbDt,                    false],
        ['마지막로그인', d.mbLogin,                 false],
        ['로그인 횟수',  d.mbLoginCnt+'회',         false],
        ['구매 횟수',    d.mbOrdCnt+'건',           false],
        ['구매 총액',    d.mbOrdTotal+' KRW',       false],
        ['포인트 잔액',  d.mbPoint+' P',            false],
    ];
    if(d.mbIntercept && d.mbIntercept>'00000000')
        rows.push(['⛔ 차단일','<span style="color:#e05555">'+d.mbIntercept+'</span>',false]);
    if(d.mbLeave && d.mbLeave>'00000000')
        rows.push(['탈퇴일','<span style="color:#888">'+d.mbLeave+'</span>',false]);
    var skip={'0회':1,'0건':1,'0 KRW':1,'0 P':1,' KRW':1,' P':1,'':1};
    var html='';
    for(var i=0;i<rows.length;i++){
        var v=rows[i][1]||'';
        if(skip[v]) continue;
        var plain=v.replace(/<[^>]+>/g,'');
        var cp=rows[i][2]?'<button class="mb-cp" onclick="cpTip(this,\''+plain.replace(/\\/g,'\\\\').replace(/'/g,"\\'")+'\')" onmousedown="event.stopPropagation()">복사</button>':'';
        html+='<div class="mb-tr"><span class="mb-tl">'+rows[i][0]+'</span><span class="mb-tv">'+v+'</span>'+cp+'</div>';
    }
    _tip.innerHTML=html;
    _tip.style.display='block';
    _tip.style.left=Math.min(ev.clientX+14,window.innerWidth-310)+'px';
    _tip.style.top =Math.min(ev.clientY+14,window.innerHeight-360)+'px';
}
function qHideMbTip(){_tipHide=setTimeout(function(){if(_tip)_tip.style.display='none';},200);}
function cpTip(btn,text){
    var done=function(){btn.textContent='✓';setTimeout(function(){btn.textContent='복사';},1200);};
    if(navigator.clipboard){navigator.clipboard.writeText(text).then(done);}
    else{var t=document.createElement('textarea');t.value=text;document.body.appendChild(t);t.select();document.execCommand('copy');document.body.removeChild(t);done();}
}

// 커스텀 confirm 다이얼로그
var _dnConfirmForm = null, _dnShortageMode = false, _dnSelectedReason = '';
var _dnHoldCurrency = '', _dnActionMode = '';

var _DN_APPROVE_REASONS = [
    { id:'confirmed', label:'입금 확인 완료. 포인트가 충전되었습니다.',            custom:false },
    { id:'complete',  label:'입금이 정상 처리되었습니다. 감사합니다.',             custom:false },
    { id:'approved',  label:'입금 승인 완료. 곧 서비스를 이용하실 수 있습니다.',   custom:false },
    { id:'other',     label:'직접 입력',                                           custom:true  }
];
var _DN_REJECT_REASONS = [
    { id:'not_found',  label:'입금 내역을 확인할 수 없습니다.',                            custom:false },
    { id:'mismatch',   label:'신청 정보와 실제 입금 정보가 일치하지 않아 거부되었습니다.', custom:false },
    { id:'duplicate',  label:'중복 입금 신청으로 처리되지 않습니다.',                      custom:false },
    { id:'no_confirm', label:'추가 확인이 완료되지 않아 거부 처리되었습니다.',             custom:false },
    { id:'other',      label:'직접 입력',                                                  custom:true  }
];

function _dnSetMemo(memoVal) {
    var memoEl = document.getElementById('dn-confirm-memo');
    if (memoVal && memoVal.trim() !== '') {
        memoEl.style.display = 'block';
        memoEl.querySelector('.dn-confirm-memo-text').textContent = memoVal.trim();
    } else {
        memoEl.style.display = 'none';
    }
}

function showDnConfirm(form, actionLabel, memoVal) {
    _dnConfirmForm = form; _dnShortageMode = false; _dnActionMode = '';
    document.getElementById('dn-shortage-section').style.display = 'none';
    document.getElementById('dn-reason-section').style.display = 'none';
    document.getElementById('dn-custom-msg-section').style.display = 'none';
    var modal = document.getElementById('dn-confirm-modal');
    document.getElementById('dn-confirm-title').textContent = actionLabel + ' 하시겠습니까?';
    _dnSetMemo(memoVal);
    modal.style.display = 'flex';
    return false;
}
function showApproveConfirm(form) {
    return _showActionReasonConfirm(form, 'approve', '입금승인 처리하시겠습니까?', _DN_APPROVE_REASONS, '📋 앱 전송 메시지 선택');
}
function showRejectConfirm(form) {
    return _showActionReasonConfirm(form, 'reject', '입금승인거부 처리하시겠습니까?', _DN_REJECT_REASONS, '📋 거부 사유 선택');
}
function _showActionReasonConfirm(form, mode, title, reasons, sectionLabel) {
    _dnConfirmForm = form; _dnActionMode = mode;
    _dnShortageMode = false; _dnSelectedReason = '';
    document.getElementById('dn-shortage-section').style.display = 'none';
    document.getElementById('dn-confirm-memo').style.display = 'none';
    document.getElementById('dn-custom-msg-section').style.display = 'none';
    document.getElementById('dn-custom-msg-input').value = '';
    var list = document.getElementById('dn-reason-list');
    list.innerHTML = '';
    reasons.forEach(function(r, idx) {
        var lbl = document.createElement('label');
        lbl.className = 'dn-reason-row';
        var radio = document.createElement('input');
        radio.type = 'radio'; radio.name = 'dn_action_reason'; radio.value = r.id;
        if (idx === 0) { radio.checked = true; _dnSelectedReason = r.id; }
        radio.addEventListener('change', (function(rid, rcustom) {
            return function() {
                _dnSelectedReason = rid;
                var cust = document.getElementById('dn-custom-msg-section');
                cust.style.display = rcustom ? 'block' : 'none';
                if (rcustom) { setTimeout(function(){ document.getElementById('dn-custom-msg-input').focus(); }, 60); }
            };
        })(r.id, r.custom));
        lbl.appendChild(radio);
        var sp = document.createElement('span');
        sp.innerHTML = '<strong>' + r.label + '</strong>';
        lbl.appendChild(sp);
        list.appendChild(lbl);
    });
    document.getElementById('dn-reason-label').textContent = sectionLabel;
    document.getElementById('dn-reason-section').style.display = 'block';
    document.getElementById('dn-confirm-title').textContent = title;
    document.getElementById('dn-confirm-modal').style.display = 'flex';
    return false;
}

var _DN_HOLD_REASONS = [
    { id:'shortage',      label:'입금액 부족',          desc:'신청 금액보다 적게 입금됨',                     showShortage:true  },
    { id:'name_mismatch', label:'입금자명 불일치',       desc:'신고된 입금자명과 실제 이체자명이 다름',         showShortage:false },
    { id:'no_deposit',    label:'입금 미확인',           desc:'플랫폼 계좌에서 해당 입금 내역을 찾을 수 없음',  showShortage:false },
    { id:'time_mismatch', label:'이체 정보 불일치',      desc:'신고한 이체 시간·금액과 계좌 기록이 다름',      showShortage:false },
    { id:'fx_error',      label:'환율/수수료 계산 오류', desc:'입금액이 환율 계산 결과와 맞지 않음',            showShortage:false },
    { id:'pending',       label:'확인 진행 중',          desc:'은행 지연·담당자 추가 확인 필요',               showShortage:false },
    { id:'other',         label:'기타 (메모 직접 작성)', desc:'',                                              showShortage:false }
];
function showHoldConfirm(form, memoVal, currency, expectedAmt, submittedAmt) {
    _dnConfirmForm = form; _dnShortageMode = true; _dnHoldCurrency = currency || '';
    _dnSelectedReason = '';
    // shortage input 초기화
    var inp = document.getElementById('dn-shortage-input');
    if (inp) { inp.value = ''; inp.dataset.userEdited = ''; }
    document.getElementById('dn-shortage-section').style.display = 'none';
    // 사유 라디오 동적 생성
    var list = document.getElementById('dn-reason-list');
    list.innerHTML = '';
    _DN_HOLD_REASONS.forEach(function(r, idx) {
        var lbl   = document.createElement('label');
        lbl.className = 'dn-reason-row';
        var radio = document.createElement('input');
        radio.type = 'radio'; radio.name = 'dn_hold_reason'; radio.value = r.id;
        if (idx === 0) { radio.checked = true; _dnSelectedReason = r.id; }
        radio.addEventListener('change', (function(rid, rshortage){
            return function() {
                _dnSelectedReason = rid;
                _applyHoldReasonUI(currency, expectedAmt, submittedAmt, rshortage);
            };
        })(r.id, r.showShortage));
        lbl.appendChild(radio);
        var sp = document.createElement('span');
        sp.innerHTML = '<strong>' + r.label + '</strong>' +
                       (r.desc ? '<em>' + r.desc + '</em>' : '');
        lbl.appendChild(sp);
        list.appendChild(lbl);
    });
    document.getElementById('dn-reason-section').style.display = 'block';
    document.getElementById('dn-confirm-title').textContent = '입금승인보류 처리하시겠습니까?';
    _dnSetMemo(memoVal);
    // 첫 번째 사유 적용 (입금액 부족 → shortage 표시)
    _applyHoldReasonUI(currency, expectedAmt, submittedAmt, _DN_HOLD_REASONS[0].showShortage);
    document.getElementById('dn-confirm-modal').style.display = 'flex';
    return false;
}
function _applyHoldReasonUI(currency, expectedAmt, submittedAmt, showShortage) {
    var shortage = document.getElementById('dn-shortage-section');
    var input    = document.getElementById('dn-shortage-input');
    var currLbl  = document.getElementById('dn-shortage-currency-label');
    if (showShortage) {
        shortage.style.display = 'block';
        currLbl.textContent = currency || '';
        if (!input.dataset.userEdited) {
            var def = (expectedAmt > 0 && submittedAmt > 0)
                      ? Math.max(0, Math.round((expectedAmt - submittedAmt) * 10000) / 10000) : 0;
            input.value = def > 0 ? def : '';
        }
        input.oninput = function() {
            input.dataset.userEdited = '1';
            var r = _DN_HOLD_REASONS.find(function(x){ return x.id === _dnSelectedReason; });
            _updateShortagePreview(currency, r ? r.label : null);
        };
        var rCur = _DN_HOLD_REASONS.find(function(x){ return x.id === _dnSelectedReason; });
        _updateShortagePreview(currency, rCur ? rCur.label : null);
        setTimeout(function(){ input.focus(); input.select(); }, 80);
    } else {
        shortage.style.display = 'none';
        _updateShortagePreview(currency, null);
    }
}

function _updateShortagePreview(currency, reasonLabel) {
    var input = document.getElementById('dn-shortage-input');
    var pr    = document.getElementById('dn-shortage-preview');
    if (!input || !pr) return;
    var val = parseFloat(input.value);
    if (reasonLabel && val > 0) {
        pr.textContent = '앱 메시지 포함: "[보류 사유: ' + reasonLabel + '] 추가 입금 필요: ' + val + ' ' + (currency||'') + '"';
        pr.style.color = '#e8c060';
    } else if (reasonLabel) {
        pr.textContent = '부족액 미입력 시 "추가 입금 필요" 문구 없이 보류 처리됩니다.';
        pr.style.color = '#556677';
    } else {
        pr.textContent = '';
    }
}

function dnConfirmOk() {
    document.getElementById('dn-confirm-modal').style.display = 'none';
    if (_dnConfirmForm) {
        if (_dnShortageMode) {
            var v  = parseFloat(document.getElementById('dn-shortage-input').value) || 0;
            var h  = _dnConfirmForm.querySelector('[name=shortage_amount]');
            if (h) h.value = v;
            var hr = _dnConfirmForm.querySelector('[name=hold_reason]');
            if (hr) {
                var rObj = (_DN_HOLD_REASONS || []).find(function(x){ return x.id === _dnSelectedReason; });
                hr.value = rObj ? rObj.label : (_dnSelectedReason || '');
            }
        } else if (_dnActionMode === 'approve' || _dnActionMode === 'reject') {
            var reasons = _dnActionMode === 'approve' ? _DN_APPROVE_REASONS : _DN_REJECT_REASONS;
            var rObj = reasons.find(function(x){ return x.id === _dnSelectedReason; });
            var msg = '';
            if (rObj && rObj.custom) {
                msg = (document.getElementById('dn-custom-msg-input').value || '').trim();
            } else if (rObj) {
                msg = rObj.label;
            }
            var memoField = _dnConfirmForm.querySelector('[name=adm_memo]');
            if (memoField) memoField.value = msg;
        }
        _dnConfirmForm.submit(); _dnConfirmForm = null;
    }
    _dnActionMode = ''; _dnShortageMode = false; _dnSelectedReason = '';
}
function dnConfirmCancel() {
    document.getElementById('dn-confirm-modal').style.display = 'none';
    document.getElementById('dn-shortage-section').style.display = 'none';
    document.getElementById('dn-reason-section').style.display = 'none';
    document.getElementById('dn-custom-msg-section').style.display = 'none';
    var inp = document.getElementById('dn-shortage-input');
    if (inp) inp.dataset.userEdited = '';
    _dnConfirmForm = null; _dnActionMode = ''; _dnShortageMode = false; _dnSelectedReason = '';
}

/* ── 컬럼 검색 필터 ── */
function _dnFilterTable() {
    var filters = [];
    document.querySelectorAll('.dn-sf').forEach(function(inp) {
        var v = inp.value.trim().toLowerCase();
        if (v) filters.push({ col: parseInt(inp.dataset.col), val: v });
    });
    document.querySelectorAll('.dn-table tbody tr').forEach(function(tr) {
        if (!filters.length) { tr.style.display = ''; return; }
        var ok = filters.every(function(f) {
            var c = tr.cells[f.col];
            return c && c.textContent.toLowerCase().indexOf(f.val) !== -1;
        });
        tr.style.display = ok ? '' : 'none';
    });
}
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.dn-sf').forEach(function(inp) {
        inp.addEventListener('input', _dnFilterTable);
    });
    document.querySelectorAll('#dn-hdr th[data-sort]').forEach(function(th) {
        th.addEventListener('click', function() {
            var col = parseInt(th.dataset.sort);
            var tbody = document.querySelector('.dn-table tbody');
            if (!tbody) return;
            var rows = Array.from(tbody.querySelectorAll('tr'));
            var asc = (th.dataset.sortDir !== 'asc');
            th.dataset.sortDir = asc ? 'asc' : 'desc';
            document.querySelectorAll('#dn-hdr th[data-sort]').forEach(function(t) {
                t.classList.remove('sort-asc','sort-desc');
                var ic = t.querySelector('.sort-ic'); if (ic) ic.textContent = '⇅';
            });
            th.classList.add(asc ? 'sort-asc' : 'sort-desc');
            var ic = th.querySelector('.sort-ic'); if (ic) ic.textContent = asc ? '↑' : '↓';
            rows.sort(function(a, b) {
                var ta = (a.cells[col] ? a.cells[col].textContent : '').trim().toLowerCase();
                var tb = (b.cells[col] ? b.cells[col].textContent : '').trim().toLowerCase();
                var na = parseFloat(ta.replace(/[^0-9.-]/g,'')), nb = parseFloat(tb.replace(/[^0-9.-]/g,''));
                if (!isNaN(na) && !isNaN(nb)) return asc ? na-nb : nb-na;
                return asc ? ta.localeCompare(tb,'ko') : tb.localeCompare(ta,'ko');
            });
            rows.forEach(function(r) { tbody.appendChild(r); });
        });
    });
});
</script>
<style>
#dn-confirm-modal {
    display:none; position:fixed; inset:0; z-index:99999;
    background:rgba(0,0,0,.55); align-items:center; justify-content:center;
}
.dn-confirm-box {
    background:#252526; border:1px solid #454545; border-radius:10px;
    padding:24px 28px; min-width:300px; max-width:420px; width:90%;
    box-shadow:0 8px 32px rgba(0,0,0,.7);
}
.dn-confirm-header {
    display:flex; align-items:center; gap:8px;
    color:#cccccc; font-size:13px; margin-bottom:14px;
}
.dn-confirm-header svg { flex-shrink:0; }
.dn-confirm-title { color:#cccccc; font-size:15px; margin-bottom:10px; line-height:1.5; }
.dn-confirm-memo-wrap {
    background:#252526; border:1px solid #454545; border-radius:6px;
    padding:9px 12px; margin-bottom:14px; font-size:13px; color:#3794ff;
}
.dn-confirm-memo-label { font-size:11px; color:#888888; margin-bottom:4px; }
.dn-confirm-memo-text { color:#cccccc; word-break:break-all; }
.dn-confirm-btns { display:flex; justify-content:flex-end; gap:10px; margin-top:18px; }
.dn-confirm-btns button { padding:7px 22px; border:none; border-radius:6px; font-size:14px; cursor:pointer; font-weight:bold; }
.dn-btn-ok  { background:#0e639c; color:#ffffff; }
.dn-btn-ok:hover  { background:#1177bb; }
.dn-btn-no  { background:#454545; color:#cccccc; }
.dn-btn-no:hover  { background:#3c3c3c; }
/* shortage 입력 */
.dn-shortage-section { border-top:1px solid #454545; margin-top:14px; padding-top:14px; }
.dn-shortage-label { font-size:12px; color:#3794ff; font-weight:bold; margin-bottom:4px; }
.dn-shortage-hint  { font-size:11px; color:#666666; margin-bottom:10px; line-height:1.5; }
.dn-shortage-row   { display:flex; align-items:center; gap:8px; }
.dn-shortage-row input[type=number] {
    width:130px; padding:7px 10px; font-size:15px; font-weight:bold;
    background:#252526; border:2px solid #454545; color:#cccccc;
    border-radius:6px; text-align:right;
}
.dn-shortage-row input[type=number]:focus { outline:none; border-color:#3794ff; }
.dn-shortage-currency { font-size:14px; color:#cccccc; font-weight:bold; }
.dn-shortage-preview  { font-size:11px; margin-top:8px; min-height:16px; }
/* 보류 사유 선택 */
.dn-reason-section  { border-bottom:1px solid #454545; margin-bottom:14px; padding-bottom:14px; }
.dn-reason-label    { font-size:12px; color:#3794ff; font-weight:bold; margin-bottom:8px; }
.dn-reason-list     { display:flex; flex-direction:column; gap:5px; }
.dn-reason-row      { display:flex; align-items:flex-start; gap:8px; cursor:pointer; padding:5px 8px; border-radius:5px; }
.dn-reason-row:hover { background:rgba(255,255,255,.05); }
.dn-reason-row input[type=radio] { margin-top:3px; accent-color:#0e639c; cursor:pointer; flex-shrink:0; }
.dn-reason-row span  { font-size:12.5px; color:#cccccc; line-height:1.5; }
.dn-reason-row span strong { color:#cccccc; }
.dn-reason-row span em { color:#888888; font-style:normal; font-size:11px; display:block; line-height:1.4; }
.dn-custom-msg-section { margin-top:10px; border-top:1px solid #454545; padding-top:10px; }
.dn-custom-msg-label { font-size:12px; color:#3794ff; font-weight:bold; margin-bottom:6px; }
.dn-custom-msg-input {
    width:100%; box-sizing:border-box; background:#252526; border:1px solid #454545;
    border-radius:4px; color:#cccccc; font-size:13px; padding:6px 10px;
    resize:vertical; font-family:inherit; line-height:1.5;
}
.dn-custom-msg-input:focus { outline:none; border-color:#0e639c; }
.dn-custom-msg-input::placeholder { color:#666666; }
</style>
<div id="dn-confirm-modal">
  <div class="dn-confirm-box">
    <div class="dn-confirm-header">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#cccccc" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
      vpnlink.kr
    </div>
    <div class="dn-confirm-title" id="dn-confirm-title"></div>
    <div class="dn-confirm-memo-wrap" id="dn-confirm-memo" style="display:none">
      <div class="dn-confirm-memo-label">📱 앱 전송 메시지</div>
      <div class="dn-confirm-memo-text"></div>
    </div>
    <div class="dn-reason-section" id="dn-reason-section" style="display:none">
      <div class="dn-reason-label" id="dn-reason-label">📋 보류 사유 선택</div>
      <div class="dn-reason-list" id="dn-reason-list"></div>
    </div>
    <div id="dn-custom-msg-section" style="display:none">
      <div class="dn-custom-msg-label">✏️ 앱 전송 메시지 직접 입력</div>
      <textarea id="dn-custom-msg-input" class="dn-custom-msg-input" rows="3" placeholder="앱에 전달할 메시지를 입력하세요..."></textarea>
    </div>
    <div class="dn-shortage-section" id="dn-shortage-section" style="display:none">
      <div class="dn-shortage-label">📊 추가 입금 필요액 입력</div>
      <div class="dn-shortage-hint">고객 신고 금액을 신뢰하지 않고, 플랫폼 계좌를 직접 확인한 실제 부족액을 입력하세요.<br>입력 시 앱 메시지에 자동으로 포함됩니다.</div>
      <div class="dn-shortage-row">
        <input type="number" id="dn-shortage-input" min="0" step="0.0001" placeholder="0.00">
        <span class="dn-shortage-currency" id="dn-shortage-currency-label"></span>
      </div>
      <div class="dn-shortage-preview" id="dn-shortage-preview"></div>
    </div>
    <div class="dn-confirm-btns">
      <button class="dn-btn-no"  onclick="dnConfirmCancel()">취소</button>
      <button class="dn-btn-ok"  onclick="dnConfirmOk()">확인</button>
    </div>
  </div>
</div>
<div id="mb-floating-tip"></div>

<h2><?= htmlspecialchars($g5['title']) ?> (<?= $total_cnt ?>건)</h2>


<div class="dn-manual-wrap">
  <button class="dn-manual-toggle" onclick="var b=document.getElementById('dn-manual-body');b.style.display=b.style.display==='none'?'block':'none';this.textContent=b.style.display==='none'?'📋 버튼 기능 안내 ▾':'📋 버튼 기능 안내 ▲'">📋 버튼 기능 안내 ▾</button>
  <div id="dn-manual-body" style="display:none">
    <table class="dn-manual-table">
      <thead><tr><th>버튼</th><th>역할</th><th>포인트</th><th>앱 메시지</th><th>사용 시점 예시</th></tr></thead>
      <tbody>
        <tr>
          <td><span class="mn-badge mn-approve">입금승인</span></td>
          <td>고객 입금을 확인하고 포인트를 즉시 충전</td>
          <td class="mn-point mn-plus">+충전</td>
          <td>메모 입력 시 앱 전달</td>
          <td>입금 계좌·금액·입금자명 모두 일치 확인 후</td>
        </tr>
        <tr>
          <td><span class="mn-badge mn-cancel-approve">입금승인취소</span></td>
          <td>이미 승인된 건을 되돌림. 충전 포인트 차감, 주문 취소 상태로 복원</td>
          <td class="mn-point mn-minus">−차감</td>
          <td>메모 입력 시 앱 전달 (빨간색)</td>
          <td>실수로 승인했거나 환불 처리가 필요할 때</td>
        </tr>
        <tr>
          <td><span class="mn-badge mn-hold">입금승인보류</span></td>
          <td>입금 확인이 불완전하여 추가 확인이 필요한 상태로 대기</td>
          <td class="mn-point mn-none">없음</td>
          <td>메모 내용 앱 전달 (회색)<br><small>※ 메모에 안내 사항 필수 작성 권장</small></td>
          <td>금액 부족, 입금자명 불일치, 추가 입금 요청 시</td>
        </tr>
        <tr>
          <td><span class="mn-badge mn-reject">입금승인거부</span></td>
          <td>입금 신고를 거절. 승인 불가 사유를 메모로 전달</td>
          <td class="mn-point mn-none">없음</td>
          <td>메모 내용 앱 전달 (빨간색)<br><small>※ 메모에 거부 사유 필수 작성 권장</small></td>
          <td>기한 초과, 허위 신고, 지정 계좌 외 입금 등</td>
        </tr>
      </tbody>
    </table>
    <p class="mn-note">💡 <b>관리자 메모</b>는 모든 버튼 클릭 시 앱의 "📬 담당자 응답 확인" 버튼을 통해 고객에게 전달됩니다. 보류·거부 시에는 사유를 반드시 기재해 주세요.</p>
  </div>
</div>

<div class="filter-bar">
<?php foreach ($status_labels as $k => $v): ?>
  <a href="?dn_status=<?= urlencode($k) ?>" class="<?= $status_filter === $k ? 'active' : '' ?>"><?= $v ?></a>
<?php endforeach; ?>
</div>

<div class="dn-table-wrap">
<table class="dn-table">
<thead>
<tr id="dn-hdr">
  <th data-sort="0">주문 정보 <span class="sort-ic">⇅</span></th>
  <th data-sort="1">충전신청 포인트<br><span class="th-sub">(KRW → 환산액)</span></th>
  <th>신고된 입금계좌 / 입금자정보</th>
  <th data-sort="3">이체일시<br><span class="th-sub">(당초 vs 신고)</span></th>
  <th data-sort="4">이체금액<br><span class="th-sub">(당초 vs 신고)</span></th>
  <th>주문 입금자명<br><span class="th-sub">(당초 vs 신고)</span></th>
  <th data-sort="6">비고 <span class="sort-ic">⇅</span></th>
  <th data-sort="7">상태 <span class="sort-ic">⇅</span></th>
  <th>처리 (앱 피드백)</th>
</tr>
<tr class="dn-search-row">
  <th><input class="dn-sf" data-col="0" placeholder="주문번호 · 회원"></th>
  <th></th>
  <th><input class="dn-sf" data-col="2" placeholder="계좌 · 입금자"></th>
  <th></th>
  <th></th>
  <th><input class="dn-sf" data-col="5" placeholder="입금자명"></th>
  <th><input class="dn-sf" data-col="6" placeholder="비고"></th>
  <th><input class="dn-sf" data-col="7" placeholder="상태"></th>
  <th></th>
</tr>
</thead>
<tbody>
<?php if (empty($list)): ?>
<tr><td colspan="9" style="text-align:center;padding:20px;color:#667788">내역이 없습니다.</td></tr>
<?php else: ?>
<?php foreach ($list as $r):
    $color    = $status_colors[$r['dn_status']] ?? '#888';
    $currency = !empty($r['od_fx_type']) ? strtoupper(trim($r['od_fx_type'])) : 'KRW';

    // ── 비교 계산 ──────────────────────────────────────────────────
    $name_submitted = trim($r['alt_depositor_name'] ?? '');
    $name_expected  = trim($r['od_deposit_name'] ?? '');
    $name_match     = ($name_submitted !== '' && $name_expected !== '')
                      ? (mb_strtolower($name_submitted,'UTF-8') === mb_strtolower($name_expected,'UTF-8'))
                      : null;

    $amt_submitted      = (float)($r['alt_deposit_amount'] ?? 0);
    $cart_price_for_cmp = (int)($r['od_cart_price'] ?? 0);
    $amt_expected_raw   = (float)($r['od_fx_amount'] ?? 0);
    if ($currency !== 'KRW') {
        $fx_key_cmp = 'KRW' . $currency;
        if (isset($admin_fx_rates[$fx_key_cmp])) {
            $fx_r_cmp = $admin_fx_rates[$fx_key_cmp]['rate'];
            if ($amt_expected_raw <= 0 || (int)$amt_expected_raw === $cart_price_for_cmp)
                $amt_expected_raw = round($cart_price_for_cmp * $fx_r_cmp, 2);
        }
    }
    $amt_expected = $amt_expected_raw;
    $amt_match    = ($amt_submitted > 0 && $amt_expected > 0)
                    ? (abs($amt_submitted - $amt_expected) / max($amt_expected, 0.001) < 0.005)
                    : null;

    // ── 신고된 입금계좌 / 입금자정보 ──────────────────────────────
    if ($r['used_platform_account']) {
        $accts = !empty($platform_accts[$currency]) ? $platform_accts[$currency]
               : (!empty($platform_accts['KRW']) ? $platform_accts['KRW'] : []);
        $acct_display = '<span class="cv-acct-ok"><b>플랫폼 계좌</b>'
            . (!empty($accts) ? ' (' . htmlspecialchars($currency) . ')' : '') . '</span>';
        foreach ($accts as $acct_line)
            $acct_display .= '<br><span class="cv-accent" style="font-size:11px">'
                . htmlspecialchars($acct_line) . '</span>';
        if ($name_submitted !== '') {
            $nc = ($name_match === true) ? ' <span class="cmp-ok">✓ 일치</span>'
                : (($name_match === false) ? ' <span class="cmp-ng">✗ 불일치</span>' : '');
            $acct_display .= '<br><span class="cv-rate-res" style="font-size:11px">입금자: '
                . htmlspecialchars($name_submitted) . $nc . '</span>';
        }
        if ($amt_submitted > 0) {
            $ac = ($amt_match === true) ? ' <span class="cmp-ok">✓ 일치</span>'
                : (($amt_match === false) ? ' <span class="cmp-ng">✗ 불일치</span>' : '');
            $acct_display .= '<br><span class="cv-rate-res" style="font-size:11px">입금액: '
                . fmt_amount($amt_submitted) . ' ' . htmlspecialchars($currency) . $ac . '</span>';
        }
        if (!empty($r['transfer_datetime']))
            $acct_display .= '<br><span class="cv-mb-nick" style="font-size:11px">이체일시: '
                . dn_format_dt_with_tz($r['transfer_datetime'], $r['dn_timezone'] ?? 'Asia/Seoul')
                . '</span>';
    } else {
        $acct_display = '<span class="cv-alt-acct"><b>별도계좌</b> '
            . '<span class="cmp-ng">⚠ 플랫폼 지정계좌 외 입금</span><br>'
            . '은행: ' . htmlspecialchars($r['alt_bank_name']) . '<br>'
            . '계좌: ' . htmlspecialchars($r['alt_bank_account']) . '<br>'
            . '예금주: ' . htmlspecialchars($r['alt_bank_holder']);
        if ($name_submitted !== '') {
            $nc = ($name_match === true) ? ' <span class="cmp-ok">✓</span>'
                : (($name_match === false) ? ' <span class="cmp-ng">✗</span>' : '');
            $acct_display .= '<br>입금자: ' . htmlspecialchars($name_submitted) . $nc;
        }
        if ($amt_submitted > 0) {
            $ac = ($amt_match === true) ? ' <span class="cmp-ok">✓</span>'
                : (($amt_match === false) ? ' <span class="cmp-ng">✗</span>' : '');
            $acct_display .= '<br>입금액: ' . fmt_amount($amt_submitted) . $ac;
        }
        if (!empty($r['transfer_datetime']))
            $acct_display .= '<br>이체일시: '
                . dn_format_dt_with_tz($r['transfer_datetime'], $r['dn_timezone'] ?? 'Asia/Seoul');
        $acct_display .= '</span>';
    }

    // ── 비고 ────────────────────────────────────────────────────────
    $notes_display = !empty($r['alt_notes']) ? $r['alt_notes'] : ($r['memo'] ?? '');

    // ── 회원 상태 ────────────────────────────────────────────────────
    $is_blocked  = !empty($r['mb_intercept_date']) && $r['mb_intercept_date'] > '00000000';
    $is_leaved   = !empty($r['mb_leave_date'])     && $r['mb_leave_date']     > '00000000';
    $mb_id_color = $is_blocked ? '#e05555' : ($is_leaved ? '#888888' : '#cccccc');
    $mb_dt_safe  = (substr($r['mb_datetime'] ?? '', 0, 4) > '0000')
                   ? htmlspecialchars(substr($r['mb_datetime'], 0, 16)) : '';
    $mb_login_safe = (substr($r['mb_today_login'] ?? '', 0, 4) > '0000')
                   ? htmlspecialchars(substr($r['mb_today_login'], 0, 16)) : '';
?>
<tr>
  <td class="col-oi">
    <div class="oi-top">
      <span class="oi-num"><?= $r['dn_id'] ?></span>
      <a href="orderlist4shoppoint.php?sel_field=od_id&search=<?= urlencode($r['od_id']) ?>" class="oi-od"><?= htmlspecialchars($r['od_id']) ?></a>
      <?php if (!empty($r['order_status'])): ?><span class="oi-os"><?= htmlspecialchars($r['order_status'] ?? '') ?></span><?php endif; ?>
    </div>
    <div class="mb-cell"
         onmouseenter="showMbTip(event,this)"
         onmouseleave="qHideMbTip()"
         data-mb-id="<?= htmlspecialchars($r['mb_id']) ?>"
         data-mb-name="<?= htmlspecialchars($r['mb_name'] ?? '') ?>"
         data-mb-nick="<?= htmlspecialchars($r['mb_nick'] ?? '') ?>"
         data-mb-email="<?= htmlspecialchars($r['mb_email'] ?? '') ?>"
         data-mb-hp="<?= htmlspecialchars($r['mb_hp'] ?? '') ?>"
         data-mb-dt="<?= $mb_dt_safe ?>"
         data-mb-login="<?= $mb_login_safe ?>"
         data-mb-login-cnt="<?= (int)($r['mb_login_cnt'] ?? 0) ?>"
         data-mb-ord-cnt="<?= (int)($r['mb_ord_cnt'] ?? 0) ?>"
         data-mb-ord-total="<?= number_format((int)($r['mb_ord_total'] ?? 0)) ?>"
         data-mb-point="<?= number_format((int)($r['mb_point'] ?? 0)) ?>"
         data-mb-intercept="<?= htmlspecialchars($r['mb_intercept_date'] ?? '') ?>"
         data-mb-leave="<?= htmlspecialchars($r['mb_leave_date'] ?? '') ?>"
    >
      <b style="color:<?= $mb_id_color ?>"><?= htmlspecialchars($r['mb_id']) ?></b>
      <?php if (!empty($r['mb_name']) && $r['mb_name'] !== $r['mb_id']): ?>
        <br><small class="cv-mb-name"><?= htmlspecialchars($r['mb_name']) ?></small>
      <?php endif; ?>
      <?php if (!empty($r['mb_nick']) && $r['mb_nick'] !== ($r['mb_name'] ?? '') && $r['mb_nick'] !== $r['mb_id']): ?>
        <br><small class="cv-mb-nick"><?= htmlspecialchars($r['mb_nick']) ?></small>
      <?php endif; ?>
      <?php if ($is_blocked): ?>
        <br><small class="cmp-ng" style="font-size:10px">⛔ 차단</small>
      <?php elseif ($is_leaved): ?>
        <br><small style="color:#888;font-size:10px">탈퇴</small>
      <?php endif; ?>
    </div>
    <div class="oi-dt"><?= substr($r['dn_created_at'], 0, 16) ?> <small style="color:#888;font-size:11px">(<?= dn_elapsed_str($r['dn_created_at']) ?>)</small></div>
  </td>
  <td>
    <?php
    $cart_price      = (int)($r['od_cart_price'] ?? 0);
    $charge_currency = !empty($r['od_fx_type']) ? strtoupper(trim($r['od_fx_type'])) : 'KRW';
    echo '<b class="cv-val">' . number_format($cart_price) . ' P</b>';
    if ($charge_currency === 'KRW') {
        echo '<br><small class="cv-sub">' . number_format($cart_price) . ' KRW</small>';
    }
    if ($charge_currency !== 'KRW') {
        $fx_key2 = 'KRW' . $charge_currency;
        if (isset($admin_fx_rates[$fx_key2])) {
            $r2  = $admin_fx_rates[$fx_key2]['rate'];
            $fa2 = $r['od_fx_amount'] > 0 ? (float)$r['od_fx_amount'] : round($cart_price * $r2, 2);
            if ((int)$fa2 === $cart_price) $fa2 = round($cart_price * $r2, 2);
            $rs2 = number_format($r2, 6);
            echo '<br><small class="cv-accent">× ' . $rs2 . '</small>';
            echo '<br><small class="cv-rate-res">= ' . rtrim(rtrim(number_format($fa2, 4), '0'), '.') . ' ' . htmlspecialchars($charge_currency) . '</small>';
        }
    }
    ?>
  </td>
  <td><?= $acct_display ?></td>
  <td>
    <div class="cmp-wrap">
      <?php
      if (!empty($r['od_time'])) {
          $ts  = strtotime($r['od_time']);
          if ($ts) {
              $ts_dead = $ts + 3 * 3600;
              $dead_str = date('Y-m-d H:i', $ts_dead);
              $is_over  = ($ts_dead < time());
              echo '<div class="cmp-orig">';
              echo '<span class="cmp-lbl-o">' . ($is_over ? '기한초과' : '당초 기한') . '</span>';
              echo '<span style="color:' . ($is_over ? '#e05555' : '#a0c8a0') . ';font-size:12px">' . $dead_str . '</span>';
              echo '</div>';
          }
      }
      if (!empty($r['transfer_datetime'])) {
          echo '<div class="cmp-rep">';
          echo '<span class="cmp-lbl-r">신고</span>';
          echo '<span class="cv-dt-rep">'
              . dn_format_dt_with_tz($r['transfer_datetime'], $r['dn_timezone'] ?? 'Asia/Seoul')
              . '</span>';
          echo '</div>';
      }
      ?>
    </div>
  </td>
  <td>
    <div class="cmp-wrap">
      <?php if ($amt_expected > 0): ?>
      <div class="cmp-orig">
        <span class="cmp-lbl-o">당초</span>
        <b class="cv-val"><?= fmt_amount($amt_expected) ?></b>
        <small class="cv-sub"><?= htmlspecialchars($currency) ?></small>
      </div>
      <?php endif; ?>
      <?php if ($amt_submitted > 0): ?>
      <div class="cmp-rep">
        <span class="cmp-lbl-r">신고</span>
        <?php if ($amt_match === true): ?>
          <span class="cmp-ok">✓ <?= fmt_amount($amt_submitted) ?></span>
        <?php elseif ($amt_match === false): ?>
          <span class="cmp-ng">✗ <?= fmt_amount($amt_submitted) ?></span>
        <?php else: ?>
          <span><?= fmt_amount($amt_submitted) ?></span>
        <?php endif; ?>
        <small class="cv-sub"><?= htmlspecialchars($currency) ?></small>
      </div>
      <?php elseif (!empty($r['transfer_amount']) && (int)$r['transfer_amount'] > 0): ?>
      <div class="cmp-rep">
        <span class="cmp-lbl-r">신고</span>
        <b><?= number_format((int)$r['transfer_amount']) ?></b>원
      </div>
      <?php endif; ?>
      <?php if ($amt_expected <= 0 && $amt_submitted <= 0 && (empty($r['transfer_amount']) || (int)$r['transfer_amount'] <= 0)): ?>
        <span style="color:#445566">—</span>
      <?php endif; ?>
    </div>
  </td>
  <td>
    <div class="cmp-wrap">
      <?php if ($name_expected !== ''): ?>
      <div class="cmp-orig">
        <span class="cmp-lbl-o">당초</span>
        <span style="color:<?= ($name_match === true) ? '#3db870' : (($name_match === false) ? '#e05555' : '#cccccc') ?>">
          <?= htmlspecialchars($name_expected) ?>
        </span>
        <?php if ($name_match === true): ?><span class="cmp-ok"> ✓</span><?php endif; ?>
      </div>
      <?php endif; ?>
      <?php if ($name_submitted !== ''): ?>
      <div class="cmp-rep">
        <span class="cmp-lbl-r">신고</span>
        <?php if ($name_match === true): ?>
          <span class="cmp-ok"><?= htmlspecialchars($name_submitted) ?></span>
        <?php elseif ($name_match === false): ?>
          <span class="cmp-ng"><?= htmlspecialchars($name_submitted) ?></span>
        <?php else: ?>
          <span><?= htmlspecialchars($name_submitted) ?></span>
        <?php endif; ?>
      </div>
      <?php elseif ($name_expected === ''): ?>
        <span style="color:#445566">—</span>
      <?php endif; ?>
    </div>
  </td>
  <td style="font-size:11px;color:#7a9ab0"><?= nl2br(htmlspecialchars($notes_display)) ?></td>
  <td>
    <span class="badge" style="background:<?= $color ?>22;color:<?= $color ?>;border:1px solid <?= $color ?>">
      <?= htmlspecialchars($r['dn_status']) ?></span>
    <?php if ($r['dn_processed_at']): ?>
      <br><small style="color:#556677"><?= substr($r['dn_processed_at'], 0, 16) ?><br>
      <?= htmlspecialchars($r['dn_processed_by']) ?></small>
    <?php endif; ?>
    <?php if ($r['dn_admin_memo']): ?>
      <br><small class="cv-accent">📬 <?= htmlspecialchars($r['dn_admin_memo']) ?></small>
    <?php endif; ?>
  </td>
  <td>
    <div class="adm-memo-wrap">
      <span class="adm-memo-hint">📱 아래 메시지가 앱에서 고객에게 표시됩니다</span>
      <input type="text" id="adm_memo_<?= $r['dn_id'] ?>"
             value="<?= htmlspecialchars($r['dn_admin_memo'] ?? '') ?>"
             placeholder="고객에게 전달할 메시지 (선택)">
    </div>
    <div class="btn-row">
      <?php
      $safe_chk_mb  = sql_real_escape_string($r['mb_id']);
      $safe_chk_oid = sql_real_escape_string($r['od_id'] ?? '');
      $is_approved  = false;
      if ($safe_chk_oid !== '') {
          $appr_chk    = sql_fetch("SELECT COUNT(*) AS cnt FROM g5_point
                                    WHERE mb_id='{$safe_chk_mb}'
                                    AND po_rel_table='@buyshoppoints'
                                    AND po_rel_id='{$safe_chk_mb}'
                                    AND po_rel_action='{$safe_chk_oid}'", false);
          $is_approved = (int)($appr_chk['cnt'] ?? 0) > 0;
      }
      ?>
      <?php if ($is_approved): ?>
      <form method="post" style="display:contents"
            onsubmit="var _m=document.getElementById('adm_memo_<?= $r['dn_id'] ?>').value;this.querySelector('[name=adm_memo]').value=_m;return showDnConfirm(this,'입금승인취소',_m);">
        <input type="hidden" name="dn_id" value="<?= $r['dn_id'] ?>">
        <input type="hidden" name="act" value="complete_cancel">
        <input type="hidden" name="adm_memo" value="">
        <input type="hidden" name="back_status" value="<?= htmlspecialchars($status_filter) ?>">
        <button class="btn-sm btn-approve-cancel">입금승인취소</button>
      </form>
      <?php else: ?>
      <form method="post" style="display:contents"
            onsubmit="return showApproveConfirm(this);">
        <input type="hidden" name="dn_id" value="<?= $r['dn_id'] ?>">
        <input type="hidden" name="act" value="complete">
        <input type="hidden" name="adm_memo" value="">
        <input type="hidden" name="back_status" value="<?= htmlspecialchars($status_filter) ?>">
        <button class="btn-sm btn-approve">입금승인</button>
      </form>
      <form method="post" style="display:contents"
            onsubmit="var _m=document.getElementById('adm_memo_<?= $r['dn_id'] ?>').value;this.querySelector('[name=adm_memo]').value=_m;return showHoldConfirm(this,_m,'<?= htmlspecialchars($currency) ?>',<?= (float)($amt_expected ?? 0) ?>,<?= (float)($amt_submitted ?? 0) ?>);">
        <input type="hidden" name="dn_id" value="<?= $r['dn_id'] ?>">
        <input type="hidden" name="act" value="hold">
        <input type="hidden" name="adm_memo" value="">
        <input type="hidden" name="shortage_amount" value="0">
        <input type="hidden" name="shortage_currency" value="<?= htmlspecialchars($currency) ?>">
        <input type="hidden" name="hold_reason" value="">
        <input type="hidden" name="back_status" value="<?= htmlspecialchars($status_filter) ?>">
        <button class="btn-sm btn-hold">입금승인보류</button>
      </form>
      <form method="post" style="display:contents"
            onsubmit="return showRejectConfirm(this);">
        <input type="hidden" name="dn_id" value="<?= $r['dn_id'] ?>">
        <input type="hidden" name="act" value="cancel">
        <input type="hidden" name="adm_memo" value="">
        <input type="hidden" name="back_status" value="<?= htmlspecialchars($status_filter) ?>">
        <button class="btn-sm btn-cancel">입금승인거부</button>
      </form>
      <?php endif; ?>
    </div>
  </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div><!-- /dn-table-wrap -->

<?php if ($total_pages > 1): ?>
<div style="margin-top:12px;text-align:center">
<?php for ($p = 1; $p <= $total_pages; $p++): ?>
  <a href="?dn_status=<?= urlencode($status_filter) ?>&page=<?= $p ?>"
     style="margin:0 3px;<?= $p === $page ? 'font-weight:bold;color:#fff' : 'color:#cccccc' ?>"><?= $p ?></a>
<?php endfor; ?>
</div>
<?php endif; ?>

<?php include_once(G5_ADMIN_PATH . '/admin.tail.php'); ?>
