<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../admin_panel.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
$stmt->execute([$_SESSION['admin_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

$success = $error = '';

// ========== مدیریت کارت‌های بانکی ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // افزودن کارت جدید
    if (isset($_POST['add_bank_account'])) {
        $stmt = $pdo->prepare("INSERT INTO payment_accounts (bank_name, card_number, card_owner, iban, account_number, is_active, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['bank_name'],
            $_POST['card_number'],
            $_POST['card_owner'],
            $_POST['iban'] ?? null,
            $_POST['account_number'] ?? null,
            $_POST['is_active'] ?? 1,
            $_POST['sort_order'] ?? 0
        ]);
        $success = "حساب بانکی با موفقیت اضافه شد";
        header("Location: " . $_SERVER['PHP_SELF'] . "?status=" . ($_GET['status'] ?? 'pending') . "&tab=bank");
        exit;
    }
    
    // ویرایش کارت
    if (isset($_POST['edit_bank_account'])) {
        $stmt = $pdo->prepare("UPDATE payment_accounts SET bank_name=?, card_number=?, card_owner=?, iban=?, account_number=?, is_active=?, sort_order=? WHERE id=?");
        $stmt->execute([
            $_POST['bank_name'],
            $_POST['card_number'],
            $_POST['card_owner'],
            $_POST['iban'] ?? null,
            $_POST['account_number'] ?? null,
            $_POST['is_active'],
            $_POST['sort_order'],
            $_POST['account_id']
        ]);
        $success = "حساب بانکی با موفقیت ویرایش شد";
        header("Location: " . $_SERVER['PHP_SELF'] . "?status=" . ($_GET['status'] ?? 'pending') . "&tab=bank");
        exit;
    }
    
    // حذف کارت
    if (isset($_POST['delete_bank_account'])) {
        $stmt = $pdo->prepare("DELETE FROM payment_accounts WHERE id=?");
        $stmt->execute([$_POST['account_id']]);
        $success = "حساب بانکی با موفقیت حذف شد";
        header("Location: " . $_SERVER['PHP_SELF'] . "?status=" . ($_GET['status'] ?? 'pending') . "&tab=bank");
        exit;
    }
}

// ========== مدیریت درخواست‌های افزایش موجودی ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && in_array($_POST['action'], ['approve', 'reject'])) {
    $request_id = intval($_POST['request_id']);
    $action = $_POST['action'];
    $admin_note = trim($_POST['admin_note'] ?? '');
    
    $stmt = $pdo->prepare("SELECT * FROM balance_requests WHERE id = ? AND status = 'pending'");
    $stmt->execute([$request_id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($request) {
        if ($action === 'approve') {
            $pdo->beginTransaction();
            try {
                $updateAgent = $pdo->prepare("UPDATE agents SET balance = balance + ? WHERE id = ?");
                $updateAgent->execute([$request['amount'], $request['agent_id']]);
                $updateRequest = $pdo->prepare("UPDATE balance_requests SET status = 'approved', processed_at = NOW(), admin_note = ? WHERE id = ?");
                $updateRequest->execute([$admin_note, $request_id]);
                $pdo->commit();
                $success = "درخواست تایید شد. مبلغ " . number_format($request['amount']) . " تومان به حساب نماینده اضافه شد.";
                header("Location: " . $_SERVER['PHP_SELF'] . "?status=pending");
                exit;
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "خطا در انجام عملیات: " . $e->getMessage();
            }
        } elseif ($action === 'reject') {
            $updateRequest = $pdo->prepare("UPDATE balance_requests SET status = 'rejected', processed_at = NOW(), admin_note = ? WHERE id = ?");
            $updateRequest->execute([$admin_note, $request_id]);
            $success = "درخواست با موفقیت رد شد.";
            header("Location: " . $_SERVER['PHP_SELF'] . "?status=pending");
            exit;
        }
    } else {
        $error = "درخواست مورد نظر یافت نشد یا قبلاً بررسی شده است.";
    }
}

// ========== دریافت داده‌ها برای نمایش ==========
$status_filter = $_GET['status'] ?? 'pending';
$active_tab = $_GET['tab'] ?? 'requests';
$allowed_status = ['pending', 'approved', 'rejected'];
if (!in_array($status_filter, $allowed_status)) $status_filter = 'pending';

$count_pending  = $pdo->query("SELECT COUNT(*) FROM balance_requests WHERE status = 'pending'")->fetchColumn();
$count_approved = $pdo->query("SELECT COUNT(*) FROM balance_requests WHERE status = 'approved'")->fetchColumn();
$count_rejected = $pdo->query("SELECT COUNT(*) FROM balance_requests WHERE status = 'rejected'")->fetchColumn();
$total_approved_amount = $pdo->query("SELECT COALESCE(SUM(amount),0) FROM balance_requests WHERE status = 'approved'")->fetchColumn();

$stmt = $pdo->prepare("
    SELECT br.*, a.balance as current_balance 
    FROM balance_requests br
    LEFT JOIN agents a ON br.agent_id = a.id
    WHERE br.status = ?
    ORDER BY br.created_at DESC
");
$stmt->execute([$status_filter]);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

$bank_accounts = $pdo->query("SELECT * FROM payment_accounts ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت رسیدها</title>
    <link rel="stylesheet" href="../style.css">
    <style>
        :root {
            --pending: #f59e0b;
            --pending-bg: rgba(245,158,11,0.12);
            --pending-bdr: rgba(245,158,11,0.30);
            --approved: #10b981;
            --approved-bg: rgba(16,185,129,0.12);
            --approved-bdr: rgba(16,185,129,0.30);
            --rejected: #ef4444;
            --rejected-bg: rgba(239,68,68,0.12);
            --rejected-bdr: rgba(239,68,68,0.30);
            --glass-bg: rgba(255,255,255,0.75);
            --blur: blur(12px);
            --glass-border: rgba(255,255,255,0.5);
            --glass-border-mid: rgba(255,255,255,0.4);
            --glass-border-hi: rgba(255,255,255,0.7);
            --glass-inset: rgba(255,255,255,0.35);
            --glass-top-shine: rgba(255,255,255,0.6);
            --shadow-sm: 0 4px 12px rgba(0,0,0,0.05);
            --shadow-md: 0 8px 24px rgba(0,0,0,0.08);
            --r-sm: 8px;
            --r-md: 12px;
            --r-lg: 16px;
            --r-xl: 20px;
            --r-pill: 40px;
            --t-smooth: all 0.2s ease;
            --text-1: #1f2937;
            --text-2: #374151;
            --text-3: #6b7280;
        }

        * { box-sizing: border-box; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 0; }
        
        .page-wrap { max-width: 1440px; margin: 0 auto; padding: 24px; position: relative; z-index: 1; }
        .kpi-strip { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 28px; }
        .kpi-card { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-lg); padding: 18px 20px; transition: var(--t-smooth); box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-sm); }
        .kpi-card:hover { transform: translateY(-4px); border-color: var(--glass-border-hi); }
        .kpi-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-bottom: 12px; backdrop-filter: blur(4px); }
        .kpi-icon.pending { background: var(--pending-bg); border: 1px solid var(--pending-bdr); }
        .kpi-icon.approved { background: var(--approved-bg); border: 1px solid var(--approved-bdr); }
        .kpi-icon.rejected { background: var(--rejected-bg); border: 1px solid var(--rejected-bdr); }
        .kpi-icon.total { background: rgba(124,58,237,0.12); border: 1px solid rgba(124,58,237,0.28); }
        .kpi-value { font-size: 28px; font-weight: 700; color: var(--text-1); line-height: 1; }
        .kpi-label { font-size: 12px; color: var(--text-3); margin-top: 5px; font-weight: 500; }
        
        .filter-bar { display: flex; gap: 10px; margin-bottom: 20px; align-items: center; flex-wrap: wrap; }
        .filter-tab { display: inline-flex; align-items: center; gap: 8px; padding: 9px 20px; border-radius: var(--r-pill); border: 1px solid var(--glass-border); background: var(--glass-inset); backdrop-filter: var(--blur-sm); color: var(--text-2); font-size: 13px; font-weight: 500; text-decoration: none; transition: var(--t-smooth); }
        .filter-tab.pending.active { background: var(--pending-bg); border-color: var(--pending-bdr); color: #92400e; }
        .filter-tab.approved.active { background: var(--approved-bg); border-color: var(--approved-bdr); color: #065f46; }
        .filter-tab.rejected.active { background: var(--rejected-bg); border-color: var(--rejected-bdr); color: #7f1d1d; }
        .tab-count { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 22px; padding: 0 6px; border-radius: 99px; font-size: 11px; font-weight: 700; background: rgba(0,0,0,0.08); }
        
        .table-card { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); overflow: hidden; margin-bottom: 28px; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md); }
        .table-header { display: flex; align-items: center; justify-content: space-between; padding: 18px 24px; border-bottom: 1px solid rgba(255,255,255,0.4); background: rgba(255,255,255,0.15); }
        .table-title { font-size: 16px; font-weight: 700; color: var(--text-1); display: flex; align-items: center; gap: 10px; }
        .table-scroll { overflow-x: auto; }
        
        .rec-table { width: 100%; border-collapse: collapse; min-width: 900px; }
        .rec-table thead th { padding: 12px 14px; text-align: center; font-size: 11px; font-weight: 600; color: var(--text-3); background: rgba(255,255,255,0.18); border-bottom: 1px solid rgba(255,255,255,0.35); }
        .rec-table tbody td { padding: 14px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.25); font-size: 13px; color: var(--text-2); }
        .amount-cell { font-weight: 700; font-size: 14px; color: var(--text-1); }
        .receipt-thumb { width: 44px; height: 44px; border-radius: 10px; object-fit: cover; cursor: pointer; border: 1.5px solid var(--glass-border-mid); transition: var(--t-smooth); }
        .receipt-thumb:hover { transform: scale(1.05); border-color: var(--glass-border-hi); }
        
        .status-pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 12px; border-radius: var(--r-pill); font-size: 11px; font-weight: 700; }
        .status-pill.pending { background: var(--pending-bg); color: #92400e; border: 1px solid var(--pending-bdr); }
        .status-pill.approved { background: var(--approved-bg); color: #065f46; border: 1px solid var(--approved-bdr); }
        .status-pill.rejected { background: var(--rejected-bg); color: #7f1d1d; border: 1px solid var(--rejected-bdr); }
        
        .tbl-btn { display: inline-flex; align-items: center; gap: 5px; padding: 6px 13px; border-radius: var(--r-sm); font-size: 12px; font-weight: 600; border: 1px solid; cursor: pointer; transition: var(--t-smooth); background: transparent; }
        .tbl-btn-detail { background: rgba(255,255,255,0.35); border-color: var(--glass-border-mid); color: var(--text-1); }
        .tbl-btn-approve { background: var(--approved-bg); border-color: var(--approved-bdr); color: #065f46; }
        .tbl-btn-reject { background: var(--rejected-bg); border-color: var(--rejected-bdr); color: #7f1d1d; }
        .tbl-btn-edit { background: rgba(59,130,246,0.12); border-color: rgba(59,130,246,0.30); color: #1e40af; }
        .tbl-btn-delete { background: rgba(239,68,68,0.12); border-color: rgba(239,68,68,0.30); color: #7f1d1d; }
        .tbl-btn-add { background: rgba(16,185,129,0.12); border-color: rgba(16,185,129,0.30); color: #065f46; }
        
        .alert { display: flex; align-items: center; gap: 10px; padding: 14px 18px; border-radius: var(--r-md); margin-bottom: 20px; font-size: 13px; font-weight: 500; backdrop-filter: blur(8px); }
        .alert-success { background: var(--approved-bg); border: 1px solid var(--approved-bdr); color: #065f46; }
        .alert-error { background: var(--rejected-bg); border: 1px solid var(--rejected-bdr); color: #7f1d1d; }
        
        .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(80,60,160,0.22); backdrop-filter: blur(22px); z-index: 1000; justify-content: center; align-items: center; }
        .modal-overlay.active { display: flex; }
        .modal-sheet { background: rgba(255,255,255,0.95); backdrop-filter: blur(20px); border: 1px solid var(--glass-border-hi); border-radius: var(--r-xl); width: 100%; max-width: 560px; max-height: 90vh; overflow-y: auto; padding: 28px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); }
        
        .detail-group { background: rgba(255,255,255,0.25); border: 1px solid var(--glass-border); border-radius: var(--r-md); overflow: hidden; margin-bottom: 14px; }
        .detail-row { display: flex; padding: 11px 14px; border-bottom: 1px solid rgba(255,255,255,0.3); }
        .detail-row:last-child { border-bottom: none; }
        .detail-key { width: 120px; font-weight: 600; color: var(--text-3); font-size: 12px; }
        .detail-val { flex: 1; font-size: 13px; color: var(--text-1); }
        .receipt-inline { max-width: 100%; border-radius: var(--r-md); margin-top: 10px; cursor: pointer; }
        .receipt-text-box { background: rgba(255,255,255,0.25); border: 1px solid var(--glass-border); border-radius: var(--r-md); padding: 12px; font-size: 12px; white-space: pre-wrap; }
        
        .form-group { margin-bottom: 18px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 13px; color: #374151; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 12px; border-radius: 8px; border: 1px solid #e5e7eb; font-size: 13px; transition: all 0.2s; background: white; }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #8b5cf6; box-shadow: 0 0 0 3px rgba(139,92,246,0.1); }
        .form-row { display: flex; gap: 12px; }
        .form-row .form-group { flex: 1; }
        
        .bank-card-list { display: grid; gap: 10px; }
        .bank-card-item { background: rgba(255,255,255,0.5); border: 1px solid var(--glass-border); border-radius: var(--r-md); padding: 12px; display: flex; justify-content: space-between; align-items: center; }
        .bank-card-info { flex: 1; }
        .bank-card-name { font-weight: 700; font-size: 14px; color: #1e40af; }
        .bank-card-number { font-family: monospace; font-size: 13px; direction: ltr; display: inline-block; background: rgba(0,0,0,0.05); padding: 3px 8px; border-radius: 6px; margin-top: 5px; }
        .bank-card-owner { font-size: 11px; color: #666; margin-top: 3px; }
        .bank-card-actions { display: flex; gap: 8px; }
        
        .badge-active { background: #10b981; color: white; padding: 2px 8px; border-radius: 20px; font-size: 10px; font-weight: 600; }
        .badge-inactive { background: #ef4444; color: white; padding: 2px 8px; border-radius: 20px; font-size: 10px; font-weight: 600; }
        
        .admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 1px solid rgba(255,255,255,0.3); background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); border-radius: var(--r-lg); padding: 16px 24px; }
        .brand { display: flex; align-items: center; gap: 12px; }
        .brand-logo { height: 40px; }
        .brand-name { font-size: 18px; font-weight: 700; color: white; text-shadow: 0 1px 2px rgba(0,0,0,0.1); }
        .admin-info { display: flex; gap: 12px; align-items: center; }
        .admin-welcome { color: white; font-size: 13px; background: rgba(0,0,0,0.2); padding: 6px 12px; border-radius: 20px; }
        .logout-btn { padding: 8px 16px; border-radius: 8px; background: rgba(239,68,68,0.2); border: 1px solid rgba(239,68,68,0.4); color: white; text-decoration: none; font-size: 13px; transition: all 0.2s; }
        .logout-btn:hover { background: rgba(239,68,68,0.4); }
        
        .tab-buttons { display: flex; gap: 12px; margin-bottom: 24px; background: rgba(255,255,255,0.15); backdrop-filter: blur(8px); border-radius: var(--r-lg); padding: 6px; width: fit-content; }
        .tab-btn { padding: 10px 24px; border: none; background: transparent; cursor: pointer; font-size: 14px; font-weight: 600; border-radius: var(--r-md); transition: all 0.2s; color: white; }
        .tab-btn.active { background: rgba(255,255,255,0.3); color: white; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        
        @media (max-width: 1024px) { .kpi-strip { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 768px) { .page-wrap { padding: 14px; } .admin-header { flex-direction: column; text-align: center; gap: 12px; } .tab-buttons { width: 100%; justify-content: center; } }
        
        .loading-spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid rgba(0,0,0,0.1); border-top-color: #8b5cf6; border-radius: 50%; animation: spin 0.6s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        svg.icon { width: 18px; height: 18px; stroke-width: 1.8; }
    </style>
</head>
<body>
<div class="page-wrap">

    <div class="admin-header">
        <div class="brand">
            <img src="../picture/rahgozar.png" alt="لوگو" class="brand-logo">
            <span class="brand-name">مدیریت رسیدها</span>
        </div>
        <div class="admin-info">
            <span class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></span>
            <a href="../admin_panel.php" class="logout-btn">بازگشت</a>
            <a href="../admin_panel.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <!-- تب‌ها -->
    <div class="tab-buttons">
        <button class="tab-btn <?= $active_tab == 'requests' ? 'active' : '' ?>" onclick="switchTab('requests')">
            <svg class="icon" style="display: inline; margin-left: 6px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            درخواست‌ها
        </button>
        <button class="tab-btn <?= $active_tab == 'bank' ? 'active' : '' ?>" onclick="switchTab('bank')">
            <svg class="icon" style="display: inline; margin-left: 6px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="7" width="20" height="14" rx="2"/><line x1="16" y1="21" x2="16" y2="15"/><line x1="8" y1="21" x2="8" y2="15"/><line x1="12" y1="21" x2="12" y2="15"/><line x1="12" y1="3" x2="12" y2="7"/><line x1="5" y1="3" x2="19" y2="3"/></svg>
            مدیریت حساب‌های بانکی
        </button>
    </div>

    <!-- ========== بخش 1: درخواست‌ها ========== -->
    <div id="requests-tab" class="tab-content" style="display: <?= $active_tab == 'requests' ? 'block' : 'none' ?>;">
        <div class="kpi-strip">
            <div class="kpi-card">
                <div class="kpi-icon pending">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="1.8"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                </div>
                <div class="kpi-value"><?= number_format($count_pending) ?></div>
                <div class="kpi-label">در انتظار بررسی</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon approved">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="1.8"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                </div>
                <div class="kpi-value"><?= number_format($count_approved) ?></div>
                <div class="kpi-label">تایید شده</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon rejected">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="1.8"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
                </div>
                <div class="kpi-value"><?= number_format($count_rejected) ?></div>
                <div class="kpi-label">رد شده</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon total">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="1.8"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                </div>
                <div class="kpi-value"><?= number_format($total_approved_amount) ?></div>
                <div class="kpi-label">جمع تایید شده (تومان)</div>
            </div>
        </div>

        <div class="filter-bar">
            <a href="?status=pending&tab=requests" class="filter-tab pending <?= $status_filter=='pending' ? 'active' : '' ?>">
                در انتظار <span class="tab-count"><?= $count_pending ?></span>
            </a>
            <a href="?status=approved&tab=requests" class="filter-tab approved <?= $status_filter=='approved' ? 'active' : '' ?>">
                تایید شده <span class="tab-count"><?= $count_approved ?></span>
            </a>
            <a href="?status=rejected&tab=requests" class="filter-tab rejected <?= $status_filter=='rejected' ? 'active' : '' ?>">
                رد شده <span class="tab-count"><?= $count_rejected ?></span>
            </a>
        </div>

        <div class="table-card">
            <div class="table-header">
                <div class="table-title">لیست درخواست‌ها</div>
            </div>
            <div class="table-scroll">
                <table class="rec-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>نماینده</th>
                            <th>مبلغ (تومان)</th>
                            <th>بانک مقصد</th>
                            <th>رسید</th>
                            <th>تاریخ ارسال</th>
                            <th>وضعیت</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (count($requests) > 0): ?>
                        <?php foreach ($requests as $req): ?>
                        <?php
                            $bank_details = $req['selected_bank_details'] ? json_decode($req['selected_bank_details'], true) : null;
                        ?>
                        <tr>
                            <td>#<?= $req['id'] ?></td>
                            <td><?= htmlspecialchars($req['agent_name']) ?></td>
                            <td class="amount-cell"><?= number_format($req['amount']) ?> تومان</td>
                            <td><?= $bank_details ? htmlspecialchars($bank_details['bank_name'] ?? '-') : '-' ?></td>
                            <td>
                                <?php if ($req['receipt_image']): ?>
                                    <img src="../../<?= htmlspecialchars($req['receipt_image']) ?>" class="receipt-thumb" onclick="openLightbox('../../<?= htmlspecialchars($req['receipt_image']) ?>')">
                                <?php elseif ($req['receipt_text']): ?>
                                    <button class="tbl-btn tbl-btn-detail" onclick="openTextModal('<?= htmlspecialchars(addslashes($req['receipt_text'])) ?>')">متن رسید</button>
                                <?php else: ?>
                                    —
                                <?php endif; ?>
                            </td>
                            <td><?= date('Y/m/d H:i', strtotime($req['created_at'])) ?></td>
                            <td>
                                <span class="status-pill <?= $req['status'] ?>">
                                    <?= ['pending'=>'در انتظار','approved'=>'تایید شده','rejected'=>'رد شده'][$req['status']] ?>
                                </span>
                            </td>
                            <td>
                                <div style="display:flex;gap:6px;justify-content:center;">
                                    <button class="tbl-btn tbl-btn-detail" onclick='openDetailsModal(<?= json_encode($req) ?>)'>جزئیات</button>
                                    <?php if ($req['status'] === 'pending'): ?>
                                        <button class="tbl-btn tbl-btn-approve" onclick="openActionModal(<?= $req['id'] ?>, 'approve', '<?= htmlspecialchars(addslashes($req['agent_name'])) ?>', <?= $req['amount'] ?>)">تایید</button>
                                        <button class="tbl-btn tbl-btn-reject" onclick="openActionModal(<?= $req['id'] ?>, 'reject', '<?= htmlspecialchars(addslashes($req['agent_name'])) ?>', <?= $req['amount'] ?>)">رد</button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" style="text-align:center; padding:40px;">هیچ درخواستی وجود ندارد</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ========== بخش 2: مدیریت حساب‌های بانکی ========== -->
    <div id="bank-tab" class="tab-content" style="display: <?= $active_tab == 'bank' ? 'block' : 'none' ?>;">
        <div class="table-card">
            <div class="table-header">
                <div class="table-title">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="7" width="20" height="14" rx="2"/><line x1="16" y1="21" x2="16" y2="15"/><line x1="8" y1="21" x2="8" y2="15"/><line x1="12" y1="21" x2="12" y2="15"/><line x1="12" y1="3" x2="12" y2="7"/><line x1="5" y1="3" x2="19" y2="3"/></svg>
                    حساب‌های بانکی مقصد (کارت‌هایی که کاربران باید به آن واریز کنند)
                </div>
                <button class="tbl-btn tbl-btn-add" onclick="openBankModal('add')">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                    افزودن حساب جدید
                </button>
            </div>
            <div class="table-scroll">
                <table class="rec-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>نام بانک</th>
                            <th>شماره کارت</th>
                            <th>صاحب حساب</th>
                            <th>شبا / شماره حساب</th>
                            <th>وضعیت</th>
                            <th>ترتیب</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($bank_accounts) > 0): ?>
                            <?php foreach ($bank_accounts as $acc): ?>
                            <tr>
                                <td><?= $acc['id'] ?></td>
                                <td><strong><?= htmlspecialchars($acc['bank_name']) ?></strong></td>
                                <td dir="ltr"><?= htmlspecialchars($acc['card_number']) ?></td>
                                <td><?= htmlspecialchars($acc['card_owner']) ?></td>
                                <td>
                                    <?php if ($acc['iban']): ?>شبا: <?= htmlspecialchars($acc['iban']) ?><br><?php endif; ?>
                                    <?php if ($acc['account_number']): ?>شماره حساب: <?= htmlspecialchars($acc['account_number']) ?><?php endif; ?>
                                </td>
                                <td>
                                    <span class="<?= $acc['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                                        <?= $acc['is_active'] ? 'فعال' : 'غیرفعال' ?>
                                    </span>
                                </td>
                                <td><?= $acc['sort_order'] ?></td>
                                <td>
                                    <div style="display:flex;gap:6px;justify-content:center;">
                                        <button class="tbl-btn tbl-btn-edit" onclick='openBankModal("edit", <?= json_encode($acc) ?>)'>ویرایش</button>
                                        <button class="tbl-btn tbl-btn-delete" onclick='deleteBankAccount(<?= $acc['id'] ?>, "<?= htmlspecialchars($acc['bank_name']) ?>")'>حذف</button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align:center; padding:40px;">هیچ حسابی تعریف نشده است. از دکمه افزودن استفاده کنید.</div>
                            </td>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="table-card" style="background: rgba(16,185,129,0.08);">
            <div class="table-header">
                <div class="table-title">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                    راهنما
                </div>
            </div>
            <div class="table-scroll" style="padding: 20px;">
                <p style="margin: 0; color: #374151;">این حساب‌ها در صفحه درخواست افزایش موجودی (سمت کاربر) نمایش داده می‌شوند تا کاربران بدانند به کدام شماره کارت باید واریز کنند.</p>
                <ul style="margin-top: 10px; color: #6b7280; font-size: 13px;">
                    <li>شماره کارت‌ها باید ۱۶ رقمی باشد</li>
                    <li>حساب‌های فعال در صفحه کاربر نمایش داده می‌شوند</li>
                    <li>با استفاده از فیلد ترتیب می‌توانید ترتیب نمایش را مشخص کنید</li>
                </ul>
            </div>
        </div>
    </div>

</div>

<!-- فرم مخفی برای مدیریت بانک‌ها -->
<form id="bankForm" method="POST" style="display:none;">
    <input type="hidden" name="account_id" id="bank_account_id">
    <input type="hidden" name="add_bank_account" id="bank_add_action">
    <input type="hidden" name="edit_bank_account" id="bank_edit_action">
    <input type="hidden" name="delete_bank_account" id="bank_delete_action">
    <input type="hidden" name="bank_name" id="bank_name">
    <input type="hidden" name="card_number" id="bank_card_number">
    <input type="hidden" name="card_owner" id="bank_card_owner">
    <input type="hidden" name="iban" id="bank_iban">
    <input type="hidden" name="account_number" id="bank_account_number">
    <input type="hidden" name="is_active" id="bank_is_active">
    <input type="hidden" name="sort_order" id="bank_sort_order">
</form>

<script>
// ========== مدیریت تب‌ها ==========
function switchTab(tabName) {
    const url = new URL(window.location.href);
    url.searchParams.set('tab', tabName);
    if (tabName === 'requests' && !url.searchParams.has('status')) {
        url.searchParams.set('status', 'pending');
    }
    if (tabName === 'bank') {
        url.searchParams.delete('status');
    }
    window.location.href = url.toString();
}

// ========== توابع مدیریت بانک با مودال حرفه‌ای ==========
function openBankModal(action, bankData = null) {
    let modalHtml = '';
    
    if (action === 'add') {
        modalHtml = `
            <div class="modal-overlay active" id="bankModal">
                <div class="modal-sheet" onclick="event.stopPropagation()">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(0,0,0,0.1);">
                        <h3 style="font-size:18px;margin:0;">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="display:inline;margin-left:8px;"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            افزودن حساب بانکی جدید
                        </h3>
                        <button onclick="closeBankModal()" style="background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:18px;">✕</button>
                    </div>
                    <form method="POST" onsubmit="return submitBankForm('add')">
                        <div class="form-group">
                            <label>نام بانک *</label>
                            <input type="text" name="bank_name" id="modal_bank_name" placeholder="مثال: بانک ملت" required>
                        </div>
                        <div class="form-group">
                            <label>شماره کارت ۱۶ رقمی *</label>
                            <input type="text" name="card_number" id="modal_card_number" placeholder="****-****-****-****" maxlength="20" required>
                        </div>
                        <div class="form-group">
                            <label>صاحب حساب *</label>
                            <input type="text" name="card_owner" id="modal_card_owner" placeholder="نام و نام خانوادگی" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>شبا (اختیاری)</label>
                                <input type="text" name="iban" id="modal_iban" placeholder="IR...">
                            </div>
                            <div class="form-group">
                                <label>شماره حساب (اختیاری)</label>
                                <input type="text" name="account_number" id="modal_account_number" placeholder="شماره حساب">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>وضعیت</label>
                                <select name="is_active" id="modal_is_active">
                                    <option value="1">فعال</option>
                                    <option value="0">غیرفعال</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>ترتیب نمایش</label>
                                <input type="number" name="sort_order" id="modal_sort_order" value="0">
                            </div>
                        </div>
                        <div style="display:flex;gap:10px;margin-top:20px;">
                            <button type="submit" class="tbl-btn tbl-btn-approve" style="flex:1;justify-content:center;">افزودن حساب</button>
                            <button type="button" onclick="closeBankModal()" class="tbl-btn tbl-btn-detail">انصراف</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
    } else if (action === 'edit' && bankData) {
        modalHtml = `
            <div class="modal-overlay active" id="bankModal">
                <div class="modal-sheet" onclick="event.stopPropagation()">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(0,0,0,0.1);">
                        <h3 style="font-size:18px;margin:0;">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="display:inline;margin-left:8px;"><path d="M20 14.66V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5.34"/><polygon points="18 2 22 6 12 16 8 16 8 12 18 2"/></svg>
                            ویرایش حساب بانکی
                        </h3>
                        <button onclick="closeBankModal()" style="background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:18px;">✕</button>
                    </div>
                    <form method="POST" onsubmit="return submitBankForm('edit', ${bankData.id})">
                        <div class="form-group">
                            <label>نام بانک *</label>
                            <input type="text" name="bank_name" id="modal_bank_name" value="${escapeHtml(bankData.bank_name)}" required>
                        </div>
                        <div class="form-group">
                            <label>شماره کارت ۱۶ رقمی *</label>
                            <input type="text" name="card_number" id="modal_card_number" value="${escapeHtml(bankData.card_number)}" maxlength="20" required>
                        </div>
                        <div class="form-group">
                            <label>صاحب حساب *</label>
                            <input type="text" name="card_owner" id="modal_card_owner" value="${escapeHtml(bankData.card_owner)}" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>شبا (اختیاری)</label>
                                <input type="text" name="iban" id="modal_iban" value="${escapeHtml(bankData.iban || '')}">
                            </div>
                            <div class="form-group">
                                <label>شماره حساب (اختیاری)</label>
                                <input type="text" name="account_number" id="modal_account_number" value="${escapeHtml(bankData.account_number || '')}">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>وضعیت</label>
                                <select name="is_active" id="modal_is_active">
                                    <option value="1" ${bankData.is_active == 1 ? 'selected' : ''}>فعال</option>
                                    <option value="0" ${bankData.is_active == 0 ? 'selected' : ''}>غیرفعال</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>ترتیب نمایش</label>
                                <input type="number" name="sort_order" id="modal_sort_order" value="${bankData.sort_order || 0}">
                            </div>
                        </div>
                        <div style="display:flex;gap:10px;margin-top:20px;">
                            <button type="submit" class="tbl-btn tbl-btn-approve" style="flex:1;justify-content:center;">ذخیره تغییرات</button>
                            <button type="button" onclick="closeBankModal()" class="tbl-btn tbl-btn-detail">انصراف</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
    }
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
}

function closeBankModal() {
    const modal = document.getElementById('bankModal');
    if (modal) modal.remove();
}

function submitBankForm(action, accountId = null) {
    const bankName = document.getElementById('modal_bank_name').value;
    const cardNumber = document.getElementById('modal_card_number').value;
    const cardOwner = document.getElementById('modal_card_owner').value;
    const iban = document.getElementById('modal_iban')?.value || '';
    const accountNumber = document.getElementById('modal_account_number')?.value || '';
    const isActive = document.getElementById('modal_is_active').value;
    const sortOrder = document.getElementById('modal_sort_order').value;
    
    if (action === 'add') {
        document.getElementById('bank_add_action').value = '1';
        document.getElementById('bank_edit_action').value = '';
        document.getElementById('bank_delete_action').value = '';
    } else {
        document.getElementById('bank_add_action').value = '';
        document.getElementById('bank_edit_action').value = '1';
        document.getElementById('bank_delete_action').value = '';
        document.getElementById('bank_account_id').value = accountId;
    }
    
    document.getElementById('bank_name').value = bankName;
    document.getElementById('bank_card_number').value = cardNumber;
    document.getElementById('bank_card_owner').value = cardOwner;
    document.getElementById('bank_iban').value = iban;
    document.getElementById('bank_account_number').value = accountNumber;
    document.getElementById('bank_is_active').value = isActive;
    document.getElementById('bank_sort_order').value = sortOrder;
    
    document.getElementById('bankForm').submit();
    return false;
}

function deleteBankAccount(id, bankName) {
    if (confirm('آیا از حذف حساب "' + bankName + '" مطمئن هستید؟')) {
        document.getElementById('bank_add_action').value = '';
        document.getElementById('bank_edit_action').value = '';
        document.getElementById('bank_delete_action').value = '1';
        document.getElementById('bank_account_id').value = id;
        document.getElementById('bankForm').submit();
    }
}

// ========== توابع نمایش رسید ==========
function openLightbox(src) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.background = 'rgba(0,0,0,0.85)';
    modal.style.display = 'flex';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '2000';
    modal.style.backdropFilter = 'blur(10px)';
    modal.onclick = function() { this.remove(); };
    let img = document.createElement('img');
    img.src = src;
    img.style.maxWidth = '90%';
    img.style.maxHeight = '90%';
    img.style.borderRadius = '16px';
    img.style.boxShadow = '0 25px 50px -12px rgba(0,0,0,0.5)';
    modal.appendChild(img);
    document.body.appendChild(modal);
}

function openTextModal(text) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.background = 'rgba(0,0,0,0.7)';
    modal.style.display = 'flex';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '2000';
    modal.style.backdropFilter = 'blur(8px)';
    let box = document.createElement('div');
    box.style.background = 'white';
    box.style.padding = '24px';
    box.style.borderRadius = '20px';
    box.style.maxWidth = '500px';
    box.style.maxHeight = '80vh';
    box.style.overflow = 'auto';
    box.style.boxShadow = '0 25px 50px -12px rgba(0,0,0,0.25)';
    box.innerHTML = '<h3 style="margin-bottom:12px;color:#1f2937;">متن رسید</h3><p style="white-space:pre-wrap;color:#374151;line-height:1.6;">' + escapeHtml(text) + '</p><button onclick="this.closest(\'div\').parentElement.remove()" style="margin-top:16px;padding:8px 20px;background:#8b5cf6;color:white;border:none;border-radius:10px;cursor:pointer;">بستن</button>';
    modal.appendChild(box);
    modal.onclick = function(e) { if(e.target === modal) modal.remove(); };
    document.body.appendChild(modal);
}

function openDetailsModal(data) {
    let bankHtml = '';
    if (data.selected_bank_details) {
        let bank = JSON.parse(data.selected_bank_details);
        bankHtml = '<div class="detail-group"><div class="detail-row"><div class="detail-key">بانک مقصد:</div><div class="detail-val">' + escapeHtml(bank.bank_name) + '</div></div>' +
                   '<div class="detail-row"><div class="detail-key">شماره کارت:</div><div class="detail-val">' + escapeHtml(bank.card_number) + '</div></div>' +
                   '<div class="detail-row"><div class="detail-key">صاحب حساب:</div><div class="detail-val">' + escapeHtml(bank.card_owner) + '</div></div></div>';
    }
    
    let receiptHtml = '';
    if (data.receipt_image) {
        let imagePath = '../../' + data.receipt_image;
        receiptHtml = '<img src="' + escapeHtml(imagePath) + '" class="receipt-inline" onclick="openLightbox(\'' + escapeHtml(imagePath) + '\')">';
    } else if (data.receipt_text) {
        receiptHtml = '<div class="receipt-text-box">' + escapeHtml(data.receipt_text) + '</div>';
    }
    
    let statusText = {pending:'در انتظار',approved:'تایید شده',rejected:'رد شده'};
    
    let modal = document.createElement('div');
    modal.className = 'modal-overlay active';
    modal.onclick = function(e) { if(e.target === modal) modal.remove(); };
    modal.innerHTML = '<div class="modal-sheet" onclick="event.stopPropagation()">' +
        '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(0,0,0,0.1);">' +
        '<h3 style="font-size:18px;margin:0;">جزئیات درخواست</h3>' +
        '<button onclick="this.closest(\'.modal-overlay\').remove()" style="background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:18px;">✕</button>' +
        '</div>' +
        '<div class="detail-group">' +
        '<div class="detail-row"><div class="detail-key">کد پیگیری:</div><div class="detail-val"><code style="background:rgba(0,0,0,0.05);padding:4px 8px;border-radius:6px;">' + escapeHtml(data.request_tracking_code) + '</code></div></div>' +
        '<div class="detail-row"><div class="detail-key">مبلغ:</div><div class="detail-val"><strong style="color:#10b981;font-size:16px;">' + numberFormat(data.amount) + ' تومان</strong></div></div>' +
        '<div class="detail-row"><div class="detail-key">نام نماینده:</div><div class="detail-val">' + escapeHtml(data.agent_name) + '</div></div>' +
        '</div>' +
        bankHtml +
        (data.receipt_tracking_code ? '<div class="detail-group"><div class="detail-row"><div class="detail-key">شماره پیگیری:</div><div class="detail-val">' + escapeHtml(data.receipt_tracking_code) + '</div></div></div>' : '') +
        (data.receipt_deposit_time ? '<div class="detail-group"><div class="detail-row"><div class="detail-key">ساعت واریز:</div><div class="detail-val">' + escapeHtml(data.receipt_deposit_time) + '</div></div></div>' : '') +
        (data.user_note ? '<div class="detail-group"><div class="detail-row"><div class="detail-key">یادداشت کاربر:</div><div class="detail-val">' + escapeHtml(data.user_note) + '</div></div></div>' : '') +
        (data.admin_note ? '<div class="detail-group"><div class="detail-row"><div class="detail-key">یادداشت ادمین:</div><div class="detail-val">' + escapeHtml(data.admin_note) + '</div></div></div>' : '') +
        (receiptHtml ? '<div class="detail-group"><div class="detail-row"><div class="detail-key">رسید:</div><div class="detail-val">' + receiptHtml + '</div></div></div>' : '') +
        '<div class="detail-group"><div class="detail-row"><div class="detail-key">وضعیت:</div><div class="detail-val"><span class="status-pill ' + data.status + '">' + statusText[data.status] + '</span></div></div>' +
        '<div class="detail-row"><div class="detail-key">زمان ارسال:</div><div class="detail-val">' + escapeHtml(data.created_at) + '</div></div>' +
        (data.processed_at ? '<div class="detail-row"><div class="detail-key">زمان بررسی:</div><div class="detail-val">' + escapeHtml(data.processed_at) + '</div></div>' : '') +
        '</div>' +
        '</div>';
    document.body.appendChild(modal);
}

function openActionModal(id, action, name, amount) {
    let modal = document.createElement('div');
    modal.className = 'modal-overlay active';
    modal.onclick = function(e) { if(e.target === modal) modal.remove(); };
    
    let title = action === 'approve' ? 'تایید درخواست افزایش موجودی' : 'رد درخواست افزایش موجودی';
    let iconColor = action === 'approve' ? '#10b981' : '#ef4444';
    let iconPath = action === 'approve' ? '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>' : '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>';
    
    modal.innerHTML = `
        <div class="modal-sheet" onclick="event.stopPropagation()" style="max-width:480px;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:12px;border-bottom:1px solid rgba(0,0,0,0.1);">
                <h3 style="font-size:18px;margin:0;display:flex;align-items:center;gap:8px;">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="${iconColor}" stroke-width="1.8">${iconPath}</svg>
                    ${title}
                </h3>
                <button onclick="this.closest('.modal-overlay').remove()" style="background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:18px;">✕</button>
            </div>
            <div style="background:${action === 'approve' ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)'};padding:14px;border-radius:12px;margin-bottom:24px;border-right:3px solid ${iconColor};">
                <p style="margin:0;color:#374151;font-size:14px;">
                    آیا از ${action === 'approve' ? 'تایید' : 'رد'} درخواست 
                    <strong>${escapeHtml(name)}</strong> به مبلغ 
                    <strong style="color:${iconColor};">${numberFormat(amount)} تومان</strong> 
                    مطمئن هستید؟
                </p>
            </div>
            <form method="POST">
                <input type="hidden" name="request_id" value="${id}">
                <input type="hidden" name="action" value="${action}">
                <div class="form-group">
                    <label>یادداشت ادمین (اختیاری)</label>
                    <textarea name="admin_note" rows="3" placeholder="توضیحات خود را وارد کنید..." style="width:100%;padding:10px;border-radius:8px;border:1px solid #e5e7eb;font-family:inherit;"></textarea>
                </div>
                <div style="display:flex;gap:10px;margin-top:20px;">
                    <button type="submit" class="tbl-btn ${action === 'approve' ? 'tbl-btn-approve' : 'tbl-btn-reject'}" style="flex:1;justify-content:center;">${action === 'approve' ? '✓ تایید درخواست' : '✗ رد درخواست'}</button>
                    <button type="button" onclick="this.closest('.modal-overlay').remove()" class="tbl-btn tbl-btn-detail">انصراف</button>
                </div>
            </form>
        </div>
    `;
    document.body.appendChild(modal);
}

function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

function numberFormat(num) {
    return new Intl.NumberFormat('fa-IR').format(num);
}
</script>
</body>
</html>