<?php
// ========================================
// مدیریت کیف پول کاربران — پنل ادمین
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'مدیریت کیف پول | کیف‌لند';
$success = ''; $error = '';

// ========================================
// شارژ / کسر دستی توسط ادمین
// ========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['adjust_wallet'])) {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'خطای امنیتی.';
    } else {
        $target_user = (int)($_POST['user_id'] ?? 0);
        $amount      = (int)preg_replace('/[^0-9]/', '', $_POST['amount'] ?? 0);
        $action      = $_POST['action'] === 'deduct' ? 'deduct' : 'add';
        $desc        = trim($_POST['description'] ?? '');

        if ($target_user <= 0 || $amount <= 0) {
            $error = 'اطلاعات وارد شده معتبر نیست.';
        } else {
            try {
                $db->beginTransaction();

                if ($action === 'deduct') {
                    $bal = $db->prepare("SELECT wallet_balance FROM users WHERE id = ? FOR UPDATE");
                    $bal->execute([$target_user]);
                    $current = (int)$bal->fetchColumn();
                    if ($current < $amount) throw new Exception('موجودی کاربر کافی نیست (' . number_format($current) . ' تومان).');
                    $db->prepare("UPDATE users SET wallet_balance = wallet_balance - ? WHERE id = ?")->execute([$amount, $target_user]);
                    $txType = 'admin_deduct';
                } else {
                    $db->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?")->execute([$amount, $target_user]);
                    $txType = 'admin_add';
                }

                $newBal = $db->query("SELECT wallet_balance FROM users WHERE id = $target_user")->fetchColumn();
                $db->prepare("INSERT INTO wallet_transactions (user_id, type, amount, balance_after, description, status, created_at) VALUES (?, ?, ?, ?, ?, 'success', NOW())")
                   ->execute([$target_user, $txType, $amount, $newBal, $desc ?: ($action === 'add' ? 'افزایش موجودی توسط ادمین' : 'کسر موجودی توسط ادمین')]);

                $db->commit();
                Auth::logActivity('admin_wallet_' . $action, "کاربر #$target_user — " . number_format($amount) . " تومان");
                $success = ($action === 'add' ? 'افزوده' : 'کسر') . ' شد: ' . number_format($amount) . ' تومان';
            } catch (Exception $e) {
                $db->rollBack();
                $error = $e->getMessage();
            }
        }
    }
}

// ========================================
// جستجو و فیلتر
// ========================================
$search  = trim($_GET['search'] ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset  = ($page - 1) * $perPage;

$sql    = "SELECT u.id, u.full_name, u.email, u.phone, u.wallet_balance FROM users u WHERE 1=1";
$params = [];
if ($search !== '') { $sql .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)"; $p = "%$search%"; array_push($params, $p, $p, $p); }
$countStmt = $db->prepare(preg_replace('/SELECT u\.id.*FROM/', 'SELECT COUNT(*) FROM', $sql));
$countStmt->execute($params);
$totalUsers = $countStmt->fetchColumn();
$totalPages = ceil($totalUsers / $perPage);
$sql .= " ORDER BY u.wallet_balance DESC LIMIT ? OFFSET ?";
array_push($params, $perPage, $offset);
$stmt = $db->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

// آمار کلی
$stats = $db->query("SELECT SUM(wallet_balance) as total_balance, COUNT(*) as users_with_wallet FROM users WHERE wallet_balance > 0")->fetch();

// تراکنش‌های اخیر
$recentTx = $db->query("SELECT wt.*, u.full_name FROM wallet_transactions wt LEFT JOIN users u ON wt.user_id = u.id ORDER BY wt.created_at DESC LIMIT 15")->fetchAll();

$csrfToken = Auth::generateCSRFToken();
include 'includes/admin-header.php';
?>

<style>
.wallet-admin{padding:24px;}
.page-hd h1{font-size:26px;font-weight:700;margin:0 0 4px;}
.page-hd p{color:var(--text-secondary);font-size:14px;margin:0 0 24px;}
.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px;}
.stat-card{background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:16px;padding:20px;text-align:center;backdrop-filter:blur(20px);}
.stat-num{font-size:26px;font-weight:800;color:var(--primary);}
.stat-lbl{font-size:13px;color:var(--text-secondary);margin-top:4px;}
.glass-card{background:var(--glass-bg);backdrop-filter:blur(40px) saturate(180%);border:1px solid var(--glass-border);border-radius:20px;padding:24px;margin-bottom:20px;box-shadow:0 4px 16px rgba(0,0,0,0.06);}
.glass-card h3{margin:0 0 16px;font-size:17px;font-weight:700;display:flex;align-items:center;gap:8px;}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:16px;display:flex;align-items:center;gap:8px;font-size:14px;}
.alert-success{background:rgba(52,199,89,0.15);color:#0B5D0A;border:1px solid rgba(52,199,89,0.3);}
.alert-danger{background:rgba(255,59,48,0.15);color:#7A1815;border:1px solid rgba(255,59,48,0.3);}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.form-group{display:flex;flex-direction:column;gap:6px;}
.form-group label{font-size:13px;font-weight:600;color:var(--text-primary);}
.form-ctrl{padding:10px 14px;border:1px solid var(--glass-border);border-radius:10px;font-family:inherit;font-size:14px;background:var(--glass-bg);}
.form-ctrl:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px rgba(0,122,255,0.12);}
.btn{padding:10px 18px;border-radius:10px;border:none;font-weight:600;font-size:14px;cursor:pointer;transition:all 0.2s;display:inline-flex;align-items:center;gap:6px;font-family:inherit;}
.btn-primary{background:var(--primary);color:white;}
.btn-primary:hover{opacity:0.9;}
.btn-sm{padding:7px 12px;font-size:13px;}
.btn-ghost{background:transparent;border:1px solid var(--glass-border);color:var(--text-primary);}
.tw{width:100%;border-collapse:collapse;}
.tw th{text-align:right;padding:12px 14px;font-size:13px;font-weight:600;color:var(--text-secondary);border-bottom:1px solid var(--glass-border);}
.tw td{padding:14px;border-bottom:1px solid rgba(0,0,0,0.04);font-size:14px;vertical-align:middle;}
.tw tr:hover td{background:rgba(255,255,255,0.3);}
.badge-green{background:rgba(52,199,89,0.15);color:#0B5D0A;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:600;}
.badge-red{background:rgba(255,59,48,0.15);color:#7A1815;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:600;}
.badge-blue{background:rgba(0,122,255,0.15);color:#00396B;padding:3px 9px;border-radius:20px;font-size:12px;font-weight:600;}
.two-col{display:grid;grid-template-columns:1fr 1fr;gap:20px;}
.search-bar{display:flex;gap:10px;margin-bottom:16px;}
.search-bar input{flex:1;padding:10px 14px;border:1px solid var(--glass-border);border-radius:10px;font-family:inherit;font-size:14px;background:var(--glass-bg);}
.pagination{display:flex;gap:8px;margin-top:16px;flex-wrap:wrap;}
.page-link{min-width:38px;height:38px;display:flex;align-items:center;justify-content:center;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:8px;font-size:14px;color:var(--text-primary);text-decoration:none;transition:0.2s;}
.page-link:hover,.page-link.active{background:var(--primary);color:white;border-color:var(--primary);}
.modal{position:fixed;inset:0;z-index:2000;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);padding:20px;}
.modal.active{display:flex;}
.modal-dialog{background:var(--glass-bg);backdrop-filter:blur(40px);border:1px solid var(--glass-border);border-radius:20px;width:100%;max-width:480px;box-shadow:0 12px 48px rgba(0,0,0,0.15);}
.modal-header{padding:20px;border-bottom:1px solid var(--glass-border);display:flex;justify-content:space-between;align-items:center;}
.modal-title{margin:0;font-size:17px;font-weight:700;}
.modal-close{width:36px;height:36px;border-radius:50%;border:none;background:rgba(255,255,255,0.3);cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;}
.modal-body{padding:24px;}
.modal-footer{padding:16px 20px;border-top:1px solid var(--glass-border);display:flex;justify-content:flex-end;gap:10px;}
@media(max-width:768px){.stat-grid,.two-col,.form-row{grid-template-columns:1fr;}}
</style>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div style="flex:1;"></div>
    </header>

    <div class="wallet-admin">
        <div class="page-hd">
            <h1><i class="fas fa-wallet" style="color:var(--primary);margin-left:8px;"></i> مدیریت کیف پول</h1>
            <p>مشاهده، شارژ و کسر موجودی کیف پول کاربران</p>
        </div>

        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>
        <?php if ($error):   ?><div class="alert alert-danger" ><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error)   ?></div><?php endif; ?>

        <!-- آمار -->
        <div class="stat-grid">
            <div class="stat-card"><div class="stat-num"><?= number_format($stats['total_balance'] ?? 0) ?></div><div class="stat-lbl">کل موجودی (تومان)</div></div>
            <div class="stat-card"><div class="stat-num"><?= number_format($stats['users_with_wallet'] ?? 0) ?></div><div class="stat-lbl">کاربران با موجودی</div></div>
            <div class="stat-card"><div class="stat-num"><?= number_format($totalUsers) ?></div><div class="stat-lbl">کل کاربران</div></div>
        </div>

        <div class="two-col">
            <!-- لیست کاربران -->
            <div class="glass-card">
                <h3><i class="fas fa-users" style="color:var(--primary);"></i> کاربران</h3>
                <form method="GET" class="search-bar">
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="جستجو نام، ایمیل، موبایل...">
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
                </form>
                <div style="overflow-x:auto;">
                    <table class="tw">
                        <thead><tr><th>کاربر</th><th>موجودی</th><th>عملیات</th></tr></thead>
                        <tbody>
                        <?php foreach ($users as $u): ?>
                        <tr>
                            <td>
                                <div style="font-weight:600;"><?= htmlspecialchars($u['full_name']) ?></div>
                                <small style="color:var(--text-secondary);"><?= htmlspecialchars($u['email']) ?></small>
                            </td>
                            <td><strong><?= number_format($u['wallet_balance']) ?></strong> <small>ت</small></td>
                            <td>
                                <button class="btn btn-ghost btn-sm adjust-btn"
                                    data-id="<?= $u['id'] ?>"
                                    data-name="<?= htmlspecialchars($u['full_name']) ?>"
                                    data-balance="<?= number_format($u['wallet_balance']) ?>">
                                    <i class="fas fa-edit"></i> تنظیم
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php for ($i=1; $i<=$totalPages; $i++): ?>
                    <a href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>" class="page-link <?= $i==$page?'active':'' ?>"><?= $i ?></a>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- تراکنش‌های اخیر -->
            <div class="glass-card">
                <h3><i class="fas fa-history" style="color:var(--primary);"></i> تراکنش‌های اخیر</h3>
                <div style="overflow-x:auto;">
                    <table class="tw">
                        <thead><tr><th>کاربر</th><th>نوع</th><th>مبلغ</th><th>تاریخ</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentTx as $tx): ?>
                        <tr>
                            <td style="font-size:13px;"><?= htmlspecialchars($tx['full_name'] ?? '-') ?></td>
                            <td>
                                <?php $badge = match($tx['type']) {
                                    'charge','refund','admin_add' => 'badge-green',
                                    'purchase','admin_deduct' => 'badge-red',
                                    default => 'badge-blue'
                                }; ?>
                                <span class="<?= $badge ?>">
                                    <?= match($tx['type']) {
                                        'charge'=>'شارژ','purchase'=>'خرید','refund'=>'بازگشت',
                                        'admin_add'=>'شارژ ادمین','admin_deduct'=>'کسر ادمین', default=>$tx['type']
                                    } ?>
                                </span>
                            </td>
                            <td style="font-weight:600;"><?= number_format($tx['amount']) ?></td>
                            <td style="font-size:12px;color:var(--text-secondary);"><?= jdate($tx['created_at']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- مودال تنظیم موجودی -->
<div class="modal" id="adjustModal">
    <div class="modal-dialog">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <input type="hidden" name="user_id" id="modal_user_id">
            <div class="modal-header">
                <h3 class="modal-title"><i class="fas fa-wallet"></i> تنظیم کیف پول</h3>
                <button type="button" class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div style="background:var(--glass-bg);padding:14px;border-radius:12px;margin-bottom:20px;">
                    <div style="font-weight:700;" id="modal_name"></div>
                    <div style="font-size:14px;color:var(--text-secondary);margin-top:4px;">موجودی فعلی: <strong id="modal_balance"></strong> تومان</div>
                </div>
                <div class="form-row" style="margin-bottom:14px;">
                    <div class="form-group">
                        <label>عملیات</label>
                        <select name="action" class="form-ctrl">
                            <option value="add">➕ افزایش موجودی</option>
                            <option value="deduct">➖ کسر موجودی</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>مبلغ (تومان)</label>
                        <input type="text" name="amount" class="form-ctrl" placeholder="مثال: 100000" required id="modal_amount">
                    </div>
                </div>
                <div class="form-group">
                    <label>توضیح (اختیاری)</label>
                    <input type="text" name="description" class="form-ctrl" placeholder="مثال: جایزه مسابقه">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" onclick="closeModal()">انصراف</button>
                <button type="submit" name="adjust_wallet" class="btn btn-primary"><i class="fas fa-check"></i> ثبت تغییر</button>
            </div>
        </form>
    </div>
</div>

<script>
document.querySelectorAll('.adjust-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('modal_user_id').value = btn.dataset.id;
        document.getElementById('modal_name').textContent    = btn.dataset.name;
        document.getElementById('modal_balance').textContent = btn.dataset.balance;
        document.getElementById('modal_amount').value = '';
        document.getElementById('adjustModal').classList.add('active');
    });
});
function closeModal() { document.getElementById('adjustModal').classList.remove('active'); }
document.getElementById('adjustModal').addEventListener('click', e => { if (e.target === document.getElementById('adjustModal')) closeModal(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
</script>

<?php include 'includes/admin-footer.php'; ?>
