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

date_default_timezone_set('Asia/Tehran');

if (!isset($_SESSION['agent_id'])) {
    header("Location: ../agent.php");
    exit;
}

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

if (!$agent) {
    session_destroy();
    header("Location: ../agent.php");
    exit;
}

$success = $error = '';
$upload_error = '';

$bank_accounts = $pdo->query("SELECT * FROM payment_accounts WHERE is_active = 1 ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$current_datetime = date('Y/m/d H:i:s');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_request'])) {
    $amount_toman = floatval($_POST['amount']);
    $selected_bank_id = intval($_POST['selected_bank']);
    $receipt_tracking_code = trim($_POST['receipt_tracking_code']);
    $user_note = trim($_POST['user_note']);
    $receipt_text = trim($_POST['receipt_text']);
    $receipt_type = $_POST['receipt_type'] ?? 'image';
    
    $receipt_deposit_time = trim($_POST['receipt_deposit_time']);
    if (empty($receipt_deposit_time)) {
        $receipt_deposit_time = date('Y/m/d H:i:s');
    }
    
    if ($amount_toman <= 0) {
        $error = "مبلغ وارد شده معتبر نیست.";
    } elseif ($amount_toman < 1000) {
        $error = "حداقل مبلغ برای درخواست افزایش موجودی 1,000 تومان است.";
    } elseif (empty($selected_bank_id) || $selected_bank_id == 0) {
        $error = "لطفاً حساب بانکی مقصد را انتخاب کنید.";
    } else {
        $bank_stmt = $pdo->prepare("SELECT * FROM payment_accounts WHERE id = ? AND is_active = 1");
        $bank_stmt->execute([$selected_bank_id]);
        $selected_bank = $bank_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$selected_bank) {
            $error = "حساب بانکی انتخاب شده معتبر نیست.";
        } else {
            $receipt_image_path = null;
            $has_image = false;
            
            if ($receipt_type == 'image' && isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = '../../uploads/receipts/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION);
                $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                
                if (!in_array(strtolower($file_ext), $allowed_ext)) {
                    $upload_error = "فرمت فایل مجاز نیست. فقط jpg, jpeg, png, gif, webp";
                } else {
                    $new_filename = 'receipt_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                    $upload_path = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($_FILES['receipt_image']['tmp_name'], $upload_path)) {
                        $receipt_image_path = 'uploads/receipts/' . $new_filename;
                        $has_image = true;
                    } else {
                        $upload_error = "خطا در آپلود فایل.";
                    }
                }
            }
            
            if ($receipt_type == 'image' && !$has_image && empty($upload_error)) {
                $error = "لطفاً عکس رسید را آپلود کنید.";
            } elseif ($receipt_type == 'text' && empty($receipt_text)) {
                $error = "لطفاً متن رسید را وارد کنید.";
            } elseif (empty($upload_error)) {
                $request_tracking_code = strtoupper(substr(md5(uniqid() . $agent['id'] . time()), 0, 12));
                
                $bank_details = json_encode([
                    'bank_id' => $selected_bank['id'],
                    'bank_name' => $selected_bank['bank_name'],
                    'card_number' => $selected_bank['card_number'],
                    'card_owner' => $selected_bank['card_owner']
                ]);
                
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO balance_requests (
                            agent_id, agent_name, agent_token, amount, 
                            selected_bank_account_id, selected_bank_details,
                            receipt_image, receipt_text, receipt_tracking_code, 
                            receipt_deposit_time, user_note, request_tracking_code, status
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
                    ");
                    
                    $stmt->execute([
                        $agent['id'],
                        $agent['name'],
                        $agent['token'],
                        $amount_toman,
                        $selected_bank['id'],
                        $bank_details,
                        $receipt_image_path,
                        $receipt_text,
                        $receipt_tracking_code,
                        $receipt_deposit_time,
                        $user_note,
                        $request_tracking_code
                    ]);
                    
                    $success = "درخواست شما با موفقیت ثبت شد. مبلغ " . number_format($amount_toman) . " تومان | کد پیگیری: " . $request_tracking_code;
                    $_POST = [];
                    
                } catch (PDOException $e) {
                    $error = "خطا در ثبت درخواست: " . $e->getMessage();
                }
            } else {
                $error = $upload_error;
            }
        }
    }
}

$history_requests = [];
try {
    $stmt = $pdo->prepare("
        SELECT * FROM balance_requests 
        WHERE agent_id = ? 
        ORDER BY created_at DESC 
        LIMIT 20
    ");
    $stmt->execute([$agent['id']]);
    $history_requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

$stats = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
foreach ($history_requests as $req) {
    if (isset($stats[$req['status']])) $stats[$req['status']]++;
}

$status_filter = $_GET['status'] ?? 'all';
$filtered_requests = $history_requests;
if ($status_filter !== 'all') {
    $filtered_requests = array_filter($history_requests, function($req) use ($status_filter) {
        return $req['status'] === $status_filter;
    });
}

$total_pending_amount = 0;
foreach ($history_requests as $req) {
    if ($req['status'] == 'pending') $total_pending_amount += $req['amount'];
}
?>
<!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);
            --accent: #8b5cf6;
            --accent-2: #6366f1;
            --glass-bg: rgba(255,255,255,0.28);
            --glass-inset: rgba(255,255,255,0.18);
            --glass-border: rgba(255,255,255,0.35);
            --glass-border-mid: rgba(255,255,255,0.45);
            --glass-border-hi: rgba(255,255,255,0.65);
            --glass-top-shine: rgba(255,255,255,0.45);
            --text-1: #1f2937;
            --text-2: #4b5563;
            --text-3: #6b7280;
            --shadow-sm: 0 2px 8px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.06);
            --shadow-md: 0 8px 24px rgba(0,0,0,0.08), 0 2px 4px rgba(0,0,0,0.04);
            --blur: blur(12px);
            --blur-sm: blur(6px);
            --t-smooth: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            --r-sm: 8px;
            --r-md: 12px;
            --r-lg: 16px;
            --r-xl: 24px;
            --r-pill: 999px;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: linear-gradient(145deg, #eef2ff 0%, #e0e7ff 100%); min-height: 100vh; font-family: 'Vazir', system-ui, sans-serif; }
        .page-wrap { max-width: 1440px; margin: 0 auto; padding: 24px; position: relative; z-index: 1; }
        
        .admin-header { display: flex; align-items: center; justify-content: space-between; background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); padding: 16px 28px; margin-bottom: 28px; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-sm); }
        .brand { display: flex; align-items: center; gap: 12px; }
        .brand-logo { width: 44px; height: 44px; border-radius: 14px; object-fit: cover; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .brand-name { font-size: 20px; font-weight: 800; background: linear-gradient(135deg, #4f46e5, #7c3aed); -webkit-background-clip: text; background-clip: text; color: transparent; }
        .admin-info { display: flex; align-items: center; gap: 12px; }
        .admin-welcome { font-size: 13px; color: var(--text-2); background: var(--glass-inset); padding: 8px 16px; border-radius: var(--r-pill); border: 1px solid var(--glass-border); }
        .logout-btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: rgba(239,68,68,0.12); border: 1px solid rgba(239,68,68,0.25); border-radius: var(--r-pill); color: #dc2626; text-decoration: none; font-size: 12px; font-weight: 600; transition: var(--t-smooth); }
        .logout-btn:hover { background: rgba(239,68,68,0.22); transform: translateY(-1px); }
        
        .balance-card { background: linear-gradient(135deg, rgba(79,70,229,0.2), rgba(139,92,246,0.15)); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); padding: 32px; margin-bottom: 28px; text-align: center; position: relative; overflow: hidden; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md); }
        .balance-card::before { content: ''; position: absolute; top: 0; left: 10%; right: 10%; height: 1px; background: linear-gradient(90deg, transparent, var(--glass-top-shine) 50%, transparent); }
        .balance-label { font-size: 14px; color: var(--text-3); letter-spacing: 1px; }
        .balance-amount { font-size: 56px; font-weight: 800; color: var(--text-1); margin: 12px 0; font-family: monospace; }
        .balance-amount small { font-size: 20px; font-weight: 500; }
        
        .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: 44px; height: 44px; border-radius: 14px; display: flex; align-items: center; justify-content: center; margin-bottom: 12px; backdrop-filter: var(--blur-sm); }
        .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(139,92,246,0.12); border: 1px solid rgba(139,92,246,0.25); }
        .kpi-value { font-size: 26px; font-weight: 700; color: var(--text-1); }
        .kpi-label { font-size: 12px; color: var(--text-3); margin-top: 6px; }
        
        .form-card { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); margin-bottom: 32px; overflow: hidden; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md); }
        .card-header { display: flex; align-items: center; gap: 10px; padding: 18px 24px; border-bottom: 1px solid var(--glass-border); background: rgba(255,255,255,0.12); }
        .card-header-icon { width: 36px; height: 36px; background: linear-gradient(135deg, var(--accent), var(--accent-2)); border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; }
        .card-title { font-size: 18px; font-weight: 700; color: var(--text-1); }
        .card-body { padding: 24px; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .form-field { display: flex; flex-direction: column; gap: 8px; }
        .form-field label { font-size: 12px; font-weight: 600; color: var(--text-2); }
        .form-field input, .form-field select, .form-field textarea { padding: 12px 14px; background: rgba(255,255,255,0.35); backdrop-filter: var(--blur-sm); border: 1px solid var(--glass-border); border-radius: var(--r-md); color: var(--text-1); font-size: 14px; transition: var(--t-smooth); }
        .form-field input:focus, .form-field select:focus, .form-field textarea:focus { outline: none; border-color: rgba(139,92,246,0.45); background: rgba(255,255,255,0.55); box-shadow: 0 0 0 3px rgba(139,92,246,0.15); }
        
        .bank-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; margin-top: 8px; }
        .bank-item { background: rgba(255,255,255,0.28); border: 2px solid var(--glass-border); border-radius: var(--r-md); padding: 14px; cursor: pointer; transition: var(--t-smooth); }
        .bank-item.selected { border-color: #8b5cf6; background: rgba(139,92,246,0.12); box-shadow: 0 0 0 2px rgba(139,92,246,0.2); }
        .bank-item:hover { transform: translateY(-2px); border-color: var(--glass-border-hi); }
        .bank-name { font-weight: 700; color: var(--text-1); margin-bottom: 8px; }
        .bank-card { font-family: monospace; font-size: 13px; direction: ltr; text-align: left; background: rgba(255,255,255,0.25); padding: 6px 8px; border-radius: var(--r-sm); }
        .bank-owner { font-size: 11px; color: var(--text-3); margin-top: 8px; }
        
        .radio-group { display: flex; gap: 16px; flex-wrap: wrap; }
        .radio-group label { display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: rgba(255,255,255,0.25); border: 1px solid var(--glass-border); border-radius: var(--r-pill); cursor: pointer; transition: var(--t-smooth); font-weight: 500; font-size: 13px; }
        .radio-group label.active { background: linear-gradient(135deg, var(--accent), var(--accent-2)); border-color: transparent; color: white; }
        .radio-group input { display: none; }
        .receipt-type-content { display: none; margin-top: 20px; padding: 20px; background: rgba(255,255,255,0.18); border-radius: var(--r-lg); border: 1px solid var(--glass-border); }
        .receipt-type-content.active { display: block; }
        
        .submit-btn { width: 100%; padding: 14px; background: linear-gradient(135deg, var(--accent), var(--accent-2)); border: none; border-radius: var(--r-pill); color: white; font-size: 15px; font-weight: 700; cursor: pointer; margin-top: 20px; transition: var(--t-smooth); box-shadow: 0 4px 14px rgba(139,92,246,0.3); }
        .submit-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(139,92,246,0.4); }
        
        .alert { display: flex; align-items: center; gap: 12px; padding: 14px 20px; border-radius: var(--r-md); margin-bottom: 20px; font-size: 13px; font-weight: 500; }
        .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; }
        .alert-info { background: rgba(59,130,246,0.12); border: 1px solid rgba(59,130,246,0.25); color: #1e40af; }
        
        .history-section { background: var(--glass-bg); backdrop-filter: var(--blur); border: 1px solid var(--glass-border-mid); border-radius: var(--r-xl); overflow: hidden; box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md); }
        .history-tabs { display: flex; gap: 8px; padding: 16px 20px; border-bottom: 1px solid var(--glass-border); background: rgba(255,255,255,0.12); flex-wrap: wrap; }
        .history-tab { padding: 8px 20px; border-radius: var(--r-pill); background: transparent; border: 1px solid var(--glass-border); color: var(--text-2); text-decoration: none; font-size: 13px; font-weight: 500; transition: var(--t-smooth); }
        .history-tab:hover { background: var(--glass-inset); }
        .history-tab.active { background: #3b82f6; border-color: #3b82f6; color: white; }
        .history-tab.pending.active { background: var(--pending); border-color: var(--pending); }
        .history-tab.approved.active { background: var(--approved); border-color: var(--approved); }
        .history-tab.rejected.active { background: var(--rejected); border-color: var(--rejected); }
        
        .table-scroll { overflow-x: auto; }
        .history-table { width: 100%; border-collapse: collapse; min-width: 700px; }
        .history-table th, .history-table td { padding: 14px 12px; text-align: center; border-bottom: 1px solid var(--glass-border); font-size: 13px; }
        .history-table th { background: rgba(255,255,255,0.08); color: var(--text-2); font-weight: 600; }
        
        .status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: var(--r-pill); font-size: 11px; font-weight: 600; }
        .status-badge::before { content: ''; width: 6px; height: 6px; border-radius: 50%; }
        .status-pending { background: var(--pending-bg); color: #d97706; border: 1px solid var(--pending-bdr); }
        .status-pending::before { background: var(--pending); }
        .status-approved { background: var(--approved-bg); color: #059669; border: 1px solid var(--approved-bdr); }
        .status-approved::before { background: var(--approved); }
        .status-rejected { background: var(--rejected-bg); color: #dc2626; border: 1px solid var(--rejected-bdr); }
        .status-rejected::before { background: var(--rejected); }
        
        .view-detail { background: rgba(59,130,246,0.15); border: 1px solid rgba(59,130,246,0.3); color: #2563eb; padding: 6px 14px; border-radius: var(--r-pill); cursor: pointer; font-size: 12px; font-weight: 600; transition: var(--t-smooth); }
        .view-detail:hover { background: rgba(59,130,246,0.25); transform: translateY(-1px); }
        .empty-state { text-align: center; padding: 48px; color: var(--text-3); }
        
        .modal { 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; padding: 20px; }
        .modal.active { display: flex; }
        .modal-card { background: rgba(255,255,255,0.85); backdrop-filter: blur(20px); border: 1px solid var(--glass-border-hi); border-radius: var(--r-xl); padding: 28px; max-width: 520px; width: 100%; max-height: 85vh; overflow-y: auto; box-shadow: var(--shadow-xl); }
        .detail-row { display: flex; padding: 12px 0; border-bottom: 1px solid var(--glass-border); }
        .detail-label { width: 110px; font-weight: 600; color: var(--text-2); font-size: 12px; }
        .detail-value { flex: 1; color: var(--text-1); font-size: 13px; }
        .receipt-image-small { max-width: 100%; border-radius: var(--r-md); margin-top: 8px; cursor: pointer; border: 1px solid var(--glass-border); }
        .close-modal-btn { width: 100%; padding: 12px; background: var(--glass-inset); border: 1px solid var(--glass-border); border-radius: var(--r-pill); cursor: pointer; margin-top: 20px; font-weight: 600; transition: var(--t-smooth); }
        .close-modal-btn:hover { background: rgba(239,68,68,0.12); border-color: rgba(239,68,68,0.3); color: #dc2626; }
        
        @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; gap: 14px; text-align: center; } .balance-amount { font-size: 38px; } .kpi-strip { grid-template-columns: repeat(2, 1fr); } .bank-list { grid-template-columns: 1fr; } }
        @media (max-width: 480px) { .kpi-strip { grid-template-columns: 1fr; } .history-tabs { justify-content: center; } }
    </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($agent['name']) ?></strong></span>
            <a href="../agent.php" class="logout-btn">بازگشت</a>
            <a href="../agent.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>

    <div class="balance-card">
        <div class="balance-label">موجودی فعلی شما</div>
        <div class="balance-amount">
            <?= number_format($agent['balance']) ?>
            <small>تومان</small>
        </div>
    </div>

    <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($stats['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($stats['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($stats['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_pending_amount) ?></div>
            <div class="kpi-label">مبلغ در انتظار (تومان)</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="form-card">
        <div class="card-header">
            <div class="card-header-icon">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            </div>
            <div class="card-title">درخواست افزایش موجودی</div>
        </div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data" id="requestForm">
                <div class="form-grid">
                    <div class="form-field">
                        <label>مبلغ (تومان) *</label>
                        <input type="number" name="amount" placeholder="مبلغ به تومان" min="1000" step="1000" required value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">
                        <small>حداقل مبلغ: 1,000 تومان</small>
                    </div>
                    <div class="form-field">
                        <label>شماره پیگیری تراکنش</label>
                        <input type="text" name="receipt_tracking_code" placeholder="شماره پیگیری بانکی" value="<?= htmlspecialchars($_POST['receipt_tracking_code'] ?? '') ?>">
                    </div>
                    <div class="form-field">
                        <label>ساعت واریز</label>
                        <input type="text" name="receipt_deposit_time" placeholder="مثال: 1403/01/15 14:30" value="<?= htmlspecialchars($_POST['receipt_deposit_time'] ?? '') ?>">
                        <small>خالی بگذارید = زمان جاری</small>
                    </div>
                </div>

                <div class="form-field">
                    <label>انتخاب حساب بانکی مقصد *</label>
                    <div class="bank-list" id="bankList">
                        <?php if (count($bank_accounts) > 0): ?>
                            <?php foreach ($bank_accounts as $bank): ?>
                                <div class="bank-item <?= (($_POST['selected_bank'] ?? '') == $bank['id']) ? 'selected' : '' ?>" data-bank-id="<?= $bank['id'] ?>">
                                    <div class="bank-name"><?= htmlspecialchars($bank['bank_name']) ?></div>
                                    <div class="bank-card"><?= htmlspecialchars($bank['card_number']) ?></div>
                                    <div class="bank-owner"><?= htmlspecialchars($bank['card_owner']) ?></div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-info">هیچ حساب بانکی فعالی تعریف نشده است. لطفاً با پشتیبانی تماس بگیرید.</div>
                        <?php endif; ?>
                    </div>
                    <input type="hidden" name="selected_bank" id="selectedBank" value="<?= htmlspecialchars($_POST['selected_bank'] ?? '') ?>">
                </div>

                <div class="form-field">
                    <label>نوع رسید</label>
                    <div class="radio-group">
                        <label class="<?= (!isset($_POST['receipt_type']) || $_POST['receipt_type'] == 'image') ? 'active' : '' ?>">
                            <input type="radio" name="receipt_type" value="image" <?= (!isset($_POST['receipt_type']) || $_POST['receipt_type'] == 'image') ? 'checked' : '' ?>>
                            آپلود عکس رسید
                        </label>
                        <label class="<?= (isset($_POST['receipt_type']) && $_POST['receipt_type'] == 'text') ? 'active' : '' ?>">
                            <input type="radio" name="receipt_type" value="text" <?= (isset($_POST['receipt_type']) && $_POST['receipt_type'] == 'text') ? 'checked' : '' ?>>
                            وارد کردن متن رسید
                        </label>
                    </div>
                </div>

                <div id="imageReceipt" class="receipt-type-content <?= (!isset($_POST['receipt_type']) || $_POST['receipt_type'] == 'image') ? 'active' : '' ?>">
                    <div class="form-field">
                        <label>آپلود عکس رسید *</label>
                        <input type="file" name="receipt_image" accept="image/*">
                        <small>فرمت‌های مجاز: JPG, PNG, GIF, WEBP</small>
                    </div>
                </div>

                <div id="textReceipt" class="receipt-type-content <?= (isset($_POST['receipt_type']) && $_POST['receipt_type'] == 'text') ? 'active' : '' ?>">
                    <div class="form-field">
                        <label>متن رسید *</label>
                        <textarea name="receipt_text" rows="3" placeholder="شماره تراکنش، کد پیگیری، مبلغ واریزی و ..."><?= htmlspecialchars($_POST['receipt_text'] ?? '') ?></textarea>
                    </div>
                </div>

                <div class="form-field">
                    <label>یادداشت (اختیاری)</label>
                    <textarea name="user_note" rows="2" placeholder="توضیحات اضافی خود را وارد کنید..."><?= htmlspecialchars($_POST['user_note'] ?? '') ?></textarea>
                </div>

                <button type="submit" name="submit_request" class="submit-btn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" style="display: inline; margin-left: 8px;"><path d="M19 10l-7-7-7 7"/><path d="M12 3v14"/><path d="M3 17v3a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-3"/></svg>
                    ثبت درخواست افزایش موجودی
                </button>
            </form>
        </div>
    </div>

    <div class="history-section">
        <div class="history-tabs">
            <a href="?status=all" class="history-tab <?= $status_filter == 'all' ? 'active' : '' ?>">همه (<?= count($history_requests) ?>)</a>
            <a href="?status=pending" class="history-tab pending <?= $status_filter == 'pending' ? 'active' : '' ?>">در انتظار (<?= $stats['pending'] ?>)</a>
            <a href="?status=approved" class="history-tab approved <?= $status_filter == 'approved' ? 'active' : '' ?>">تایید شده (<?= $stats['approved'] ?>)</a>
            <a href="?status=rejected" class="history-tab rejected <?= $status_filter == 'rejected' ? 'active' : '' ?>">رد شده (<?= $stats['rejected'] ?>)</a>
        </div>

        <div class="table-scroll">
            <table class="history-table">
                <thead>
                    <tr>
                        <th>کد پیگیری</th>
                        <th>مبلغ (تومان)</th>
                        <th>حساب بانکی</th>
                        <th>زمان ارسال</th>
                        <th>وضعیت</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($filtered_requests) > 0): ?>
                        <?php foreach ($filtered_requests as $req): 
                            $bank_details = json_decode($req['selected_bank_details'], true);
                        ?>
                            <tr>
                                <td><code><?= htmlspecialchars($req['request_tracking_code']) ?></code></td>
                                <td><strong><?= number_format($req['amount']) ?></strong></td>
                                <td><?= htmlspecialchars($bank_details['bank_name'] ?? '-') ?></td>
                                <td><?= date('Y/m/d H:i', strtotime($req['created_at'])) ?></td>
                                <td>
                                    <span class="status-badge status-<?= $req['status'] ?>">
                                        <?= $req['status'] == 'pending' ? 'در انتظار' : ($req['status'] == 'approved' ? 'تایید شده' : 'رد شده') ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="view-detail" onclick='showRequestDetail(<?= json_encode($req) ?>)'>
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: inline; margin-left: 4px;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                                        جزئیات
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6">
                                <div class="empty-state">
                                    <div>هیچ درخواستی در این بخش وجود ندارد.</div>
                                </div>
                              </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<div id="detailModal" class="modal" onclick="closeDetailModal(event)">
    <div class="modal-card" onclick="event.stopPropagation()">
        <h3 style="margin-bottom: 20px;">جزئیات درخواست</h3>
        <div id="detailContent"></div>
        <button class="close-modal-btn" onclick="closeDetailModal()">بستن</button>
    </div>
</div>

<script>
    document.querySelectorAll('.bank-item').forEach(function(item) {
        item.addEventListener('click', function() {
            var bankId = this.getAttribute('data-bank-id');
            document.querySelectorAll('.bank-item').forEach(function(el) {
                el.classList.remove('selected');
            });
            this.classList.add('selected');
            document.getElementById('selectedBank').value = bankId;
        });
    });

    function toggleReceiptType(radioElement) {
        var imageReceipt = document.getElementById('imageReceipt');
        var textReceipt = document.getElementById('textReceipt');
        var labels = document.querySelectorAll('.radio-group label');
        
        labels.forEach(function(label) {
            label.classList.remove('active');
        });
        radioElement.closest('label').classList.add('active');
        
        if (radioElement.value === 'image') {
            imageReceipt.classList.add('active');
            textReceipt.classList.remove('active');
        } else {
            imageReceipt.classList.remove('active');
            textReceipt.classList.add('active');
        }
    }

    document.querySelectorAll('input[name="receipt_type"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            toggleReceiptType(this);
        });
    });

    function showRequestDetail(request) {
        var data = request;
        var bankDetails = '';
        if (data.selected_bank_details) {
            var bank = JSON.parse(data.selected_bank_details);
            bankDetails = '<div class="detail-row"><div class="detail-label">بانک مقصد:</div><div class="detail-value">' + escapeHtml(bank.bank_name) + '</div></div>' +
                          '<div class="detail-row"><div class="detail-label">شماره کارت:</div><div class="detail-value">' + escapeHtml(bank.card_number) + '</div></div>' +
                          '<div class="detail-row"><div class="detail-label">صاحب حساب:</div><div class="detail-value">' + escapeHtml(bank.card_owner) + '</div></div>';
        }
        
        var receiptHtml = '';
        if (data.receipt_image) {
            var imagePath = '../../' + data.receipt_image;
            receiptHtml = '<div class="detail-row"><div class="detail-label">عکس رسید:</div><div class="detail-value"><img src="' + escapeHtml(imagePath) + '" class="receipt-image-small" onclick="window.open(\'' + escapeHtml(imagePath) + '\', \'_blank\')"></div></div>';
        } else if (data.receipt_text) {
            receiptHtml = '<div class="detail-row"><div class="detail-label">متن رسید:</div><div class="detail-value">' + escapeHtml(data.receipt_text) + '</div></div>';
        }
        
        var statusText = {
            'pending': 'در انتظار تایید',
            'approved': 'تایید شده',
            'rejected': 'رد شده'
        };
        
        var statusColor = {
            'pending': '#d97706',
            'approved': '#059669',
            'rejected': '#dc2626'
        };
        
        var html = '<div class="detail-row"><div class="detail-label">کد پیگیری:</div><div class="detail-value"><code>' + escapeHtml(data.request_tracking_code) + '</code></div></div>' +
                   '<div class="detail-row"><div class="detail-label">مبلغ:</div><div class="detail-value"><strong>' + numberFormat(data.amount) + ' تومان</strong></div></div>' +
                   bankDetails +
                   (data.receipt_tracking_code ? '<div class="detail-row"><div class="detail-label">شماره پیگیری:</div><div class="detail-value">' + escapeHtml(data.receipt_tracking_code) + '</div></div>' : '') +
                   (data.receipt_deposit_time ? '<div class="detail-row"><div class="detail-label">ساعت واریز:</div><div class="detail-value">' + escapeHtml(data.receipt_deposit_time) + '</div></div>' : '') +
                   (data.user_note ? '<div class="detail-row"><div class="detail-label">یادداشت شما:</div><div class="detail-value">' + escapeHtml(data.user_note) + '</div></div>' : '') +
                   (data.admin_note ? '<div class="detail-row"><div class="detail-label">پاسخ ادمین:</div><div class="detail-value">' + escapeHtml(data.admin_note) + '</div></div>' : '') +
                   receiptHtml +
                   '<div class="detail-row"><div class="detail-label">وضعیت:</div><div class="detail-value" style="color: ' + statusColor[data.status] + '; font-weight: bold;">' + statusText[data.status] + '</div></div>' +
                   '<div class="detail-row"><div class="detail-label">زمان ارسال:</div><div class="detail-value">' + escapeHtml(data.created_at) + '</div></div>' +
                   (data.processed_at ? '<div class="detail-row"><div class="detail-label">زمان بررسی:</div><div class="detail-value">' + escapeHtml(data.processed_at) + '</div></div>' : '');
        
        document.getElementById('detailContent').innerHTML = html;
        document.getElementById('detailModal').classList.add('active');
    }

    function closeDetailModal(event) {
        if (!event || event.target === document.getElementById('detailModal')) {
            document.getElementById('detailModal').classList.remove('active');
        }
    }

    function escapeHtml(str) {
        if (!str) return '';
        return 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>