<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
verify_csrf();
if (function_exists('mj291_payment_ensure_schema')) { mj291_payment_ensure_schema(); }
if (function_exists('mj295_wallet_ensure_schema')) { mj295_wallet_ensure_schema(); }
$adminTitle = 'Payment Center';
$adminSubtitle = 'Review invoices, payment proofs, pending user payments, receipts and payment settings from one simple screen.';

if (!function_exists('mj294_pay_status_class')) {
function mj294_pay_status_class(string $status): string {
    $s = strtolower(trim($status));
    if (in_array($s, ['approved','partial_approved','paid','completed','verified','payment_verified'], true)) { return 'success'; }
    if (in_array($s, ['pending_review','submitted','uploaded','proof_uploaded','payment_uploaded','pending'], true)) { return 'warning'; }
    if (in_array($s, ['invoice_created','unpaid','draft','awaiting_payment'], true)) { return 'secondary'; }
    if (in_array($s, ['need_more_info'], true)) { return 'info'; }
    if (in_array($s, ['rejected','failed','cancelled','payment_rejected'], true)) { return 'danger'; }
    return 'secondary';
}
}
if (!function_exists('mj294_status_badge')) {
function mj294_status_badge(string $status): string {
    $label = ucwords(str_replace(['_','-'], ' ', trim($status) ?: 'unknown'));
    return '<span class="badge badge-'.e(mj294_pay_status_class($status)).'">'.e($label).'</span>';
}
}
if (!function_exists('mj294_admin_file_href')) {
function mj294_admin_file_href(?string $path): string {
    $path = trim((string)$path);
    if ($path === '' || strtoupper($path) === 'WALLET') { return ''; }
    if (preg_match('/^https?:\/\//i', $path)) { return $path; }
    return '../'.ltrim($path, '/');
}
}
if (!function_exists('mj294_user_label')) {
function mj294_user_label(array $r): string {
    $name = trim((string)($r['user_name'] ?? $r['name'] ?? ''));
    $email = trim((string)($r['email'] ?? ''));
    if ($name === '' && $email === '') { return 'User #'.(int)($r['user_id'] ?? 0); }
    return $name !== '' ? $name : $email;
}
}
if (!function_exists('mj294_approval_preview')) {
function mj294_approval_preview(array $items): array {
    $out = [];
    foreach ($items as $it) {
        $type = (string)($it['item_type'] ?? '');
        $qty = max(1, (int)($it['quantity'] ?? 1));
        $label = trim((string)($it['item_label'] ?? 'Item'));
        if ($type === 'listing_renewal') { $out[] = 'Renew listing: '.$label; }
        elseif ($type === 'listing_sponsor') { $out[] = 'Activate sponsored listing: '.$label; }
        elseif ($type === 'listing_feature') { $out[] = 'Activate featured listing: '.$label; }
        elseif ($type === 'extra_listing_slots') { $out[] = 'Add '.$qty.' extra listing slot(s)'; }
        elseif ($type === 'extra_company_slots') { $out[] = 'Add '.$qty.' extra company slot(s)'; }
        elseif ($type === 'company_renewal') { $out[] = 'Renew company: '.$label; }
        else { $out[] = ucwords(str_replace('_',' ', $type ?: 'payment item')).': '.$label; }
    }
    return $out;
}
}


if (!function_exists('mj297_wallet_user_table')) {
function mj297_wallet_user_table(): string {
    if (function_exists('table_exists') && table_exists('mj_users')) { return 'mj_users'; }
    if (function_exists('table_exists') && table_exists('users')) { return 'users'; }
    return '';
}
}
if (!function_exists('mj297_has_col')) {
function mj297_has_col(string $table, string $col): bool {
    try { return function_exists('mj_has_col') ? mj_has_col($table, $col) : false; } catch (Throwable $e) { return false; }
}
}
if (!function_exists('mj297_user_expr')) {
function mj297_user_expr(string $table, string $alias, array $cols, string $fallbackSql, string $as): string {
    $safeAlias = preg_replace('/[^a-zA-Z0-9_]/','',$alias) ?: 'u';
    $parts = [];
    foreach ($cols as $c) {
        $safeCol = preg_replace('/[^a-zA-Z0-9_]/','',$c);
        if ($safeCol !== '' && mj297_has_col($table, $safeCol)) { $parts[] = "NULLIF({$safeAlias}.`{$safeCol}`,'')"; }
    }
    $expr = $parts ? 'COALESCE('.implode(',', $parts).', '.$fallbackSql.')' : $fallbackSql;
    $safeAs = preg_replace('/[^a-zA-Z0-9_]/','',$as) ?: 'value';
    return $expr.' AS `'.$safeAs.'`';
}
}
if (!function_exists('mj297_wallet_user_select_sql')) {
function mj297_wallet_user_select_sql(string $table=''): string {
    $table = $table ?: mj297_wallet_user_table();
    if ($table === '') { return ''; }
    $idExpr = mj297_has_col($table,'id') ? 'u.`id`' : '0';
    return $idExpr.' AS user_id, '.
        mj297_user_expr($table,'u',['name','full_name','fullname','display_name','username'],'CONCAT("User #", '.$idExpr.')','user_name').', '.
        mj297_user_expr($table,'u',['email','user_email','mail'],"''",'email').', '.
        mj297_user_expr($table,'u',['mobile','phone','contact_number','whatsapp'],"''",'mobile').', '.
        mj297_user_expr($table,'u',['preferred_currency','currency_code','currency'],"''",'preferred_currency').', '.
        (mj297_has_col($table,'country_id') ? 'u.`country_id`' : '0').' AS country_id';
}
}
if (!function_exists('mj297_wallet_user_search')) {
function mj297_wallet_user_search(string $term='', int $limit=20): array {
    $table = mj297_wallet_user_table();
    if ($table === '' || !mj297_has_col($table,'id')) { return []; }
    $select = mj297_wallet_user_select_sql($table);
    if ($select === '') { return []; }
    $limit = max(1, min(50, $limit));
    $term = trim($term);
    $candidateCols = ['name','full_name','fullname','display_name','username','user_name','email','user_email','mail','mobile','phone','contact_number','whatsapp','telephone'];
    $cols = [];
    foreach ($candidateCols as $col) { if (mj297_has_col($table,$col)) { $cols[] = $col; } }

    // Empty search: show latest users so admin can always select even when search spelling is wrong.
    if ($term === '') {
        try { return all_rows("SELECT {$select} FROM `{$table}` u ORDER BY u.`id` DESC LIMIT {$limit}"); } catch (Throwable $e) { return []; }
    }

    $where = [];
    $params = [];
    $like = '%'.mb_strtolower($term, 'UTF-8').'%';
    $compactLike = '%'.preg_replace('/\s+/', '', mb_strtolower($term, 'UTF-8')).'%';
    foreach ($cols as $col) {
        $where[] = "LOWER(TRIM(CAST(u.`{$col}` AS CHAR))) LIKE ?";
        $params[] = $like;
        $where[] = "REPLACE(LOWER(TRIM(CAST(u.`{$col}` AS CHAR))),' ','') LIKE ?";
        $params[] = $compactLike;
    }
    if (ctype_digit($term)) { $where[] = 'u.`id` = ?'; $params[] = (int)$term; }

    // Broad fallback: include any text-like column from the user table, in case a live DB uses a different name.
    try {
        $allCols = function_exists('mj_table_columns') ? array_keys(mj_table_columns($table)) : [];
        $extra = [];
        foreach ($allCols as $c) {
            if ($c === 'password_hash' || stripos($c, 'password') !== false || stripos($c, 'token') !== false) { continue; }
            if (!in_array($c, array_merge($cols, ['id']), true)) { $extra[] = $c; }
        }
        $extra = array_slice($extra, 0, 20);
        if ($extra) {
            $concatParts = [];
            foreach ($extra as $c) { $safe = preg_replace('/[^a-zA-Z0-9_]/','',$c); if ($safe !== '') { $concatParts[] = "COALESCE(CAST(u.`{$safe}` AS CHAR),'')"; } }
            if ($concatParts) { $where[] = 'LOWER(CONCAT_WS(" ",'.implode(',', $concatParts).')) LIKE ?'; $params[] = $like; }
        }
    } catch (Throwable $e) {}

    if (!$where) { return []; }
    $whereSql = ' WHERE ('.implode(' OR ', $where).')';
    $orderSql = 'u.`id` DESC';
    try { return all_rows("SELECT {$select} FROM `{$table}` u{$whereSql} ORDER BY {$orderSql} LIMIT {$limit}", $params); }
    catch (Throwable $e) {
        // Last chance simple query for standard mj_users table.
        try {
            if ($table === 'mj_users') { return all_rows("SELECT u.`id` AS user_id, COALESCE(NULLIF(u.`name`,''), CONCAT('User #',u.`id`)) AS user_name, COALESCE(u.`email`,'') AS email, COALESCE(u.`mobile`,'') AS mobile, COALESCE(u.`preferred_currency`,'') AS preferred_currency, COALESCE(u.`country_id`,0) AS country_id FROM mj_users u WHERE LOWER(u.email) LIKE ? OR LOWER(u.name) LIKE ? OR LOWER(COALESCE(u.mobile,'')) LIKE ? ORDER BY u.id DESC LIMIT {$limit}", [$like,$like,$like]); }
        } catch (Throwable $e2) {}
        return [];
    }
}
}

if (!function_exists('mj297_wallet_resolve_user')) {
function mj297_wallet_resolve_user(int $userId=0, string $term=''): ?array {
    $table = mj297_wallet_user_table();
    if ($table === '' || !mj297_has_col($table,'id')) { return null; }
    $select = mj297_wallet_user_select_sql($table);
    if ($userId > 0) {
        try { return one("SELECT {$select} FROM `{$table}` u WHERE u.`id`=? LIMIT 1", [$userId]) ?: null; } catch (Throwable $e) { return null; }
    }
    $term = trim($term);
    if ($term === '') { return null; }
    $lower = mb_strtolower($term, 'UTF-8');
    $compact = preg_replace('/\s+/', '', $lower);
    foreach (['email','user_email','mail','mobile','phone','contact_number','whatsapp','telephone'] as $col) {
        if (mj297_has_col($table,$col)) {
            try {
                $r = one("SELECT {$select} FROM `{$table}` u WHERE LOWER(TRIM(CAST(u.`{$col}` AS CHAR)))=? OR REPLACE(LOWER(TRIM(CAST(u.`{$col}` AS CHAR))),' ','')=? LIMIT 1", [$lower,$compact]);
                if ($r) { return $r; }
            } catch (Throwable $e) {}
        }
    }
    if (ctype_digit($term)) {
        try { $r = one("SELECT {$select} FROM `{$table}` u WHERE u.`id`=? LIMIT 1", [(int)$term]); if ($r) { return $r; } } catch (Throwable $e) {}
    }
    $rows = mj297_wallet_user_search($term, 5);
    if (count($rows) === 1) { return $rows[0]; }
    return null;
}
}

if (!function_exists('mj297_wallet_admin_rows')) {
function mj297_wallet_admin_rows(string $qterm=''): array {
    $table = mj297_wallet_user_table();
    if ($table === '') { return []; }
    $select = mj297_wallet_user_select_sql($table);
    if ($select === '') { return []; }
    $where = [];
    $params = [];
    $qterm = trim($qterm);
    if ($qterm !== '') {
        $like='%'.mb_strtolower($qterm, 'UTF-8').'%';
        foreach (['name','full_name','fullname','display_name','username','user_name','email','user_email','mail','mobile','phone','contact_number','whatsapp','telephone'] as $col) {
            if (mj297_has_col($table,$col)) { $where[]="LOWER(TRIM(CAST(u.`{$col}` AS CHAR))) LIKE ?"; $params[]=$like; }
        }
        if (ctype_digit($qterm)) { $where[]='u.`id`=?'; $params[]=(int)$qterm; }
    }
    $whereSql = $where ? ' WHERE ('.implode(' OR ', $where).')' : '';
    try {
        if (function_exists('table_exists') && table_exists('mj_wallets')) {
            $walletId = mj297_has_col('mj_wallets','id') ? 'w.`id`' : '0';
            $walletCurrency = mj297_has_col('mj_wallets','currency_code') ? "w.`currency_code`" : "NULL";
            $walletBalance = mj297_has_col('mj_wallets','balance') ? 'w.`balance`' : '0';
            $walletHeld = mj297_has_col('mj_wallets','held_amount') ? 'w.`held_amount`' : '0';
            $walletStatus = mj297_has_col('mj_wallets','status') ? "w.`status`" : "'active'";
            return all_rows("SELECT x.*, COALESCE({$walletId},0) wallet_id, COALESCE({$walletCurrency}, NULLIF(x.preferred_currency,''), 'SGD') currency_code, COALESCE({$walletBalance},0) balance, COALESCE({$walletHeld},0) held_amount, COALESCE({$walletStatus},'active') status FROM (SELECT {$select} FROM `{$table}` u{$whereSql} ORDER BY u.`id` DESC LIMIT 200) x LEFT JOIN mj_wallets w ON w.user_id=x.user_id ORDER BY CASE WHEN COALESCE({$walletId},0)>0 THEN 0 ELSE 1 END, x.user_id DESC", $params);
        }
        return all_rows("SELECT x.*, 0 wallet_id, COALESCE(NULLIF(x.preferred_currency,''), 'SGD') currency_code, 0 balance, 0 held_amount, 'not_created' status FROM (SELECT {$select} FROM `{$table}` u{$whereSql} ORDER BY u.`id` DESC LIMIT 200) x", $params);
    } catch (Throwable $e) {
        // If wallet join fails due older schema, still show users so admin can select and add credit.
        try { return all_rows("SELECT x.*, 0 wallet_id, COALESCE(NULLIF(x.preferred_currency,''), 'SGD') currency_code, 0 balance, 0 held_amount, 'not_created' status FROM (SELECT {$select} FROM `{$table}` u{$whereSql} ORDER BY u.`id` DESC LIMIT 200) x", $params); } catch (Throwable $e2) { return []; }
    }
}
}

if (!function_exists('qmark')) {
function qmark(string $v): string { return function_exists('db') ? db()->quote($v) : "'".str_replace("'","''",$v)."'"; }
}

function mj294_legacy_rows(string $statusFilter=''): array {
    $rows = [];
    $pending = ['submitted','uploaded','pending','pending_review','proof_uploaded','payment_uploaded'];
    try {
        if (table_exists('mj_upgrade_payment_proofs')) {
            $where = '1=1'; $params = [];
            if ($statusFilter !== '') { $where .= ' AND p.status=?'; $params[] = $statusFilter; }
            else { $where .= " AND p.status IN ('submitted','uploaded','pending','pending_review','proof_uploaded','payment_uploaded','need_more_info','rejected','verified','approved','paid','payment_verified')"; }
            foreach (all_rows("SELECT p.*, u.name user_name, u.email FROM mj_upgrade_payment_proofs p LEFT JOIN mj_users u ON u.id=p.user_id WHERE {$where} ORDER BY p.id DESC LIMIT 80", $params) as $p) {
                $rows[] = ['source'=>'upgrade','id'=>(int)$p['id'],'user_id'=>(int)$p['user_id'],'user'=>mj294_user_label($p),'email'=>(string)($p['email']??''),'title'=>'Upgrade payment proof','subtitle'=>ucwords(str_replace('_',' ', (string)($p['request_type']??''))).' request #'.(int)($p['request_id']??0),'amount'=>(float)($p['amount']??0),'currency'=>(string)($p['currency_code']??'SGD'),'status'=>(string)($p['status']??''),'proof'=>(string)($p['proof_path']??''),'method'=>(string)($p['payment_method']??''),'reference'=>(string)($p['reference_no']??''),'created'=>(string)($p['created_at']??''),'raw'=>$p];
            }
        }
    } catch (Throwable $e) {}
    try {
        if (table_exists('mj_payment_proofs')) {
            $where = '1=1'; $params = [];
            if ($statusFilter !== '') { $where .= ' AND p.status=?'; $params[] = $statusFilter; }
            else { $where .= " AND p.status IN ('submitted','uploaded','pending','pending_review','proof_uploaded','payment_uploaded','need_more_info','rejected','verified','approved','paid')"; }
            foreach (all_rows("SELECT p.*, u.name user_name, u.email FROM mj_payment_proofs p LEFT JOIN mj_users u ON u.id=p.user_id WHERE {$where} ORDER BY p.id DESC LIMIT 80", $params) as $p) {
                $rows[] = ['source'=>'generic','id'=>(int)$p['id'],'user_id'=>(int)($p['user_id']??0),'user'=>mj294_user_label($p),'email'=>(string)($p['email']??''),'title'=>'General payment proof','subtitle'=>ucwords(str_replace('_',' ', (string)($p['related_type']??''))).' #'.(int)($p['related_id']??0),'amount'=>(float)($p['amount']??0),'currency'=>(string)($p['currency']??'SGD'),'status'=>(string)($p['status']??''),'proof'=>(string)($p['proof_file']??''),'method'=>(string)($p['payment_method']??''),'reference'=>'','created'=>(string)($p['uploaded_at']??''),'raw'=>$p];
            }
        }
    } catch (Throwable $e) {}
    // v2.9.15: customer-to-seller order payment proofs are intentionally hidden from Payment Center.
    // Payment Center reviews user-to-admin payments only.
    usort($rows, function($a,$b){ return strcmp((string)($b['created']??''), (string)($a['created']??'')); });
    return array_slice($rows, 0, 120);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));
    $source = trim((string)($_POST['source'] ?? ''));
    $id = (int)($_POST['id'] ?? $_POST['proof_id'] ?? 0);
    $note = trim((string)($_POST['admin_note'] ?? $_POST['note'] ?? ''));
    try {
        if ($action === 'wallet_adjust') {
            if (!function_exists('mj295_wallet_adjust')) { throw new Exception('Wallet helper is not loaded.'); }
            $walletUserId = (int)($_POST['wallet_user_id'] ?? 0);
            $walletSearchTerm = trim((string)($_POST['wallet_user_search_term'] ?? ''));
            if ($walletUserId <= 0 && $walletSearchTerm !== '' && function_exists('mj297_wallet_resolve_user')) {
                $resolvedUser = mj297_wallet_resolve_user(0, $walletSearchTerm);
                if ($resolvedUser) { $walletUserId = (int)($resolvedUser['user_id'] ?? 0); }
            }
            $direction = ((string)($_POST['wallet_direction'] ?? 'credit')) === 'debit' ? 'debit' : 'credit';
            $amount = (float)($_POST['wallet_amount'] ?? 0);
            $currency = trim((string)($_POST['wallet_currency'] ?? setting('wallet_default_currency','SGD')));
            if ($walletUserId <= 0) { throw new Exception('Please search and select a user before saving. If only one exact email/mobile/ID matches, it will auto-select.'); }
            $walletTargetUser = function_exists('mj297_wallet_resolve_user') ? mj297_wallet_resolve_user($walletUserId, '') : null;
            if (!$walletTargetUser) { throw new Exception('Selected user was not found. Please search and select again.'); }
            if (function_exists('admin_can_manage_user') && !admin_can_manage_user($admin, $walletTargetUser)) { throw new Exception('You do not have permission to adjust this user wallet.'); }
            mj295_wallet_adjust($walletUserId, $amount, $direction, (int)$admin['id'], $note, $currency);
            flash('success', ($direction === 'debit' ? 'Wallet amount deducted for ' : 'Wallet credit added for ').mj294_user_label($walletTargetUser).'.');
            redirect('payment-center.php?tab=wallet&q='.urlencode((string)($walletTargetUser['email'] ?? $walletTargetUser['user_name'] ?? $walletUserId)));
        }
        if ($source === 'batch') {
            if (!function_exists('mj291_review_batch')) { throw new Exception('Bulk payment helper is not loaded.'); }
            if ($action === 'approve_selected') {
                $itemIds = isset($_POST['item_ids']) && is_array($_POST['item_ids']) ? array_map('intval', $_POST['item_ids']) : [];
                if (!$itemIds) { throw new Exception('Please select item(s) to approve.'); }
                mj291_review_batch($id, 'approve_selected', (int)$admin['id'], $note, $itemIds);
                flash('success', 'Selected payment item(s) approved and activated.');
            } elseif (in_array($action, ['approve_all','verify','mark_paid'], true)) {
                mj291_review_batch($id, 'approve_all', (int)$admin['id'], $note);
                flash('success', 'Payment approved and services activated.');
            } elseif ($action === 'need_more_info') {
                mj291_review_batch($id, 'need_more_info', (int)$admin['id'], $note);
                flash('success', 'User will be asked to provide more payment information.');
            } elseif ($action === 'reject') {
                mj291_review_batch($id, 'reject', (int)$admin['id'], $note);
                flash('success', 'Payment rejected.');
            }
        } elseif ($source === 'upgrade') {
            $proof = one('SELECT * FROM mj_upgrade_payment_proofs WHERE id=? LIMIT 1', [$id]);
            if (!$proof) { throw new Exception('Upgrade proof not found.'); }
            if (in_array($action, ['approve_all','verify','mark_paid'], true)) {
                q('UPDATE mj_upgrade_payment_proofs SET status="verified", admin_note=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?', [$note, (int)$admin['id'], $id]);
                if (($proof['request_type'] ?? '') === 'renewal' && table_exists('mj_listing_renewal_requests')) { q('UPDATE mj_listing_renewal_requests SET payment_status="payment_verified" WHERE id=?', [(int)$proof['request_id']]); }
                if (($proof['request_type'] ?? '') === 'listing_upgrade' && table_exists('mj_listing_upgrade_requests')) { q('UPDATE mj_listing_upgrade_requests SET payment_status="payment_verified" WHERE id=?', [(int)$proof['request_id']]); }
                if (($proof['request_type'] ?? '') === 'limit_upgrade' && table_exists('mj_user_limit_upgrade_requests')) { q('UPDATE mj_user_limit_upgrade_requests SET payment_status="payment_verified" WHERE id=?', [(int)$proof['request_id']]); }
                if (function_exists('mj263_notify')) { mj263_notify((int)$proof['user_id'], null, 'upgrade_payment_verified', 'Payment proof verified', 'Your upgrade payment proof was verified by admin.', 'billing-payments.php?tab=proofs', 'normal', true); }
                flash('success', 'Legacy upgrade payment proof verified.');
            } elseif ($action === 'need_more_info') {
                q('UPDATE mj_upgrade_payment_proofs SET status="need_more_info", admin_note=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?', [$note, (int)$admin['id'], $id]);
                flash('success', 'Payment proof marked as need more info.');
            } elseif ($action === 'reject') {
                q('UPDATE mj_upgrade_payment_proofs SET status="rejected", admin_note=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?', [$note, (int)$admin['id'], $id]);
                flash('success', 'Payment proof rejected.');
            }
        } elseif ($source === 'generic') {
            if (in_array($action, ['approve_all','verify','mark_paid'], true)) { q('UPDATE mj_payment_proofs SET status="verified", admin_id=?, admin_note=?, reviewed_at=NOW() WHERE id=?', [(int)$admin['id'], $note, $id]); flash('success', 'Payment proof verified.'); }
            elseif ($action === 'need_more_info') { q('UPDATE mj_payment_proofs SET status="need_more_info", admin_id=?, admin_note=?, reviewed_at=NOW() WHERE id=?', [(int)$admin['id'], $note, $id]); flash('success', 'Payment proof marked as need more info.'); }
            elseif ($action === 'reject') { q('UPDATE mj_payment_proofs SET status="rejected", admin_id=?, admin_note=?, reviewed_at=NOW() WHERE id=?', [(int)$admin['id'], $note, $id]); flash('success', 'Payment proof rejected.'); }
        } elseif ($source === 'order') {
            throw new Exception('Customer-to-seller order payment approval is disabled. Payment Center only handles user-to-admin payments.');
        }
    } catch (Throwable $e) { flash('error', $e->getMessage()); }
    redirect('payment-center.php?tab='.urlencode((string)($_POST['return_tab'] ?? 'review')));
}

$tab = trim((string)($_GET['tab'] ?? 'review'));
$allowedTabs = ['review','waiting','invoices','history','wallet','credits','settings'];
if (!in_array($tab, $allowedTabs, true)) { $tab = 'review'; }
$finance = function_exists('mj293_finance_metrics') ? mj293_finance_metrics() : [];
$reviewBatches = [];
$waitingBatches = [];
$invoiceRows = [];
$historyBatches = [];
$walletRows = [];
$walletTxRows = [];
$walletUserSearch = trim((string)($_GET['user_q'] ?? ''));
$walletSelectedUserId = (int)($_GET['wallet_user_id'] ?? 0);
$walletUserResults = [];
$walletUserSearchFallbackLatest = false;
$walletSelectedUser = null;
try {
    // v2.9.11: lazy-load only the selected tab records. Summary cards stay aggregated, but large lists are not loaded on every tab.
    if (table_exists('mj_payment_batches')) {
        if ($tab === 'review') {
            $reviewBatches = all_rows("SELECT b.*, u.name user_name, u.email, i.invoice_no FROM mj_payment_batches b LEFT JOIN mj_users u ON u.id=b.user_id LEFT JOIN mj_invoices i ON i.id=b.invoice_id WHERE b.status IN ('pending_review','submitted','uploaded','payment_uploaded','proof_uploaded','need_more_info') ORDER BY CASE WHEN b.status='pending_review' THEN 0 WHEN b.status='need_more_info' THEN 1 ELSE 2 END, b.updated_at DESC, b.id DESC LIMIT 100");
        } elseif ($tab === 'waiting') {
            $waitingBatches = all_rows("SELECT b.*, u.name user_name, u.email, i.invoice_no FROM mj_payment_batches b LEFT JOIN mj_users u ON u.id=b.user_id LEFT JOIN mj_invoices i ON i.id=b.invoice_id WHERE b.status IN ('invoice_created','unpaid','draft') ORDER BY b.id DESC LIMIT 100");
        } elseif ($tab === 'history') {
            $historyBatches = all_rows("SELECT b.*, u.name user_name, u.email, i.invoice_no FROM mj_payment_batches b LEFT JOIN mj_users u ON u.id=b.user_id LEFT JOIN mj_invoices i ON i.id=b.invoice_id WHERE b.status IN ('approved','partial_approved','paid','completed','payment_verified','rejected','failed','cancelled','payment_rejected') ORDER BY COALESCE(b.reviewed_at,b.updated_at,b.created_at) DESC, b.id DESC LIMIT 120");
        }
    }
    if ($tab === 'invoices' && table_exists('mj_invoices')) {
        $invoiceRows = all_rows("SELECT i.*, u.name user_name, u.email, b.batch_no, b.status batch_status FROM mj_invoices i LEFT JOIN mj_users u ON u.id=i.user_id LEFT JOIN mj_payment_batches b ON b.id=i.batch_id ORDER BY i.id DESC LIMIT 150");
    }
    if ($tab === 'wallet') {
        $walletRows = function_exists('mj297_wallet_admin_rows') ? mj297_wallet_admin_rows(trim((string)($_GET['q'] ?? ''))) : (function_exists('mj295_wallet_admin_rows') ? mj295_wallet_admin_rows(trim((string)($_GET['q'] ?? ''))) : []);
        if (table_exists('mj_wallet_transactions')) {
            $userTable = function_exists('mj297_wallet_user_table') ? mj297_wallet_user_table() : (table_exists('mj_users') ? 'mj_users' : '');
            if ($userTable !== '' && function_exists('mj297_wallet_user_select_sql')) {
                $txSelect = mj297_wallet_user_select_sql($userTable);
                $walletTxRows = all_rows("SELECT t.*, usr.user_name, usr.email FROM mj_wallet_transactions t LEFT JOIN (SELECT {$txSelect} FROM `{$userTable}` u) usr ON usr.user_id=t.user_id ORDER BY t.id DESC LIMIT 80");
            } else {
                $walletTxRows = all_rows('SELECT * FROM mj_wallet_transactions ORDER BY id DESC LIMIT 80');
            }
        }
        if (function_exists('mj297_wallet_resolve_user') && $walletSelectedUserId > 0) {
            $walletSelectedUser = mj297_wallet_resolve_user($walletSelectedUserId, '');
        }
        if (function_exists('mj297_wallet_user_search')) {
            $walletUserResults = mj297_wallet_user_search($walletUserSearch, 20);
            if ($walletUserSearch !== '' && !$walletUserResults) {
                // v2.9.8: do not leave admin stuck. Show latest users so admin can still select.
                $walletUserResults = mj297_wallet_user_search('', 20);
                $walletUserSearchFallbackLatest = true;
            }
            if (!$walletSelectedUser && $walletUserSearch !== '') {
                $walletSelectedUser = mj297_wallet_resolve_user(0, $walletUserSearch);
                if ($walletSelectedUser) { $walletSelectedUserId = (int)($walletSelectedUser['user_id'] ?? 0); }
            }
        }
    }
} catch (Throwable $e) {}
$legacyRows = [];
if (in_array($tab, ['review','history'], true)) {
    $legacyRows = mj294_legacy_rows('');
    if ($tab === 'review') {
        $legacyRows = array_values(array_filter($legacyRows, function($r){ return in_array(strtolower((string)$r['status']), ['submitted','uploaded','pending','pending_review','proof_uploaded','payment_uploaded','need_more_info'], true); }));
    }
    if ($tab === 'history') {
        $legacyRows = array_values(array_filter($legacyRows, function($r){ return in_array(strtolower((string)$r['status']), ['verified','approved','paid','completed','rejected','failed','cancelled','payment_verified','payment_rejected'], true); }));
    }
}
include __DIR__.'/_header.php';
?>
<style>
.mj-payment-hero{background:linear-gradient(135deg,#f8fbff,#eef5ff);border:1px solid #dfe9ff;border-radius:18px;padding:18px 20px;margin-bottom:18px;}
.mj-payment-tabs{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px}.mj-payment-tabs a{border:1px solid #dbe6f6;border-radius:999px;padding:10px 15px;font-weight:700;color:#23364f;background:#fff}.mj-payment-tabs a.active{background:linear-gradient(135deg,#2563eb,#7c3aed);color:#fff;border-color:transparent;box-shadow:0 10px 25px rgba(37,99,235,.22)}
.mj-pay-card{border:1px solid #dce6f4;border-radius:18px;box-shadow:0 14px 35px rgba(15,23,42,.06);overflow:hidden;margin-bottom:16px;background:#fff}.mj-pay-card .mj-pay-head{display:flex;justify-content:space-between;gap:16px;padding:16px 18px;border-bottom:1px solid #eef2f7;background:#fbfdff}.mj-pay-title{font-weight:800;font-size:18px;color:#142033}.mj-pay-meta{color:#64748b;font-size:13px}.mj-pay-body{padding:16px 18px}.mj-pay-actions{background:#f8fafc;border-top:1px solid #eef2f7;padding:14px 18px}.mj-proof-box{border:1px dashed #b8c8e6;border-radius:14px;padding:12px;background:#f8fbff}.mj-approval-preview{background:#ecfeff;border:1px solid #bae6fd;border-radius:12px;padding:10px 12px}.mj-amount{font-size:22px;font-weight:900;color:#111827}.mj-mini-stat{background:#fff;border:1px solid #dce6f4;border-radius:16px;padding:14px;box-shadow:0 10px 25px rgba(15,23,42,.04)}.mj-mini-stat b{font-size:22px}.mj-action-stack .btn{margin-right:6px;margin-bottom:6px}.mj-table-card{border:1px solid #e5edf7;border-radius:16px;overflow:hidden;background:#fff}.mj-table-card table{margin-bottom:0}.mj-wallet-admin-box{border:1px solid #dce6f4;border-radius:18px;background:#fff;box-shadow:0 14px 35px rgba(15,23,42,.06);padding:16px}.mj-wallet-balance{font-size:24px;font-weight:900;color:#111827}.mj-wallet-hold{font-size:13px;color:#64748b}@media(max-width:991px){.mj-pay-card .mj-pay-head{display:block}.mj-amount{font-size:18px}.mj-payment-tabs a{flex:1;text-align:center}.mj-action-stack .btn{width:100%;}}
.mj-wallet-selected{border:1px solid #bfdbfe;background:#eff6ff;border-radius:14px;padding:10px 12px;margin-bottom:10px;color:#1e3a8a}.mj-wallet-selected b{color:#0f172a}.mj-wallet-user-results{max-height:265px;overflow:auto;border:1px solid #e5edf7;border-radius:14px;background:#fff;margin-bottom:12px}.mj-wallet-user-item{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:10px 12px;border-bottom:1px solid #eef2f7}.mj-wallet-user-item:last-child{border-bottom:0}.mj-wallet-user-item:hover{background:#f8fbff}.mj-wallet-user-name{font-weight:800;color:#0f172a}.mj-wallet-user-meta{font-size:12px;color:#64748b}.mj-wallet-user-search{background:#f8fbff;border:1px solid #e5edf7;border-radius:14px;padding:12px;margin-bottom:12px}.mj-wallet-pick{white-space:nowrap}.mj-wallet-help{font-size:12px;color:#64748b;margin-top:-4px;margin-bottom:8px}.mj-wallet-table-actions{min-width:110px}@media(max-width:991px){.mj-wallet-user-item{display:block}.mj-wallet-user-item .btn{width:100%;margin-top:8px}}
</style>
<div class="mj-payment-hero">
  <div class="d-flex flex-wrap align-items-center justify-content-between">
    <div><h3 class="mb-1"><i class="fas fa-credit-card text-primary mr-2"></i>One Payment Center</h3><div class="text-muted">Admin can verify, approve, reject, view invoices and check payment totals without jumping between many pages.</div></div>
    <div class="mt-2 mt-md-0"><a href="upgrade-payment-settings.php" class="btn btn-outline-primary"><i class="fas fa-cog mr-1"></i>Payment Settings</a></div>
  </div>
</div>
<div class="row">
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Awaiting User Payment</span><br><b><?=money((float)($finance['awaiting_user_payment_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['awaiting_user_payment_count']??0))?> invoice(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Pending Admin Review</span><br><b><?=money((float)($finance['pending_review_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['pending_review_count']??0))?> proof(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Paid / Approved</span><br><b><?=money((float)($finance['paid_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['paid_count']??0))?> record(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Open Amount</span><br><b><?=money((float)($finance['open_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['open_count']??0))?> open item(s)</div></div></div>
</div>
<div class="row">
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Receipt Amount</span><br><b><?=money((float)($finance['receipt_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['receipt_count']??0))?> receipt(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Invoice Paid Amount</span><br><b><?=money((float)($finance['invoice_paid_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['invoice_paid_count']??0))?> paid invoice(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Wallet Payment Debit</span><br><b><?=money((float)($finance['wallet_payment_debit_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['wallet_payment_debit_count']??0))?> wallet payment(s)</div></div></div>
  <div class="col-lg-3 col-6 mb-3"><div class="mj-mini-stat"><span class="text-muted">Wallet Top-up Credit</span><br><b><?=money((float)($finance['wallet_topup_credit_amount']??0),'SGD')?></b><div class="text-muted small"><?=e((int)($finance['wallet_topup_credit_count']??0))?> approved top-up(s)</div></div></div>
</div>
<div class="mj-payment-tabs">
  <a class="<?= $tab==='review'?'active':'' ?>" href="payment-center.php?tab=review"><i class="fas fa-check-circle mr-1"></i>Review & Approve</a>
  <a class="<?= $tab==='waiting'?'active':'' ?>" href="payment-center.php?tab=waiting"><i class="fas fa-file-invoice mr-1"></i>Waiting User Payment</a>
  <a class="<?= $tab==='invoices'?'active':'' ?>" href="payment-center.php?tab=invoices"><i class="fas fa-receipt mr-1"></i>Invoices / Receipts</a>
  <a class="<?= $tab==='history'?'active':'' ?>" href="payment-center.php?tab=history"><i class="fas fa-history mr-1"></i>Payment History</a>
  <a class="<?= $tab==='wallet'?'active':'' ?>" href="payment-center.php?tab=wallet"><i class="fas fa-wallet mr-1"></i>Wallet / Credits</a>
  <a class="<?= $tab==='credits'?'active':'' ?>" href="payment-center.php?tab=credits"><i class="fas fa-gift mr-1"></i>Credit Packages</a>
  <a class="<?= $tab==='settings'?'active':'' ?>" href="payment-center.php?tab=settings"><i class="fas fa-sliders-h mr-1"></i>Setup Links</a>
</div>
<?php show_flash(); ?>

<?php if ($tab === 'review'): ?>
  <div class="alert alert-primary"><b>Simple workflow:</b> Review proof → approve all or selected items → system activates the service and creates receipt. Reject or request more info if proof is unclear.</div>
  <?php foreach ($reviewBatches as $b): $items = function_exists('mj291_batch_items') ? mj291_batch_items((int)$b['id']) : []; $proofHref = mj294_admin_file_href((string)($b['proof_path'] ?? '')); ?>
    <div class="mj-pay-card">
      <div class="mj-pay-head">
        <div><div class="mj-pay-title"><?=e($b['invoice_no'] ?: $b['batch_no'] ?: ('Payment #'.$b['id']))?></div><div class="mj-pay-meta"><b><?=e(mj294_user_label($b))?></b> · <?=e($b['email']??'')?> · <?=e($b['created_at']??'')?></div></div>
        <div class="text-right"><div class="mj-amount"><?=money((float)($b['total_amount']??0),(string)($b['currency_code']??'SGD'))?></div><?=mj294_status_badge((string)($b['status']??''))?></div>
      </div>
      <div class="mj-pay-body">
        <div class="row">
          <div class="col-lg-7">
            <h6 class="font-weight-bold">Invoice items</h6>
            <form method="post" class="mj-payment-action-form">
              <?=csrf_input()?><input type="hidden" name="source" value="batch"><input type="hidden" name="id" value="<?=e($b['id'])?>"><input type="hidden" name="return_tab" value="review">
              <div class="table-responsive mb-3"><table class="table table-sm table-bordered"><thead><tr><th style="width:38px"><input type="checkbox" onclick="this.closest('table').querySelectorAll('.batch-item-check').forEach(c=>c.checked=this.checked)" checked></th><th>Item</th><th>Qty</th><th class="text-right">Total</th></tr></thead><tbody>
                <?php foreach($items as $it): ?><tr><td><input class="batch-item-check" type="checkbox" name="item_ids[]" value="<?=e($it['id'])?>" checked></td><td><b><?=e($it['item_label'] ?: ucwords(str_replace('_',' ', $it['item_type'])))?></b><br><small><?=e($it['item_description'] ?? '')?></small></td><td><?=e($it['quantity']??1)?></td><td class="text-right"><b><?=money((float)($it['total_amount']??0),(string)($it['currency_code']??'SGD'))?></b></td></tr><?php endforeach; ?>
                <?php if(!$items): ?><tr><td colspan="4" class="text-muted text-center">No item breakdown found.</td></tr><?php endif; ?>
              </tbody></table></div>
              <div class="mj-approval-preview mb-3"><b>Approval preview:</b><ul class="mb-0 mt-1"><?php foreach(mj294_approval_preview($items) as $p): ?><li><?=e($p)?></li><?php endforeach; ?><?php if(!$items): ?><li>Mark payment as approved.</li><?php endif; ?></ul></div>
              <label>Admin note</label><textarea class="form-control mb-3" name="admin_note" rows="2" placeholder="Optional note / reject reason / message to user"></textarea>
              <div class="mj-action-stack"><button class="btn btn-success" name="action" value="approve_all"><i class="fas fa-check mr-1"></i>Approve All & Activate</button><button class="btn btn-outline-success" name="action" value="approve_selected"><i class="fas fa-check-double mr-1"></i>Approve Selected</button><button class="btn btn-info" name="action" value="need_more_info"><i class="fas fa-info-circle mr-1"></i>Need More Info</button><button class="btn btn-danger" name="action" value="reject" onclick="return confirm('Reject this payment?')"><i class="fas fa-times mr-1"></i>Reject</button></div>
            </form>
          </div>
          <div class="col-lg-5">
            <div class="mj-proof-box"><h6 class="font-weight-bold">Payment proof</h6><div>Method: <b><?=e($b['payment_method'] ?: '-')?></b></div><div>Reference: <b><?=e($b['reference_no'] ?: '-')?></b></div><?php if($proofHref): ?><a class="btn btn-primary btn-sm mt-2" href="<?=e($proofHref)?>" target="_blank"><i class="fas fa-image mr-1"></i>View Proof</a><?php elseif(strtolower((string)($b['payment_method']??''))==='wallet'): ?><div class="alert alert-success mt-2 mb-0 py-2"><i class="fas fa-wallet mr-1"></i>Wallet payment. No proof file needed. New full-wallet payments auto-approve and deduct immediately.</div><?php else: ?><div class="text-muted mt-2">No proof uploaded yet.</div><?php endif; ?><div class="small text-muted mt-2"><?=e($b['note'] ?? '')?></div></div>
          </div>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
  <?php foreach ($legacyRows as $r): $proofHref = mj294_admin_file_href($r['proof']); ?>
    <div class="mj-pay-card">
      <div class="mj-pay-head"><div><div class="mj-pay-title"><?=e($r['title'])?> #<?=e($r['id'])?></div><div class="mj-pay-meta"><b><?=e($r['user'])?></b> · <?=e($r['email'])?> · <?=e($r['subtitle'])?> · <?=e($r['created'])?></div></div><div class="text-right"><div class="mj-amount"><?=money((float)$r['amount'],$r['currency'])?></div><?=mj294_status_badge($r['status'])?></div></div>
      <div class="mj-pay-body"><div class="row"><div class="col-lg-7"><p class="mb-1">Method: <b><?=e($r['method'] ?: '-')?></b></p><p>Reference: <b><?=e($r['reference'] ?: '-')?></b></p></div><div class="col-lg-5 text-lg-right"><?php if($proofHref): ?><a class="btn btn-primary" target="_blank" href="<?=e($proofHref)?>">View Proof</a><?php endif; ?></div></div></div>
      <div class="mj-pay-actions"><form method="post" class="form-inline"><input type="hidden" name="source" value="<?=e($r['source'])?>"><input type="hidden" name="id" value="<?=e($r['id'])?>"><input type="hidden" name="return_tab" value="review"><?=csrf_input()?><input class="form-control mr-2 mb-2" style="min-width:260px" name="admin_note" placeholder="Admin note / reason"><button class="btn btn-success mr-2 mb-2" name="action" value="approve_all">Approve</button><button class="btn btn-info mr-2 mb-2" name="action" value="need_more_info">Need More Info</button><button class="btn btn-danger mb-2" name="action" value="reject">Reject</button></form></div>
    </div>
  <?php endforeach; ?>
  <?php if(!$reviewBatches && !$legacyRows): ?><div class="card"><div class="card-body text-center text-muted p-5"><i class="fas fa-check-circle fa-3x mb-3 text-success"></i><h4>No payment proofs waiting review</h4><p>User-to-admin payment proofs appear here for approval. Customer-to-seller payment proofs are disabled.</p></div></div><?php endif; ?>
<?php elseif ($tab === 'waiting'): ?>
  <div class="alert alert-secondary"><b>Waiting user payment:</b> Invoice generated, but user has not uploaded proof yet. No admin action needed.</div>
  <div class="mj-table-card"><div class="table-responsive"><table class="table table-hover"><thead><tr><th>Invoice</th><th>User</th><th>Amount</th><th>Status</th><th>Created</th></tr></thead><tbody><?php foreach($waitingBatches as $b): ?><tr><td><b><?=e($b['invoice_no'] ?: $b['batch_no'] ?: ('#'.$b['id']))?></b></td><td><?=e(mj294_user_label($b))?><br><small><?=e($b['email']??'')?></small></td><td><b><?=money((float)($b['total_amount']??0),(string)($b['currency_code']??'SGD'))?></b></td><td><?=mj294_status_badge((string)($b['status']??''))?></td><td><?=e($b['created_at']??'')?></td></tr><?php endforeach; ?><?php if(!$waitingBatches): ?><tr><td colspan="5" class="text-center text-muted p-5">No invoice waiting for user payment.</td></tr><?php endif; ?></tbody></table></div></div>
<?php elseif ($tab === 'invoices'): ?>
  <div class="mj-table-card"><div class="table-responsive"><table class="table table-striped table-hover"><thead><tr><th>Invoice</th><th>User</th><th>Batch</th><th>Total</th><th>Status</th><th>Proof</th><th>Date</th><th>Action</th></tr></thead><tbody><?php foreach($invoiceRows as $i): $proof=mj294_admin_file_href((string)($i['proof_path']??'')); ?><tr><td><b><?=e($i['invoice_no'] ?: ('INV-'.$i['id']))?></b></td><td><?=e(mj294_user_label($i))?><br><small><?=e($i['email']??'')?></small></td><td><?=e($i['batch_no'] ?: '-')?></td><td><b><?=money((float)($i['total_amount']??0),(string)($i['currency_code']??'SGD'))?></b></td><td><?=mj294_status_badge((string)($i['status']??''))?></td><td><?php if($proof): ?><a target="_blank" class="btn btn-xs btn-outline-primary" href="<?=e($proof)?>">View</a><?php else: ?>-<?php endif; ?></td><td><small><?=e($i['created_at']??'')?></small></td><td><a class="btn btn-xs btn-outline-secondary mb-1" target="_blank" href="../invoice-print.php?invoice_id=<?=e((int)$i['id'])?>">Print</a><?php if($proof && in_array(strtolower((string)($i['status']??'')), ['pending_review','submitted','uploaded','payment_uploaded','proof_uploaded'], true)): ?> <a class="btn btn-xs btn-primary mb-1" href="payment-center.php?tab=review">Review</a><?php endif; ?></td></tr><?php endforeach; ?><?php if(!$invoiceRows): ?><tr><td colspan="8" class="text-center text-muted p-5">No invoices found.</td></tr><?php endif; ?></tbody></table></div></div>
<?php elseif ($tab === 'history'): ?>
  <div class="mj-table-card"><div class="table-responsive"><table class="table table-hover"><thead><tr><th>Payment</th><th>User</th><th>Amount</th><th>Status</th><th>Proof</th><th>Reviewed</th></tr></thead><tbody><?php foreach($historyBatches as $b): $proof=mj294_admin_file_href((string)($b['proof_path']??'')); ?><tr><td><b><?=e($b['invoice_no'] ?: $b['batch_no'] ?: ('#'.$b['id']))?></b></td><td><?=e(mj294_user_label($b))?><br><small><?=e($b['email']??'')?></small></td><td><b><?=money((float)($b['total_amount']??0),(string)($b['currency_code']??'SGD'))?></b></td><td><?=mj294_status_badge((string)($b['status']??''))?></td><td><?php if($proof): ?><a target="_blank" href="<?=e($proof)?>" class="btn btn-xs btn-outline-primary">View</a><?php else: ?>-<?php endif; ?></td><td><?=e($b['reviewed_at'] ?: $b['updated_at'] ?: '')?></td></tr><?php endforeach; ?><?php foreach($legacyRows as $r): $proof=mj294_admin_file_href($r['proof']); ?><tr><td><b><?=e($r['title'])?> #<?=e($r['id'])?></b><br><small><?=e($r['subtitle'])?></small></td><td><?=e($r['user'])?><br><small><?=e($r['email'])?></small></td><td><b><?=money((float)$r['amount'],$r['currency'])?></b></td><td><?=mj294_status_badge($r['status'])?></td><td><?php if($proof): ?><a target="_blank" href="<?=e($proof)?>" class="btn btn-xs btn-outline-primary">View</a><?php else: ?>-<?php endif; ?></td><td><?=e($r['created'])?></td></tr><?php endforeach; ?><?php if(!$historyBatches && !$legacyRows): ?><tr><td colspan="6" class="text-center text-muted p-5">No payment history found.</td></tr><?php endif; ?></tbody></table></div></div>
<?php elseif ($tab === 'wallet'): ?>
  <div class="alert alert-info"><b>Wallet / Credits:</b> Add credit, deduct credit, view held balances and audit every wallet movement from one place. User wallet top-ups still need admin approval, but full wallet invoice payments auto-approve and deduct immediately.</div>
  <div class="row">
    <div class="col-lg-4 mb-3">
      <div class="mj-wallet-admin-box">
        <h5 class="font-weight-bold mb-3"><i class="fas fa-plus-circle text-success mr-1"></i> Adjust User Wallet</h5>
        <form class="mj-wallet-user-search" method="get">
          <input type="hidden" name="tab" value="wallet">
          <label class="mb-1">Search user to add / deduct</label>
          <div class="input-group"><input class="form-control" name="user_q" value="<?=e($walletUserSearch)?>" placeholder="Name, email, mobile or user ID"><div class="input-group-append"><button class="btn btn-outline-primary" type="submit"><i class="fas fa-search mr-1"></i>Search</button></div></div>
          <div class="mj-wallet-help">Search first, then click <b>Select</b>. No need to remember user ID.</div>
        </form>
        <?php if($walletUserResults): ?>
          <?php if(!empty($walletUserSearchFallbackLatest)): ?><div class="alert alert-warning border py-2 small mb-2"><b>No exact match found.</b><br>Showing latest users below. Click <b>Select</b> on the correct user, or try email/mobile/User ID again.</div><?php endif; ?>
          <div class="mj-wallet-user-results">
            <?php foreach($walletUserResults as $su): $suLabel=mj294_user_label($su); $suCurrency=trim((string)($su['preferred_currency']??'')) ?: (setting('wallet_default_currency','SGD') ?: 'SGD'); ?>
              <div class="mj-wallet-user-item">
                <div><div class="mj-wallet-user-name"><?=e($suLabel)?></div><div class="mj-wallet-user-meta"><?=e($su['email']??'')?> <?=!empty($su['mobile'])?' · '.e($su['mobile']):''?> · ID <?=e($su['user_id']??'')?></div></div>
                <button type="button" class="btn btn-sm btn-primary mj-wallet-pick" data-user-id="<?=e($su['user_id']??'')?>" data-user-label="<?=e($suLabel)?>" data-user-email="<?=e($su['email']??'')?>" data-user-mobile="<?=e($su['mobile']??'')?>" data-currency="<?=e($suCurrency)?>"><i class="fas fa-check mr-1"></i>Select</button>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <?php if($walletUserSearch !== ''): ?>
            <div class="alert alert-warning border py-2 small mb-2"><b>No matching user found.</b><br>Try full email, mobile number, user ID, or part of the user name. You can also use the user list on the right and click <b>Adjust</b>.</div>
          <?php else: ?>
            <div class="alert alert-light border py-2 small text-muted">Search user by name, email, mobile or ID to adjust wallet. Latest users will appear after search.</div>
          <?php endif; ?>
        <?php endif; ?>
        <?php $selectedCurrency = trim((string)($walletSelectedUser['preferred_currency'] ?? '')) ?: (setting('wallet_default_currency','SGD') ?: 'SGD'); ?>
        <form method="post" id="walletAdjustForm">
          <?=csrf_input()?><input type="hidden" name="action" value="wallet_adjust"><input type="hidden" name="return_tab" value="wallet">
          <input type="hidden" name="wallet_user_id" id="wallet_user_id" value="<?=e($walletSelectedUserId ?: ($walletSelectedUser['user_id'] ?? ''))?>"><input type="hidden" name="wallet_user_search_term" id="wallet_user_search_term" value="<?=e($walletUserSearch)?>">
          <label>Selected user</label>
          <div class="mj-wallet-selected" id="walletSelectedBox"><?php if($walletSelectedUser): ?><b><?=e(mj294_user_label($walletSelectedUser))?></b><br><small><?=e($walletSelectedUser['email']??'')?> <?=!empty($walletSelectedUser['mobile'])?' · '.e($walletSelectedUser['mobile']):''?> · ID <?=e($walletSelectedUser['user_id']??'')?></small><?php else: ?><span class="text-muted">No user selected yet. Search and select user above.</span><?php endif; ?></div>
          <label>Action</label><select class="form-control mb-2" name="wallet_direction"><option value="credit">Add Credit</option><option value="debit">Deduct Credit</option></select>
          <label>Amount</label><input class="form-control mb-2" type="number" step="0.01" min="0.01" name="wallet_amount" required>
          <label>Currency</label><input class="form-control mb-2" name="wallet_currency" id="wallet_currency" value="<?=e($selectedCurrency)?>" maxlength="10">
          <label>Admin note</label><textarea class="form-control mb-3" name="admin_note" rows="3" placeholder="Reason / reference / internal note" required></textarea>
          <button class="btn btn-primary btn-block"><i class="fas fa-save mr-1"></i>Save Wallet Adjustment</button>
        </form>
      </div>
    </div>
    <div class="col-lg-8 mb-3">
      <div class="mj-wallet-admin-box">
        <div class="d-flex justify-content-between flex-wrap align-items-center mb-3"><h5 class="font-weight-bold mb-0"><i class="fas fa-wallet mr-1"></i>User Wallets</h5><form class="form-inline" method="get"><input type="hidden" name="tab" value="wallet"><input class="form-control form-control-sm mr-2" name="q" placeholder="Search name/email" value="<?=e($_GET['q'] ?? '')?>"><button class="btn btn-sm btn-outline-primary">Search</button></form></div>
        <div class="table-responsive"><table class="table table-hover"><thead><tr><th>User</th><th>Currency</th><th class="text-right">Balance</th><th class="text-right">Held</th><th class="text-right">Available</th><th>Status</th><th class="mj-wallet-table-actions">Action</th></tr></thead><tbody><?php foreach($walletRows as $w): $bal=(float)($w['balance']??0); $held=(float)($w['held_amount']??0); $wLabel=mj294_user_label($w); ?><tr><td><b><?=e($wLabel)?></b><br><small><?=e($w['email']??'')?> · ID <?=e($w['user_id']??'')?></small></td><td><?=e($w['currency_code']??'SGD')?></td><td class="text-right font-weight-bold"><?=money($bal,(string)($w['currency_code']??'SGD'))?></td><td class="text-right text-warning"><?=money($held,(string)($w['currency_code']??'SGD'))?></td><td class="text-right text-success font-weight-bold"><?=money(max(0,$bal-$held),(string)($w['currency_code']??'SGD'))?></td><td><?=mj294_status_badge((string)($w['status']??'active'))?></td><td><button type="button" class="btn btn-xs btn-outline-primary mj-wallet-pick" data-user-id="<?=e($w['user_id']??'')?>" data-user-label="<?=e($wLabel)?>" data-user-email="<?=e($w['email']??'')?>" data-currency="<?=e($w['currency_code']??'SGD')?>"><i class="fas fa-plus mr-1"></i>Adjust</button></td></tr><?php endforeach; ?><?php if(!$walletRows): ?><tr><td colspan="7" class="text-center text-muted p-4">No wallet records yet. A wallet is created when user opens Billing or admin adds credit.</td></tr><?php endif; ?></tbody></table></div>
      </div>
    </div>
  </div>
  <div class="mj-table-card"><div class="p-3 border-bottom"><h5 class="font-weight-bold mb-0">Latest Wallet Ledger</h5></div><div class="table-responsive"><table class="table table-hover"><thead><tr><th>Date</th><th>User</th><th>Type</th><th>Description</th><th class="text-right">Amount</th></tr></thead><tbody><?php foreach($walletTxRows as $tx): $dir=(string)($tx['direction']??''); ?><tr><td><small><?=e($tx['created_at']??'')?></small></td><td><b><?=e(mj294_user_label($tx))?></b><br><small><?=e($tx['email']??'')?></small></td><td><?=e(ucwords(str_replace('_',' ',(string)($tx['transaction_type']??''))))?></td><td><?=e($tx['description']??'')?></td><td class="text-right font-weight-bold <?= $dir==='debit'?'text-danger':'text-success' ?>"><?=($dir==='debit'?'-':'+')?><?=money((float)($tx['amount']??0),(string)($tx['currency_code']??'SGD'))?></td></tr><?php endforeach; ?><?php if(!$walletTxRows): ?><tr><td colspan="5" class="text-center text-muted p-4">No wallet transactions yet.</td></tr><?php endif; ?></tbody></table></div></div>
<?php elseif ($tab === 'credits'): ?>
  <div class="row">
    <div class="col-lg-4"><div class="card card-primary card-outline"><div class="card-body"><h5>Credit Package Setup</h5><p class="text-muted">Create top-up packages like SGD 20, SGD 50 or bonus credits. This screen is ready for package management.</p><a class="btn btn-primary" href="upgrade-payment-settings.php">Open Pricing Settings</a></div></div></div>
    <div class="col-lg-4"><div class="card card-success card-outline"><div class="card-body"><h5>Wallet Payment Rules</h5><p class="text-muted">Control wallet top-up, low balance alerts and wallet currency. Full wallet invoice payments are auto-approved when balance is enough.</p><a class="btn btn-success" href="payment-center.php?tab=settings">Open Payment Settings</a></div></div></div>
    <div class="col-lg-4"><div class="card card-info card-outline"><div class="card-body"><h5>Future Auto Top-up</h5><p class="text-muted">Users can generate wallet top-up invoices and upload proof. Admin approval adds the credit.</p><a class="btn btn-info" href="payment-center.php?tab=wallet">Manage Wallets</a></div></div></div>
  </div>
<?php else: ?>
  <div class="row">
    <div class="col-lg-4"><div class="card card-primary card-outline"><div class="card-body"><h5>Payment Methods & Pricing</h5><p class="text-muted">Control bank, PayNow/QR, PayPal, featured/sponsored/renew/slot pricing.</p><a class="btn btn-primary" href="upgrade-payment-settings.php">Open Settings</a></div></div></div>
    <div class="col-lg-4"><div class="card card-success card-outline"><div class="card-body"><h5>Finance Dashboard</h5><p class="text-muted">View revenue, pending amount, paid amount and open finance totals.</p><a class="btn btn-success" href="finance-dashboard.php">Open Finance</a></div></div></div>
    <div class="col-lg-4"><div class="card card-info card-outline"><div class="card-body"><h5>Invoice Settings</h5><p class="text-muted">Manage invoice numbering, tax/GST and receipt settings.</p><a class="btn btn-info" href="invoice-settings.php">Open Invoice Settings</a></div></div></div>
    <div class="col-lg-4"><div class="card card-warning card-outline"><div class="card-body"><h5>Wallet / Credits</h5><p class="text-muted">Add wallet credits, deduct balance, view holds and audit wallet payments.</p><a class="btn btn-warning" href="payment-center.php?tab=wallet">Open Wallet</a></div></div></div>
  </div>
<?php endif; ?>

<script>
(function(){
  function pickWalletUser(btn){
    var id = btn.getAttribute('data-user-id') || '';
    var label = btn.getAttribute('data-user-label') || ('User #' + id);
    var email = btn.getAttribute('data-user-email') || '';
    var mobile = btn.getAttribute('data-user-mobile') || '';
    var currency = btn.getAttribute('data-currency') || '<?=e(setting('wallet_default_currency','SGD') ?: 'SGD')?>';
    var idInput = document.getElementById('wallet_user_id');
    var curInput = document.getElementById('wallet_currency');
    var termInput = document.getElementById('wallet_user_search_term');
    var box = document.getElementById('walletSelectedBox');
    if (idInput) idInput.value = id;
    if (curInput && currency) curInput.value = currency;
    if (termInput) termInput.value = email || label || id;
    if (box) {
      box.innerHTML = '<b>' + label.replace(/[&<>]/g, function(c){return {"&":"&amp;","<":"&lt;",">":"&gt;"}[c];}) + '</b><br><small>' + (email || '') + (mobile ? ' · ' + mobile : '') + ' · ID ' + id + '</small>';
    }
    var form = document.getElementById('walletAdjustForm');
    if (form && form.scrollIntoView) form.scrollIntoView({behavior:'smooth', block:'center'});
  }
  document.addEventListener('click', function(e){
    var btn = e.target.closest ? e.target.closest('.mj-wallet-pick') : null;
    if (!btn) return;
    e.preventDefault();
    pickWalletUser(btn);
  });
  var form = document.getElementById('walletAdjustForm');
  if (form) {
    form.addEventListener('submit', function(e){
      var idInput = document.getElementById('wallet_user_id');
      if (!idInput || !idInput.value || parseInt(idInput.value,10) <= 0) {
        e.preventDefault();
        alert('Please search and select a user before saving wallet adjustment.');
      }
    });
  }
})();
</script>

<?php include __DIR__.'/_footer.php'; ?>
