


<?php $__env->startSection('title', 'แก้ไขอัตราค่าคอมมิชชั่น - ระบบจัดการค่าคอมมิชชั่น'); ?>

<?php $__env->startSection('content'); ?>
<div class="content-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="page-title">แก้ไขอัตราค่าคอมมิชชั่น</h1>
                <p class="page-subtitle">แก้ไขอัตรา: <?php echo e($commissionRate->warehouse_code); ?> - <?php echo e($commissionRate->vehicle_type); ?> (ขั้นที่ <?php echo e($commissionRate->tier); ?>)</p>
            </div>
            <a href="<?php echo e(route('admin.commission-rates.index')); ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i>กลับไปรายการ
            </a>
        </div>
    </div>

    <!-- Form Container -->
    <div class="table-container">
        <div class="table-header">
            <h3 class="table-title">ข้อมูลอัตราค่าคอมมิชชั่น</h3>
        </div>
        
        <div class="p-6">
            <form method="POST" action="<?php echo e(route('admin.commission-rates.update', $commissionRate)); ?>" id="commissionForm">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- คลังสินค้า -->
                    <div class="form-group">
                        <label for="warehouse_code" class="form-label">คลังสินค้า <span class="text-red-500">*</span></label>
                        <select id="warehouse_code" name="warehouse_code" 
                                class="form-control <?php $__errorArgs = ['warehouse_code'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                            <option value="">เลือกคลังสินค้า</option>
                            <?php $__currentLoopData = $warehouses ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $warehouse): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($warehouse->code); ?>" 
                                        <?php echo e(old('warehouse_code', $commissionRate->warehouse_code) === $warehouse->code ? 'selected' : ''); ?>>
                                    <?php echo e($warehouse->code); ?> - <?php echo e($warehouse->name); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['warehouse_code'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- ประเภทรถ -->
                    <div class="form-group">
                        <label for="vehicle_type" class="form-label">ประเภทรถ <span class="text-red-500">*</span></label>
                        <select id="vehicle_type" name="vehicle_type" 
                                class="form-control <?php $__errorArgs = ['vehicle_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                            <option value="">เลือกประเภทรถ</option>
                            <option value="2wheel" <?php echo e(old('vehicle_type', $commissionRate->vehicle_type) === '2wheel' ? 'selected' : ''); ?>>รถ 2 ล้อ</option>
                            <option value="4wheel" <?php echo e(old('vehicle_type', $commissionRate->vehicle_type) === '4wheel' ? 'selected' : ''); ?>>รถ 4 ล้อ</option>
                        </select>
                        <?php $__errorArgs = ['vehicle_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- ขั้น -->
                    <div class="form-group">
                        <label for="tier" class="form-label">ขั้น <span class="text-red-500">*</span></label>
                        <input type="number" id="tier" name="tier" 
                               value="<?php echo e(old('tier', $commissionRate->tier)); ?>" 
                               class="form-control <?php $__errorArgs = ['tier'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                               min="1" placeholder="เช่น 1, 2, 3" required>
                        <?php $__errorArgs = ['tier'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <p class="mt-1 text-sm text-gray-500">ขั้นต้องไม่ซ้ำกันสำหรับคลังและประเภทรถเดียวกัน</p>
                    </div>

                    <!-- จำนวนพัสดุขั้นต่ำ -->
                    <div class="form-group">
                        <label for="min_packages" class="form-label">จำนวนพัสดุขั้นต่ำ <span class="text-red-500">*</span></label>
                        <input type="number" id="min_packages" name="min_packages" 
                               value="<?php echo e(old('min_packages', $commissionRate->min_packages)); ?>" 
                               class="form-control <?php $__errorArgs = ['min_packages'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                               min="0" placeholder="เช่น 1, 50, 100" required>
                        <?php $__errorArgs = ['min_packages'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- จำนวนพัสดุสูงสุด -->
                    <div class="form-group">
                        <label for="max_packages" class="form-label">จำนวนพัสดุสูงสุด</label>
                        <input type="number" id="max_packages" name="max_packages" 
                               value="<?php echo e(old('max_packages', $commissionRate->max_packages)); ?>" 
                               class="form-control <?php $__errorArgs = ['max_packages'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                               min="1" placeholder="เว้นว่างหากไม่จำกัด">
                        <?php $__errorArgs = ['max_packages'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <p class="mt-1 text-sm text-gray-500">เว้นว่างไว้หากเป็นขั้นสุดท้าย (ไม่จำกัดจำนวนสูงสุด)</p>
                    </div>

                    <!-- อัตราค่าคอมมิชชั่นต่อชิ้น -->
                    <div class="form-group">
                        <label for="rate_per_package" class="form-label">อัตราค่าคอมมิชชั่นต่อชิ้น (บาท) <span class="text-red-500">*</span></label>
                        <input type="number" id="rate_per_package" name="rate_per_package" 
                               value="<?php echo e(old('rate_per_package', $commissionRate->rate_per_package)); ?>" 
                               class="form-control <?php $__errorArgs = ['rate_per_package'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                               step="0.01" min="0" placeholder="เช่น 0, 8, 10" required>
                        <?php $__errorArgs = ['rate_per_package'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- สถานะ -->
                    <div class="form-group">
                        <label for="is_active" class="form-label">สถานะ</label>
                        <div class="flex items-center space-x-3">
                            <label class="flex items-center">
                                <input type="radio" name="is_active" value="1" 
                                       <?php echo e(old('is_active', $commissionRate->is_active) ? 'checked' : ''); ?>

                                       class="text-orange-600 focus:ring-orange-500">
                                <span class="ml-2">ใช้งานอยู่</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="is_active" value="0" 
                                       <?php echo e(!old('is_active', $commissionRate->is_active) ? 'checked' : ''); ?>

                                       class="text-orange-600 focus:ring-orange-500">
                                <span class="ml-2">ปิดใช้งาน</span>
                            </label>
                        </div>
                    </div>

                    <!-- ตัวอย่างการคำนวณ -->
                    <div class="form-group md:col-span-2">
                        <label class="form-label">ตัวอย่างการคำนวณ</label>
                        <div id="calculation-preview" class="p-4 bg-gray-50 rounded-lg text-sm">
                            <div class="text-gray-600">กรอกข้อมูลเพื่อดูตัวอย่างการคำนวณ</div>
                        </div>
                    </div>

                    <!-- ข้อมูลเพิ่มเติม -->
                    <div class="form-group">
                        <label class="form-label">สร้างเมื่อ</label>
                        <div class="p-3 bg-gray-50 rounded-lg text-gray-700">
                            <?php echo e($commissionRate->created_at ? $commissionRate->created_at->format('d/m/Y H:i:s') : '-'); ?>

                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">อัปเดตล่าสุด</label>
                        <div class="p-3 bg-gray-50 rounded-lg text-gray-700">
                            <?php echo e($commissionRate->updated_at ? $commissionRate->updated_at->format('d/m/Y H:i:s') : '-'); ?>

                        </div>
                    </div>
                </div>

                <!-- Existing Rates Preview -->
                <div id="existing-rates" class="mt-6" style="display: none;">
                    <h4 class="font-semibold text-gray-800 mb-3">อัตราอื่นๆ ที่มีอยู่</h4>
                    <div id="existing-rates-content" class="space-y-2">
                        <!-- จะแสดงผ่าน JavaScript -->
                    </div>
                </div>

                <!-- Submit Buttons -->
                <div class="flex justify-between items-center mt-8 pt-6 border-t border-gray-200">
                    <div class="flex space-x-3">
                        <button type="button" onclick="deleteRate()" class="btn btn-danger">
                            <i class="fas fa-trash"></i>ลบอัตราค่าคอมมิشชั่น
                        </button>
                    </div>
                    
                    <div class="flex space-x-3">
                        <a href="<?php echo e(route('admin.commission-rates.index')); ?>" class="btn btn-secondary">
                            <i class="fas fa-times"></i>ยกเลิก
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i>บันทึกการเปลี่ยนแปลง
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Real-time calculation preview
function updateCalculationPreview() {
    const minPackages = parseInt(document.getElementById('min_packages').value) || 0;
    const maxPackages = parseInt(document.getElementById('max_packages').value) || null;
    const rate = parseFloat(document.getElementById('rate_per_package').value) || 0;
    
    if (minPackages > 0 && rate >= 0) {
        const rangeText = maxPackages ? `${minPackages} - ${maxPackages}` : `${minPackages}+`;
        const exampleCount = maxPackages ? Math.min(minPackages + 10, maxPackages) : minPackages + 10;
        const calculatedPackages = exampleCount >= minPackages ? exampleCount - minPackages + 1 : 0;
        const exampleCommission = calculatedPackages * rate;
        
        document.getElementById('calculation-preview').innerHTML = `
            <div class="space-y-2">
                <div><strong>ช่วงพัสดุ:</strong> ${rangeText} ชิ้น</div>
                <div><strong>อัตราต่อชิ้น:</strong> ${rate.toFixed(2)} บาท</div>
                <div class="border-t pt-2">
                    <div class="text-orange-600"><strong>ตัวอย่าง:</strong> หากมีพัสดุ ${exampleCount} ชิ้น</div>
                    <div>พัสดุในขั้นนี้: ${calculatedPackages} ชิ้น</div>
                    <div>ค่าคอมมิชชั่น: ${exampleCommission.toFixed(2)} บาท</div>
                </div>
            </div>
        `;
    } else {
        document.getElementById('calculation-preview').innerHTML = '<div class="text-gray-600">กรอกข้อมูลเพื่อดูตัวอย่างการคำนวณ</div>';
    }
}

// Load existing rates when warehouse and vehicle type are selected
function loadExistingRates() {
    const warehouseCode = document.getElementById('warehouse_code').value;
    const vehicleType = document.getElementById('vehicle_type').value;
    
    if (warehouseCode && vehicleType) {
        fetch(`<?php echo e(route('admin.commission-rates.existing')); ?>?warehouse_code=${warehouseCode}&vehicle_type=${vehicleType}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.rates.length > 0) {
                    let html = '';
                    data.rates.forEach(rate => {
                        // Skip current rate
                        if (rate.id === <?php echo e($commissionRate->id); ?>) return;
                        
                        const rangeText = rate.max_packages ? `${rate.min_packages} - ${rate.max_packages}` : `${rate.min_packages}+`;
                        const statusClass = rate.is_active ? 'text-green-600' : 'text-red-600';
                        const statusText = rate.is_active ? 'ใช้งานอยู่' : 'ปิดใช้งาน';
                        
                        html += `
                            <div class="flex justify-between items-center p-3 bg-white rounded-lg border">
                                <div>
                                    <span class="font-medium">ขั้นที่ ${rate.tier}:</span> 
                                    ${rangeText} ชิ้น = ${rate.rate_per_package} บาท/ชิ้น
                                </div>
                                <span class="${statusClass} text-sm">${statusText}</span>
                            </div>
                        `;
                    });
                    
                    if (html) {
                        document.getElementById('existing-rates-content').innerHTML = html;
                        document.getElementById('existing-rates').style.display = 'block';
                    } else {
                        document.getElementById('existing-rates').style.display = 'none';
                    }
                } else {
                    document.getElementById('existing-rates').style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error loading existing rates:', error);
                document.getElementById('existing-rates').style.display = 'none';
            });
    } else {
        document.getElementById('existing-rates').style.display = 'none';
    }
}

// Event listeners
document.getElementById('min_packages').addEventListener('input', updateCalculationPreview);
document.getElementById('max_packages').addEventListener('input', updateCalculationPreview);
document.getElementById('rate_per_package').addEventListener('input', updateCalculationPreview);

document.getElementById('warehouse_code').addEventListener('change', loadExistingRates);
document.getElementById('vehicle_type').addEventListener('change', loadExistingRates);

// Form validation
document.getElementById('commissionForm').addEventListener('submit', function(e) {
    const minPackages = parseInt(document.getElementById('min_packages').value);
    const maxPackages = parseInt(document.getElementById('max_packages').value);
    
    if (maxPackages && maxPackages <= minPackages) {
        e.preventDefault();
        Swal.fire('ข้อผิดพลาด', 'จำนวนพัสดุสูงสุดต้องมากกว่าจำนวนขั้นต่ำ', 'error');
        return false;
    }
});

// Delete rate function
function deleteRate() {
    Swal.fire({
        title: 'ยืนยันการลบ',
        text: 'คุณต้องการลบอัตราค่าคอมมิชชั่นนี้หรือไม่? การดำเนินการนี้ไม่สามารถยกเลิกได้',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#EF4444',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'ลบ',
        cancelButtonText: 'ยกเลิก'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`<?php echo e(route('admin.commission-rates.destroy', $commissionRate)); ?>`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('สำเร็จ!', data.message, 'success').then(() => {
                        window.location.href = '<?php echo e(route('admin.commission-rates.index')); ?>';
                    });
                } else {
                    Swal.fire('เกิดข้อผิดพลาด!', data.message, 'error');
                }
            })
            .catch(error => {
                Swal.fire('เกิดข้อผิดพลาด!', 'ไม่สามารถลบอัตราได้', 'error');
            });
        }
    });
}

// Load existing rates on page load
document.addEventListener('DOMContentLoaded', function() {
    loadExistingRates();
    updateCalculationPreview();
});
</script>

<style>
.btn-secondary {
    background: #6B7280;
    color: white;
}
.btn-secondary:hover {
    background: #4B5563;
}
.btn-danger {
    background: #EF4444;
    color: white;
}
.btn-danger:hover {
    background: #DC2626;
}
</style>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/zlerpszw/public_html/www.crs.niendsitekungz.com/resources/views/admin/commission-rates/edit.blade.php ENDPATH**/ ?>