<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

if (!isLoggedIn() || !isRepresentative()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'کیف پول و پروفایل';

$representative_id = $_SESSION['user_id'];

// به‌روزرسانی پروفایل
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_profile') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $telegram = trim($_POST['telegram_id'] ?? '');
    $whatsapp = trim($_POST['whatsapp_number'] ?? '');

    try {
        $stmt = $pdo->prepare("UPDATE representatives SET full_name = ?, email = ?, phone = ?, telegram_id = ?, whatsapp_number = ? WHERE id = ?");
        $stmt->execute([$full_name, $email, $phone, $telegram, $whatsapp, $representative_id]);
        setMessage('اطلاعات پروفایل با موفقیت به‌روزرسانی شد.');
        redirect('wallet.php');
    } catch (Exception $e) {
        setMessage('خطا در به‌روزرسانی: ' . $e->getMessage(), 'error');
    }
}

// ثبت درخواست واریز جدید
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'deposit_request') {
    $amount = (float)($_POST['amount'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $receipt_image = null;

    if ($amount <= 0) {
        setMessage('مبلغ واریزی باید بیشتر از صفر باشد', 'error');
    } else {
        // آپلود تصویر فیش اگر ارسال شده باشد
        if (isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] === UPLOAD_ERR_OK) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
            $file_type = $_FILES['receipt_image']['type'];
            if (in_array($file_type, $allowed_types)) {
                $ext = pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION);
                $filename = 'receipt_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
                $target_path = '../uploads/receipts/' . $filename;
                if (move_uploaded_file($_FILES['receipt_image']['tmp_name'], $target_path)) {
                    $receipt_image = $filename;
                }
            } else {
                setMessage('فرمت تصویر فیش معتبر نیست (فقط JPG, PNG)', 'error');
            }
        }

        if (empty($description) && !$receipt_image) {
            setMessage('لطفاً فیش واریزی را آپلود کنید یا شماره پیگیری/توضیحات را وارد کنید', 'error');
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO payment_requests (representative_id, amount, description, receipt_image, status) VALUES (?, ?, ?, ?, 'pending')");
                $stmt->execute([$representative_id, $amount, $description ?: null, $receipt_image]);
                setMessage('درخواست واریز شما ثبت شد و پس از تأیید ادمین، کیف پول شما شارژ خواهد شد');
                redirect('wallet.php');
            } catch (Exception $e) {
                setMessage('خطا در ثبت درخواست: ' . $e->getMessage(), 'error');
            }
        }
    }
}

// اطلاعات نماینده
$rep = $pdo->prepare("SELECT id, username, full_name, email, phone, telegram_id, whatsapp_number, traffic_limit, expiry_date, last_activity, created_at FROM representatives WHERE id = ?");
$rep->execute([$representative_id]);
$rep = $rep->fetch();

if (!$rep) {
    setMessage('نماینده یافت نشد', 'error');
    redirect('dashboard.php');
}

$balance = walletBalance($pdo, $representative_id);

// دریافت اطلاعات بانکی ادمین
$admin_card_number = getSetting($pdo, 'admin_card_number', '');
$admin_card_name = getSetting($pdo, 'admin_card_name', '');

// تاریخچه درخواست‌های واریز
$payment_requests = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM payment_requests WHERE representative_id = ? ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([$representative_id]);
    $payment_requests = $stmt->fetchAll();
} catch (Exception $e) {}

// قیمت‌ها: اول از نماینده، در غیر این صورت از تنظیمات سراسری
$rep_prices = $pdo->prepare("SELECT price_per_gb, price_per_day FROM representatives WHERE id = ?");
$rep_prices->execute([$representative_id]);
$rep_prices = $rep_prices->fetch();
$price_per_config = walletPricePerConfig($pdo);
$price_per_gb = isset($rep_prices['price_per_gb']) && $rep_prices['price_per_gb'] !== '' && $rep_prices['price_per_gb'] !== null
    ? (float)$rep_prices['price_per_gb'] : walletPricePerGB($pdo);
$price_per_day = isset($rep_prices['price_per_day']) && $rep_prices['price_per_day'] !== '' && $rep_prices['price_per_day'] !== null
    ? (float)$rep_prices['price_per_day'] : walletPricePerDay($pdo);
$rep_discount = $pdo->prepare("SELECT discount_percent FROM representatives WHERE id = ?");
$rep_discount->execute([$representative_id]);
$rep_discount = $rep_discount->fetch();
$discount_percent = isset($rep_discount['discount_percent']) && $rep_discount['discount_percent'] !== '' && $rep_discount['discount_percent'] !== null
    ? (int)$rep_discount['discount_percent'] : defaultDiscountPercent($pdo);

// تاریخچه تراکنش‌ها (در صورت وجود جدول)
$transactions = [];
try {
    $stmt = $pdo->prepare("SELECT id, amount, type, ref_id, description, created_at FROM wallet_transactions WHERE representative_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$representative_id]);
    $transactions = $stmt->fetchAll();
} catch (Exception $e) {
    // جدول ممکن است وجود نداشته باشد
}

$type_labels = [
    'create_user' => 'ساخت کانفیگ',
    'admin_deposit' => 'واریز توسط ادمین',
    'admin_deduct' => 'برداشت توسط ادمین',
    'refund' => 'بازگشت مبلغ'
];

// Representative initials and code
$rep_name = $_SESSION['username'] ?? 'نماینده';
$rep_initials = mb_substr($rep_name, 0, 1, 'UTF-8');
$rep_customer_code = "REP-" . (1000 + $representative_id);

require_once '../includes/header.php';
?>

<style>
/* استایل‌های حرفه‌ای پروفایل و داشبورد */
.profile-card-header-pro {
    background: linear-gradient(135deg, #1e293b, #0f172a);
    border-radius: 20px;
    position: relative;
    overflow: hidden;
    border: 1px solid rgba(255,255,255,0.05);
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.profile-card-header-pro::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -10%;
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(16, 185, 129, 0.08) 0%, transparent 70%);
    z-index: 0;
}
.profile-avatar-large {
    width: 100px;
    height: 100px;
    border-radius: 28px;
    background: linear-gradient(135deg, var(--accent-primary), #10b981);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.8rem;
    color: white;
    font-weight: 700;
    border: 5px solid rgba(255,255,255,0.05);
    z-index: 1;
    position: relative;
}
.customer-code-pro {
    background: rgba(255,255,255,0.08);
    color: #10b981;
    padding: 4px 12px;
    border-radius: 8px;
    font-family: 'Vazirmatn', monospace;
    font-weight: 600;
    font-size: 0.9rem;
    border: 1px solid rgba(16, 185, 129, 0.2);
}
.btn-glass-success {
    background: rgba(16, 185, 129, 0.1);
    color: #34d399;
    border: 1px solid rgba(16, 185, 129, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 10px 20px;
    font-weight: 600;
    transition: all 0.3s;
}
.btn-glass-success:hover {
    transform: translateY(-2px);
    background: rgba(255,255,255,0.05);
}
.wallet-balance-card-pro {
    background: linear-gradient(135deg, #10b981, #059669);
    border-radius: 20px;
    border: none;
    box-shadow: 0 10px 20px rgba(16, 185, 129, 0.2);
    position: relative;
    overflow: hidden;
}
.wallet-balance-card-pro::after {
    content: '';
    position: absolute;
    top: -20%;
    left: -10%;
    width: 150px;
    height: 150px;
    background: rgba(255,255,255,0.1);
    border-radius: 50%;
}
.detail-item-pro {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 12px;
    padding: 1rem;
    margin-bottom: 1rem;
    transition: all 0.2s;
}
.detail-item-pro label {
    display: block;
    font-size: 0.75rem;
    color: var(--text-muted);
    margin-bottom: 0.25rem;
}
.detail-item-pro span {
    display: block;
    font-weight: 600;
    color: var(--text-primary);
}
.form-control-pro {
    background: rgba(255,255,255,0.03) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    color: white !important;
    border-radius: 10px;
}
.form-control-pro:focus {
    border-color: var(--accent-primary) !important;
    box-shadow: none !important;
}
</style>

<div class="container-fluid">
    <!-- Profile Header Pro -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="profile-card-header-pro">
                <div class="d-md-flex align-items-center justify-content-between p-4">
                    <div class="d-flex align-items-center gap-4">
                        <div class="profile-avatar-large shadow-lg"><?= htmlspecialchars($rep_initials) ?></div>
                        <div class="profile-info-main">
                            <h3 class="text-white mb-1"><?= htmlspecialchars($rep_name) ?></h3>
                            <p class="text-white-50 mb-2"><i class="bi bi-wallet2 me-1"></i> مدیریت کیف پول و حساب</p>
                            <span class="customer-code-pro">
                                <?= $rep_customer_code ?>
                            </span>
                        </div>
                    </div>
                    <div class="mt-4 mt-md-0 d-flex gap-2">
                        <button type="button" class="btn btn-glass-success" data-bs-toggle="modal" data-bs-target="#depositModal">
                            <i class="bi bi-plus-circle me-1"></i> شارژ کیف پول
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="card wallet-balance-card-pro h-100">
                <div class="card-body text-center d-flex flex-column justify-content-center py-5">
                    <div class="mb-3">
                        <i class="bi bi-cash-stack text-white" style="font-size: 3rem;"></i>
                    </div>
                    <h6 class="text-white opacity-75 mb-2">موجودی فعلی کیف پول</h6>
                    <h1 class="text-white mb-4"><?= number_format($balance) ?> <small class="fs-6 opacity-75 fw-normal">تومان</small></h1>
                    
                    <?php if ($price_per_config > 0 || $price_per_gb > 0 || $price_per_day > 0): ?>
                        <div class="bg-white bg-opacity-10 rounded-4 p-3 mb-4 text-start">
                            <p class="small mb-2 text-white border-bottom border-white border-opacity-10 pb-1"><strong>نرخ‌های اختصاصی شما:</strong></p>
                            <?php if ($price_per_config > 0): ?>
                                <div class="d-flex justify-content-between text-white-50 small mb-1">
                                    <span>هر کانفیگ:</span>
                                    <span class="text-white fw-bold"><?= number_format($price_per_config) ?> تومان</span>
                                </div>
                            <?php endif; ?>
                            <?php if ($price_per_gb > 0): ?>
                                <div class="d-flex justify-content-between text-white-50 small mb-1">
                                    <span>هر گیگابایت:</span>
                                    <span class="text-white fw-bold"><?= number_format($price_per_gb) ?> تومان</span>
                                </div>
                            <?php endif; ?>
                            <?php if ($price_per_day > 0): ?>
                                <div class="d-flex justify-content-between text-white-50 small mb-1">
                                    <span>هر روز اعتبار:</span>
                                    <span class="text-white fw-bold"><?= number_format($price_per_day) ?> تومان</span>
                                </div>
                            <?php endif; ?>
                            <?php if ($discount_percent > 0): ?>
                                <div class="d-flex justify-content-between text-white small mt-2 pt-1 border-top border-white border-opacity-10">
                                    <span>تخفیف ویژه:</span>
                                    <span class="badge bg-white text-success"><?= $discount_percent ?>%</span>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <button type="button" class="btn btn-light w-100 rounded-3 fw-bold py-2" data-bs-toggle="modal" data-bs-target="#depositModal">
                        <i class="bi bi-plus-lg me-1"></i> افزایش موجودی آنی
                    </button>
                </div>
            </div>
        </div>
        <div class="col-lg-8 mb-4">
            <div class="card h-100">
                <div class="card-header bg-transparent border-0 pt-4 px-4">
                    <h5 class="mb-0"><i class="bi bi-gear-fill me-2 text-primary"></i> تنظیمات و جزئیات حساب</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="detail-item-pro">
                                <label>نام کاربری</label>
                                <span><?= htmlspecialchars($rep['username']) ?></span>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="detail-item-pro">
                                <label>تاریخ انقضا</label>
                                <span><?= $rep['expiry_date'] ? date('Y/m/d', strtotime($rep['expiry_date'])) : 'نامحدود' ?></span>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="detail-item-pro">
                                <label>آخرین فعالیت</label>
                                <span><?= $rep['last_activity'] ? date('Y/m/d H:i', strtotime($rep['last_activity'])) : 'بدون فعالیت' ?></span>
                            </div>
                        </div>
                    </div>

                    <form method="POST">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label small text-muted">نام و نام خانوادگی</label>
                                <input type="text" name="full_name" class="form-control form-control-pro" value="<?= htmlspecialchars($rep['full_name'] ?? '') ?>" placeholder="وارد کنید...">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted">آدرس ایمیل</label>
                                <input type="email" name="email" class="form-control form-control-pro" value="<?= htmlspecialchars($rep['email'] ?? '') ?>" placeholder="example@mail.com">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted">آدرس تلگرام</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-dark bg-opacity-25 border-0 text-white-50"><i class="bi bi-telegram"></i></span>
                                    <input type="text" name="telegram_id" class="form-control form-control-pro" value="<?= htmlspecialchars($rep['telegram_id'] ?? '') ?>" placeholder="@username">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted">شماره واتس‌اپ</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-dark bg-opacity-25 border-0 text-white-50"><i class="bi bi-whatsapp"></i></span>
                                    <input type="text" name="whatsapp_number" class="form-control form-control-pro" value="<?= htmlspecialchars($rep['whatsapp_number'] ?? '') ?>" placeholder="09xxxxxxxxx">
                                </div>
                            </div>
                            <div class="col-12 mt-4 text-end">
                                <button type="submit" class="btn btn-primary px-4 py-2 rounded-3">
                                    <i class="bi bi-save me-1"></i> به‌روزرسانی اطلاعات پروفایل
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xl-6 mb-4">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center py-3">
                    <h5 class="mb-0 fs-6"><i class="bi bi-file-earmark-text me-2 text-warning"></i> وضعیت درخواست‌های واریز اخیر</h5>
                    <a href="#" class="text-primary small text-decoration-none">مشاهده همه</a>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($payment_requests)): ?>
                        <div class="p-5 text-center text-muted small">
                            <i class="bi bi-inbox fs-1 d-block mb-2 opacity-25"></i>
                            هنوز درخواستی ثبت نشده است.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="table-light bg-opacity-50">
                                    <tr>
                                        <th class="small">تاریخ</th>
                                        <th class="small">مبلغ</th>
                                        <th class="small text-center">وضعیت</th>
                                        <th class="small text-center">فیش</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($payment_requests as $req): ?>
                                        <tr>
                                            <td class="small"><?= date('Y/m/d H:i', strtotime($req['created_at'])) ?></td>
                                            <td class="fw-bold"><?= number_format($req['amount']) ?> <small class="fw-normal">تومان</small></td>
                                            <td class="text-center">
                                                <?php if ($req['status'] === 'pending'): ?>
                                                    <span class="badge bg-warning bg-opacity-10 text-warning px-2 py-1">در انتظار</span>
                                                <?php elseif ($req['status'] === 'approved'): ?>
                                                    <span class="badge bg-success bg-opacity-10 text-success px-2 py-1">تأیید شده</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger bg-opacity-10 text-danger px-2 py-1">رد شده</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($req['receipt_image']): ?>
                                                    <a href="../uploads/receipts/<?= htmlspecialchars($req['receipt_image']) ?>" target="_blank" class="btn btn-sm btn-soft-info p-1 px-2" title="مشاهده فیش">
                                                        <i class="bi bi-image"></i>
                                                    </a>
                                                <?php else: ?>
                                                    <span class="text-muted small">-</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-xl-6 mb-4">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center py-3">
                    <h5 class="mb-0 fs-6"><i class="bi bi-clock-history me-2 text-info"></i> تاریخچه تراکنش‌های کیف پول</h5>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($transactions)): ?>
                        <div class="p-5 text-center text-muted small">
                            <i class="bi bi-activity fs-1 d-block mb-2 opacity-25"></i>
                            هنوز تراکنشی ثبت نشده است.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="table-light bg-opacity-50">
                                    <tr>
                                        <th class="small">تاریخ</th>
                                        <th class="small">نوع تراکنش</th>
                                        <th class="small">تغییر موجودی</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $tx): ?>
                                        <tr>
                                            <td class="small"><?= date('Y/m/d H:i', strtotime($tx['created_at'])) ?></td>
                                            <td class="small"><?= htmlspecialchars($type_labels[$tx['type']] ?? $tx['type']) ?></td>
                                            <td>
                                                <?php $amt = (float)$tx['amount']; ?>
                                                <span class="<?= $amt >= 0 ? 'text-success' : 'text-danger' ?> fw-bold">
                                                    <?= $amt >= 0 ? '+' : '' ?><?= number_format($amt) ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal درخواست واریز -->
<div class="modal fade" id="depositModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="background-color: #1e293b; border-radius: 24px;">
            <div class="modal-header border-bottom border-white border-opacity-10 py-4 px-4">
                <h5 class="modal-title text-white fw-bold"><i class="bi bi-cash-stack me-2 text-success"></i> افزایش موجودی کیف پول</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <input type="hidden" name="action" value="deposit_request">
                    
                    <div class="bg-success bg-opacity-10 rounded-4 p-3 mb-4 border border-success border-opacity-20">
                        <h6 class="text-success small fw-bold mb-2"><i class="bi bi-credit-card-2-front me-1"></i> اطلاعات بانکی جهت واریز:</h6>
                        <?php if (!empty($admin_card_number)): ?>
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <span class="text-white-50 small">شماره کارت:</span>
                                <strong class="text-white font-monospace fs-6"><?= htmlspecialchars($admin_card_number) ?></strong>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-white-50 small">بنام:</span>
                                <strong class="text-white"><?= htmlspecialchars($admin_card_name) ?></strong>
                            </div>
                        <?php else: ?>
                            <p class="mb-0 text-danger small">اطلاعات بانکی توسط ادمین تنظیم نشده است.</p>
                        <?php endif; ?>
                    </div>

                    <div class="mb-4">
                        <label class="form-label small text-white-50 mb-2">مبلغ واریزی (تومان) <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-dark bg-opacity-25 border-0 text-white-50"><i class="bi bi-currency-dollar"></i></span>
                            <input type="number" name="amount" class="form-control form-control-pro py-3" required min="1000" step="1000" placeholder="مثلاً 50,000">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label small text-white-50 mb-2">تصویر فیش واریزی</label>
                        <div class="input-group">
                            <input type="file" name="receipt_image" class="form-control form-control-pro" accept="image/*">
                        </div>
                        <small class="text-white-50 opacity-50 mt-2 d-block" style="font-size: 0.7rem;">آپلود فیش باعث تسریع در تایید درخواست می‌شود.</small>
                    </div>

                    <div class="mb-0">
                        <label class="form-label small text-white-50 mb-2">توضیحات یا شماره پیگیری</label>
                        <textarea name="description" class="form-control form-control-pro" rows="3" placeholder="شماره پیگیری یا توضیحات اضافی را اینجا بنویسید..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-top border-white border-opacity-10 p-4">
                    <button type="button" class="btn btn-link text-white-50 text-decoration-none fw-bold" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-success px-5 py-2 rounded-3 fw-bold shadow-sm">
                        <i class="bi bi-send-check me-1"></i> ثبت و ارسال درخواست
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
