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

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$txId = $_GET['id'] ?? null;

if (!$txId) { die("تراکنشی انتخاب نشده است."); }

// دریافت اطلاعات فعلی تراکنش
$stmtCheck = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
$stmtCheck->execute([$txId]);
$tx = $stmtCheck->fetch();

if (!$tx || (!$isAdmin && $tx['user_id'] != $userId)) {
    die("شما دسترسی به ویرایش این تراکنش را ندارید.");
}

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') {
    $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);
    }

    // ۳. بروزرسانی تمامی فیلدها در دیتابیس
    $updateSql = "UPDATE transactions SET 
                    type=?, 
                    customer_name=?, 
                    account_username=?, 
                    plan=?, 
                    volume=?, 
                    volume_unit=?,
                    discount=?, 
                    bank_id=?, 
                    paid_amount=?, 
                    profit=?, 
                    admin_profit=?, 
                    date_shamsi=? 
                  WHERE id=?";
    
    $stmtUpdate = $pdo->prepare($updateSql);
    $stmtUpdate->execute([
        $type, 
        $customerName, 
        $accountUsername, 
        $planName, 
        $volume, 
        $volumeUnit,
        $discount, 
        $bankId, 
        $paidAmount, 
        $operatorProfit, 
        $adminProfit, 
        $dateShamsi, 
        $txId
    ]);
    
    header("Location: transactions.php?msg=edited");
    exit;
}

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

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    /* استایل‌های عمومی فیلد Select2 */
    .select2-container--default .select2-selection--single { 
        height: 46px; 
        border-radius: 8px; 
        border-color: #e5e7eb; 
        background-color: #f9fafb; 
        padding-top: 8px; 
    }
    .select2-container { width: 100% !important; }
    
    /* استایل سفارشی و بزرگ‌نمایی دکمه ضربدر (پاک کردن) */
    .select2-container--default .select2-selection--single .select2-selection__clear {
        position: absolute;
        left: 35px; /* فاصله دادن از فلش دراپ‌داون */
        right: auto;
        top: -30%;
        transform: translateY(-50%);
        font-size: 18px;
        font-weight: bold;
        color: #ef4444; /* رنگ قرمز */
        background-color: #fee2e2; /* پس‌زمینه قرمز ملایم */
        width: 26px;
        height: 26px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        line-height: 1;
        padding-bottom: 2px;
        transition: all 0.2s;
        z-index: 10;
    }
    .select2-container--default .select2-selection--single .select2-selection__clear:hover {
        background-color: #ef4444; /* تغییر رنگ در حالت هاور */
        color: #ffffff;
    }

    /* تنظیم مکان دقیق فلش (Arrow) برای جلوگیری از تداخل */
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        left: 5px !important;
        right: auto !important;
        top: 9px !important;
    }
</style>

<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 max-w-4xl mx-auto border-t-4 border-t-blue-500">
    <div class="flex justify-between items-center mb-6 border-b pb-4">
        <h2 class="text-xl font-bold text-gray-800">ویرایش کامل تراکنش: <span dir="ltr" class="text-blue-600"><?php echo htmlspecialchars($tx['account_username']); ?></span></h2>
        <a href="transactions.php" class="text-sm bg-gray-200 px-4 py-2 rounded-lg font-bold hover:bg-gray-300 transition">بازگشت به لیست</a>
    </div>
    
    <form method="POST" action="" class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
            <label class="block text-sm font-bold mb-1 text-gray-700">نوع تراکنش</label>
            <select name="tx_type" class="w-full border rounded-lg p-2.5 bg-gray-50 focus:ring-2 focus:ring-blue-200 focus:outline-none">
                <option value="new" <?php if($tx['type']=='new') echo 'selected'; ?>>فروش جدید</option>
                <option value="recharge" <?php if($tx['type']=='recharge') echo 'selected'; ?>>تمدیدی</option>
            </select>
        </div>

        <div>
            <label class="block text-sm font-bold mb-1 text-gray-700">تاریخ (شمسی)</label>
            <input type="text" name="tx_date" required class="w-full border rounded-lg p-2.5 bg-gray-50 text-left font-bold" value="<?php echo $tx['date_shamsi']; ?>" dir="ltr">
        </div>
        
        <div>
            <label class="block text-sm font-bold mb-1 text-gray-700">نام مشتری</label>
            <select name="customer_name" id="ajax_customer_name" class="w-full border rounded-lg p-2.5 bg-gray-50">
                <option value="<?php echo htmlspecialchars($tx['customer_name']); ?>" selected="selected">
                    <?php echo htmlspecialchars($tx['customer_name']); ?>
                </option>
            </select>
        </div>

        <div>
            <label class="block text-sm font-bold mb-1 text-red-600">نام کاربری (اکانت)</label>
            <select name="account_username" id="ajax_account_username" required class="w-full border rounded-lg p-2.5 bg-gray-50 text-left" dir="ltr">
                <option value="<?php echo htmlspecialchars($tx['account_username']); ?>" selected="selected">
                    <?php echo htmlspecialchars($tx['account_username']); ?>
                </option>
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-bold mb-1 text-gray-700">حساب واریزی</label>
            <select name="bank_id" class="w-full border rounded-lg p-2.5 bg-gray-50 focus:ring-2 focus:ring-blue-200 focus:outline-none">
                <option value="">نامشخص / نقدی</option>
                <?php foreach($banks as $b): ?>
                    <option value="<?php echo $b['id']; ?>" <?php if($tx['bank_id']==$b['id']) echo 'selected'; ?>><?php echo $b['bank_name']; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-bold mb-1 text-gray-700">نوع سرویس (طرح)</label>
            <select name="plan_id" class="w-full border rounded-lg p-2.5 bg-gray-50 focus:ring-2 focus:ring-blue-200 focus:outline-none">
                <?php foreach($plans as $p): ?>
                    <option value="<?php echo $p['id']; ?>" <?php echo ($tx['plan'] == $p['plan_name']) ? '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-bold mb-1 text-gray-700">حجم</label>
            <div class="flex" dir="ltr">
                <select name="volume_unit" class="border border-r-0 rounded-l-lg p-2.5 bg-gray-100 text-sm font-bold outline-none focus:ring-2 focus:ring-blue-200 cursor-pointer">
                    <option value="GB" <?php echo (!isset($tx['volume_unit']) || $tx['volume_unit'] !== 'MB') ? 'selected' : ''; ?>>GB</option>
                    <option value="MB" <?php echo (isset($tx['volume_unit']) && $tx['volume_unit'] === 'MB') ? 'selected' : ''; ?>>MB</option>
                </select>
                <input type="number" name="volume" step="0.1" required min="0.1" class="w-full border rounded-r-lg p-2.5 bg-gray-50 focus:ring-2 focus:ring-blue-200 focus:outline-none text-left" value="<?php echo $tx['volume']; ?>" dir="ltr">
            </div>
        </div>
        
        <div>
            <label class="block text-sm font-bold mb-1 text-amber-600">تخفیف ویژه (تومان)</label>
            <input type="number" name="discount" class="w-full border rounded-lg p-2.5 bg-yellow-50 font-bold focus:ring-2 focus:ring-yellow-200 focus:outline-none" value="<?php echo $tx['discount']; ?>">
        </div>
        
        <div class="md:col-span-2">
            <label class="block text-sm font-bold mb-1 text-purple-700">مبلغ واریزی دستی (اختیاری)</label>
            <input type="number" name="paid_amount" class="w-full border border-purple-300 bg-purple-50 rounded-lg p-3 font-black text-purple-800 focus:ring-2 focus:ring-purple-200 focus:outline-none" value="<?php echo $tx['paid_amount']; ?>" placeholder="خالی بگذارید تا طبق فرمول محاسبه شود...">
        </div>
        
        <div class="md:col-span-2 mt-4 pt-4 border-t border-gray-100">
            <button type="submit" class="w-full bg-blue-600 text-white py-3.5 rounded-xl font-bold hover:bg-blue-700 shadow-lg shadow-blue-100 transition-all">بروزرسانی نهایی و محاسبه مجدد سود</button>
        </div>
    </form>
</div>

<script src="/vpnet-panel/assets/js/jquery.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() {
    function setupAjaxSelect(elementId, type) {
        $(elementId).select2({
            tags: true,
            placeholder: "پاک کنید و نام جدید را تایپ کنید...",
            allowClear: true,
            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');
});
</script>

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