<?php
// modules/transactions.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$success_msg = '';

// دریافت لیست بانک‌ها بر اساس سطح دسترسی
if ($isAdmin) {
    $banks = $pdo->query("SELECT * FROM banks ORDER BY id DESC")->fetchAll();
} else {
    $stmtBanks = $pdo->prepare("SELECT * FROM banks WHERE user_id = ? ORDER BY id DESC");
    $stmtBanks->execute([$userId]);
    $banks = $stmtBanks->fetchAll();
}
$plans = $pdo->query("SELECT * FROM plans ORDER BY id ASC")->fetchAll();

// ---------------------------------------------------------
// پردازش فرم ثبت تراکنش جدید
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'add_tx') {
    $type = $_POST['tx_type'];
    $dateShamsi = $_POST['tx_date'];
    $customerName = trim($_POST['customer_name']) ?: '-';
$accountUsername = trim($_POST['account_username']);
    $planId = (int)$_POST['plan_id']; 
    $volume = (float)$_POST['volume'];
    $volumeUnit = (isset($_POST['volume_unit']) && $_POST['volume_unit'] === 'MB') ? 'MB' : 'GB';
    $discount = (int)$_POST['discount']; 
    $bankId = empty($_POST['bank_id']) ? null : (int)$_POST['bank_id'];
    $customPaid = $_POST['paid_amount'] !== '' ? (int)$_POST['paid_amount'] : null;

    $stmtPlan = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
    $stmtPlan->execute([$planId]);
    $selectedPlan = $stmtPlan->fetch();
    
    if (!$selectedPlan) { die("طرح انتخاب شده معتبر نیست."); }
    
    $planName = $selectedPlan['plan_name'];
    $basePrice = $selectedPlan['retail_price'];
    $operatorCostPrice = $selectedPlan['cost_price'];
    $adminCostPrice = $selectedPlan['admin_cost_price'];

    $volumeForPrice = ($volumeUnit === 'MB') ? ($volume / 1024) : $volume;

    $finalPrice = ($basePrice * $volumeForPrice) - $discount;
    $paidAmount = ($customPaid !== null) ? $customPaid : $finalPrice;

    if ($isAdmin) {
        $operatorProfit = 0;
        $adminProfit = $paidAmount - ($adminCostPrice * $volumeForPrice);
    } else {
        $operatorProfit = $paidAmount - ($operatorCostPrice * $volumeForPrice);
        $adminProfit = ($operatorCostPrice * $volumeForPrice) - ($adminCostPrice * $volumeForPrice);
    }

    $insertSql = "INSERT INTO transactions 
                  (user_id, type, customer_name, account_username, plan, volume, volume_unit, discount, seller_id, bank_id, paid_amount, profit, admin_profit, date_shamsi) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)";
    $stmtInsert = $pdo->prepare($insertSql);
    $stmtInsert->execute([$userId, $type, $customerName, $accountUsername, $planName, $volume, $volumeUnit, $discount, $bankId, $paidAmount, $operatorProfit, $adminProfit, $dateShamsi]);
    
    $success_msg = "تراکنش (" . ($type == 'new' ? 'جدید' : 'تمدیدی') . ") با موفقیت ثبت شد!";
}

// ---------------------------------------------------------
// پردازش درخواست حذف تراکنش
// ---------------------------------------------------------
if (isset($_GET['delete_id'])) {
    $deleteId = (int)$_GET['delete_id'];
    if ($isAdmin) {
        $stmtDelete = $pdo->prepare("DELETE FROM transactions WHERE id = ?");
        $stmtDelete->execute([$deleteId]);
    } else {
        $stmtDelete = $pdo->prepare("DELETE FROM transactions WHERE id = ? AND user_id = ?");
        $stmtDelete->execute([$deleteId, $userId]);
    }
    header("Location: transactions.php?msg=deleted");
    exit;
}

if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') { $success_msg = "تراکنش مورد نظر با موفقیت حذف شد."; }
if (isset($_GET['msg']) && $_GET['msg'] == 'edited') { $success_msg = "تراکنش با موفقیت ویرایش شد."; }

// ---------------------------------------------------------
// دریافت لیست تراکنش‌های اخیر برای نمایش در جدول
// ---------------------------------------------------------
$whereClause = $isAdmin ? "1=1" : "t.user_id = :user_id";
$sqlList = "SELECT t.*, u.username as creator, b.bank_name, i.id as inv_id, i.config_link 
            FROM transactions t 
            LEFT JOIN users u ON t.user_id = u.id 
            LEFT JOIN banks b ON t.bank_id = b.id 
            LEFT JOIN inventory i ON t.account_username = i.account_username AND i.status = 'sold'
            WHERE $whereClause 
            GROUP BY t.id
            ORDER BY t.id DESC LIMIT 50"; 
            
$stmtList = $pdo->prepare($sqlList);
if (!$isAdmin) { $stmtList->bindParam(':user_id', $userId); }
$stmtList->execute();
$transactions = $stmtList->fetchAll();

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

<?php if($success_msg): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-6" role="alert">
    <strong class="font-bold">عالی!</strong>
    <span class="block sm:inline"><?php echo $success_msg; ?></span>
</div>
<?php endif; ?>

<!-- فرم ثبت تراکنش جدید -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 mb-8 border-t-4 border-t-blue-500 transition-all duration-300" id="txFormContainer">
    <h2 id="formTitle" class="text-xl font-bold mb-6 text-gray-800">ثبت تراکنش جدید</h2>
    <form method="POST" action="" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <input type="hidden" name="action" value="add_tx">
        
        <div>
            <label class="block text-sm font-medium mb-1">نوع تراکنش</label>
            <select name="tx_type" id="tx_type" class="w-full border rounded p-2 bg-gray-50 focus:border-blue-500 focus:outline-none">
                <option value="new">فروش جدید</option>
                <option value="recharge">شارژ مجدد (تمدیدی)</option>
            </select>
        </div>
        <div>
            <label class="block text-sm font-medium mb-1">تاریخ (شمسی)</label>
            <input type="text" name="tx_date" required class="w-full border rounded p-2 bg-gray-50 text-left font-bold text-blue-700" dir="ltr" value="<?php echo getTodayShamsi(); ?>">
        </div>
        
        <div><label class="block text-sm font-medium mb-1">نام مشتری</label><select name="customer_name" id="ajax_customer_name" class="w-full border rounded p-2 bg-gray-50"></select></div>
        <div><label class="block text-sm font-medium mb-1 text-red-600">نام کاربری (اکانت) *</label><select name="account_username" id="ajax_account_username" required class="w-full border rounded p-2 bg-gray-50 text-left" dir="ltr"></select></div>
        
        <div><label class="block text-sm font-medium mb-1">حساب واریزی</label>
            <select name="bank_id" class="w-full border rounded p-2 bg-gray-50 focus:border-blue-500 focus:outline-none">
                <option value="">نامشخص / نقدی</option>
                <?php foreach($banks as $b): ?><option value="<?php echo $b['id']; ?>"><?php echo $b['bank_name']; ?></option><?php endforeach; ?>
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-medium mb-1">نوع سرویس (طرح)</label>
            <select name="plan_id" id="plan_id" class="w-full border rounded p-2 bg-gray-50 focus:border-blue-500 focus:outline-none">
                <?php foreach($plans as $p): ?>
                    <option value="<?php echo $p['id']; ?>" data-name="<?php echo htmlspecialchars($p['plan_name']); ?>" <?php echo $p['is_default'] ? 'selected' : ''; ?>>
                        <?php echo $p['plan_name']; ?> (<?php echo number_format($p['retail_price']); ?> تومان)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium mb-1">حجم</label>
            <div class="flex" dir="ltr">
                <select name="volume_unit" id="volume_unit" class="border border-r-0 rounded-l p-2 bg-gray-100 text-sm font-bold outline-none focus:border-blue-500">
                    <option value="GB">GB</option>
                    <option value="MB">MB</option>
                </select>
                <input type="number" name="volume" id="volume" step="0.1" required min="0.1" value="1" class="w-full border rounded-r p-2 bg-gray-50 focus:border-blue-500 focus:outline-none text-left" dir="ltr">
            </div>
        </div>
        <div><label class="block text-sm font-medium mb-1">تخفیف ویژه (تومان)</label><input type="number" name="discount" value="0" class="w-full border rounded p-2 bg-yellow-50 font-bold focus:border-blue-500 focus:outline-none" placeholder="مبلغ تخفیف..."></div>
        
        <div class="lg:col-span-2">
            <label class="block text-sm font-medium mb-1 text-purple-700 font-bold">مبلغ واریزی مشتری (اختیاری)</label>
            <input type="number" name="paid_amount" placeholder="اگر مبلغی متفاوت از سیستم واریز شده وارد کنید..." class="w-full border border-purple-300 rounded p-2 bg-purple-50 placeholder-purple-300 focus:border-purple-500 focus:outline-none">
        </div>

        <div class="lg:col-span-4 flex justify-end mt-4 pt-4 border-t border-gray-100">
            <button type="submit" class="bg-blue-600 text-white px-8 py-3 rounded-lg font-bold hover:bg-blue-700 transition w-full md:w-auto shadow-md">ثبت در پایگاه داده</button>
        </div>
    </form>
</div>

<!-- لیست تراکنش‌ها -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 overflow-hidden">
    <h2 class="text-xl font-bold mb-4 text-gray-800">تراکنش‌های اخیر (دفتر کل)</h2>
    <div class="overflow-x-auto">
        <table id="txTable" class="w-full text-sm text-right text-gray-500">
            <thead class="bg-gray-100 text-gray-700">
                <tr>
                    <th class="px-4 py-3">تاریخ</th>
                    <th class="px-4 py-3">مشتری / اکانت</th>
                    <th class="px-4 py-3">سرویس</th>
                    <th class="px-4 py-3">واریزی</th>
                    <th class="px-4 py-3 text-green-700">سود خالص</th>
                    <?php if($isAdmin): ?><th class="px-4 py-3 text-red-600">ثبت‌کننده</th><?php endif; ?>
                    <th class="px-4 py-3 text-center">عملیات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($transactions as $tx): 
                    $displayProfit = $isAdmin ? ($tx['profit'] + $tx['admin_profit']) : $tx['profit']; 
                ?>
                <tr class="border-b hover:bg-gray-50">
                    <td class="px-4 py-3">
                        <span class="font-bold text-gray-800"><?php echo htmlspecialchars($tx['customer_name']); ?></span><br>
                        <span class="text-xs font-mono text-blue-600" dir="ltr"><?php echo htmlspecialchars($tx['account_username']); ?></span>
                        <?php if($tx['type'] == 'recharge') echo '<span class="text-[10px] bg-blue-100 text-blue-700 px-1 rounded ml-1">تمدید</span>'; ?>
                    </td>
                    <td class="px-4 py-3" dir="ltr"><?php echo htmlspecialchars($tx['plan']) . ' (' . $tx['volume'] . ' ' . ($tx['volume_unit'] ?? 'GB') . ')'; ?></td>
                    <td class="px-4 py-3 font-bold text-purple-700"><?php echo number_format($tx['paid_amount']); ?></td>
                    
                    <td class="px-4 py-3 font-bold <?php echo ($displayProfit < 0) ? 'text-red-600' : 'text-green-600'; ?>">
                        <?php echo number_format($displayProfit); ?>
                    </td>

                    <?php if($isAdmin): ?>
                        <td class="px-4 py-3"><span class="bg-gray-200 text-gray-800 px-2 py-1 rounded text-xs"><?php echo htmlspecialchars($tx['creator']); ?></span></td>
                    <?php endif; ?>
                    
                    <td class="px-4 py-3 text-center flex flex-wrap justify-center gap-1.5">
                        <?php if(!empty($tx['config_link'])): ?>
                            <button type="button" onclick="openSubModal('<?php echo htmlspecialchars($tx['config_link'], ENT_QUOTES); ?>')" class="bg-blue-100 text-blue-700 hover:bg-blue-200 px-2.5 py-1 rounded text-xs font-bold transition shadow-sm w-full md:w-auto text-center" title="مشاهده آنلاین مصرف">👁️ صفحه ساب</button>
                        <?php endif; ?>
                        
                        <button type="button" onclick="renewTx('<?php echo htmlspecialchars($tx['customer_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($tx['account_username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($tx['plan'], ENT_QUOTES); ?>', '<?php echo $tx['volume']; ?>', '<?php echo $tx['volume_unit'] ?? 'GB'; ?>')" class="bg-green-50 text-green-600 hover:bg-green-100 border border-green-200 px-2.5 py-1 rounded text-xs font-bold transition shadow-sm">تمدید</button>
                        <a href="edit_tx.php?id=<?php echo $tx['id']; ?>" class="bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-200 px-2.5 py-1 rounded text-xs font-bold transition shadow-sm">ویرایش</a>
                        <a href="?delete_id=<?php echo $tx['id']; ?>" onclick="return confirm('آیا از حذف قطعی این تراکنش مطمئن هستید؟');" class="bg-red-50 text-red-600 hover:bg-red-100 border border-red-200 px-2.5 py-1 rounded text-xs font-bold transition shadow-sm">حذف</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal نمایش ساب در آی‌فریم -->
<div id="subModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-50 transition-opacity opacity-0 px-2 sm:px-4">
    <div class="bg-white rounded-3xl shadow-2xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden transform scale-95 transition-transform" id="subModalContent">
        <div class="flex justify-between items-center p-4 sm:p-5 border-b border-gray-100 bg-gray-50 shrink-0">
            <h3 class="font-bold text-gray-800 text-lg flex items-center gap-2">
                <span class="text-2xl">🌐</span> اطلاعات لایو اشتراک
            </h3>
            <button onclick="closeSubModal()" class="text-gray-400 hover:text-red-500 text-4xl leading-none transition-colors">&times;</button>
        </div>
        <div class="flex-1 w-full bg-gray-100 relative">
            <div id="iframeLoading" class="absolute inset-0 flex flex-col items-center justify-center text-gray-400">
                <div class="text-5xl mb-3 animate-bounce">⏳</div>
                <div class="font-bold animate-pulse text-lg">در حال ارتباط با سرور...</div>
            </div>
            <!-- آی‌فریم لود کننده لینک -->
            <iframe id="subIframe" src="" class="w-full h-full border-none relative z-10" onload="document.getElementById('iframeLoading').style.display='none'"></iframe>
        </div>
    </div>
</div>

<!-- اسکریپت‌ها -->
<link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container--default .select2-selection--single { height: 42px; border-radius: 8px; border-color: #e5e7eb; background-color: #f9fafb; padding-top: 5px; }
    .select2-container { width: 100% !important; }
    .highlight-form { box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.3) !important; border-color: #3b82f6 !important; }
</style>

<script src="/vpnet-panel/assets/js/jquery.min.js"></script>
<script src="/vpnet-panel/assets/js/datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    $('#txTable').DataTable({
        "language": {
            "sEmptyTable": "هیچ داده‌ای در جدول وجود ندارد",
            "sSearch": "جستجو در دفتر کل:",
            "oPaginate": { "sNext": "بعدی", "sPrevious": "قبلی" },
            "sLengthMenu": "نمایش _MENU_ سطر"
        },
        "order": [],
        "pageLength": 25
    });

    function setupAjaxSelect(elementId, type) {
        $(elementId).select2({
            tags: true,
            placeholder: "جستجو یا تایپ جدید...",
            minimumInputLength: 2,
            ajax: {
                url: 'search_ajax.php',
                dataType: 'json',
                delay: 250,
                data: function (params) { return { term: params.term, type: type }; },
                processResults: function (data) { return data; }
            }
        });
    }

    setupAjaxSelect('#ajax_customer_name', 'customer_name');
    setupAjaxSelect('#ajax_account_username', 'account_username');
});

// توابع مربوط به مودال Iframe ساب
const subModal = document.getElementById('subModal');
const subModalContent = document.getElementById('subModalContent');
const subIframe = document.getElementById('subIframe');
const iframeLoading = document.getElementById('iframeLoading');

function openSubModal(url) {
    iframeLoading.style.display = 'flex';
    subIframe.src = url; // لود لینک داخل آی فریم
    subModal.classList.remove('hidden');
    subModal.classList.add('flex');
    setTimeout(() => {
        subModal.classList.remove('opacity-0');
        subModalContent.classList.remove('scale-95');
    }, 10);
}

function closeSubModal() {
    subModal.classList.add('opacity-0');
    subModalContent.classList.add('scale-95');
    setTimeout(() => {
        subModal.classList.add('hidden');
        subModal.classList.remove('flex');
        subIframe.src = ''; // برای جلوگیری از مصرف منابع مرورگر
    }, 300);
}

// بستن مودال با کلیک در فضای خالی
subModal.addEventListener('click', function(e) {
    if (e.target === subModal) closeSubModal();
});

// تابع جاوا اسکریپت برای انتقال اطلاعات به فرم جهت تمدید
function renewTx(cust, user, plan, vol, unit) {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    document.getElementById('formTitle').innerHTML = 'تمدید اکانت: <span class="text-blue-600" dir="ltr">' + user + '</span>';
    
    $('#tx_type').val('recharge');
    $('#volume').val(vol);
    if (unit) { $('#volume_unit').val(unit); }
    
    var custOption = new Option(cust, cust, true, true);
    $('#ajax_customer_name').append(custOption).trigger('change');
    
    var userOption = new Option(user, user, true, true);
    $('#ajax_account_username').append(userOption).trigger('change');
    
    $("#plan_id option").filter(function() { return $(this).data('name') == plan; }).prop('selected', true);

    $('#txFormContainer').addClass('highlight-form');
    setTimeout(function() {
        $('#txFormContainer').removeClass('highlight-form');
    }, 1500);
}
</script>

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