

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

<?php $__env->startSection('content'); ?>
<div class="content-container">
    <!-- Enhanced Page Header -->
    <div class="page-header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="page-title">
                    <i class="fas fa-plus-circle text-orange-500 mr-3"></i>
                    เพิ่มอัตราค่าคอมมิชชั่น
                </h1>
                <p class="page-subtitle">กำหนดอัตราค่าคอมมิชชั่นใหม่สำหรับคลังและประเภทรถ</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>

    <!-- Enhanced Form Container -->
    <div class="modern-card">
        <div class="modern-card-header">
            <h3 class="modern-card-title">
                <i class="fas fa-percentage text-green-500"></i>
                ข้อมูลอัตราค่าคอมมิชชั่น
            </h3>
        </div>
        
        <div class="modern-card-body">
            <form method="POST" action="<?php echo e(route('admin.commission-rates.store')); ?>" id="commissionForm">
                <?php echo csrf_field(); ?>
                
                <div class="form-grid">
                    <!-- คลังสินค้า -->
                    <div class="form-group">
                        <label for="warehouse_code" class="form-label required">คลังสินค้า</label>
                        <div class="input-with-icon">
                            <i class="fas fa-warehouse input-icon"></i>
                            <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', $selectedWarehouse ?? '') === $warehouse->code ? 'selected' : ''); ?>>
                                        <?php echo e($warehouse->code); ?> - <?php echo e($warehouse->name); ?>

                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                        <?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="error-message"><?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 required">ประเภทรถ</label>
                        <div class="input-with-icon">
                            <i class="fas fa-truck input-icon"></i>
                            <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') === '2wheel' ? 'selected' : ''); ?>>
                                    🏍️ รถ 2 ล้อ
                                </option>
                                <option value="4wheel" <?php echo e(old('vehicle_type') === '4wheel' ? 'selected' : ''); ?>>
                                    🚚 รถ 4 ล้อ
                                </option>
                            </select>
                        </div>
                        <?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="error-message"><?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 required">ขั้น</label>
                        <div class="input-with-icon">
                            <i class="fas fa-layer-group input-icon"></i>
                            <input type="number" id="tier" name="tier" value="<?php echo e(old('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>
                        </div>
                        <?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="error-message"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <p class="help-text">ขั้นต้องไม่ซ้ำกันสำหรับคลังและประเภทรถเดียวกัน</p>
                    </div>

                    <!-- จำนวนพัสดุขั้นต่ำ -->
                    <div class="form-group">
                        <label for="min_packages" class="form-label required">จำนวนพัสดุขั้นต่ำ</label>
                        <div class="input-with-icon">
                            <i class="fas fa-box input-icon"></i>
                            <input type="number" id="min_packages" name="min_packages" value="<?php echo e(old('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>
                        </div>
                        <?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="error-message"><?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>
                        <div class="input-with-icon">
                            <i class="fas fa-boxes input-icon"></i>
                            <input type="number" id="max_packages" name="max_packages" value="<?php echo e(old('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="เว้นว่างหากไม่จำกัด">
                        </div>
                        <?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="error-message"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <p class="help-text">เว้นว่างไว้หากเป็นขั้นสุดท้าย (ไม่จำกัดจำนวนสูงสุด)</p>
                    </div>

                    <!-- อัตราค่าคอมมิชชั่นต่อชิ้น -->
                    <div class="form-group">
                        <label for="rate_per_package" class="form-label required">อัตราค่าคอมมิชชั่นต่อชิ้น (บาท)</label>
                        <div class="input-with-icon">
                            <i class="fas fa-coins input-icon"></i>
                            <input type="number" id="rate_per_package" name="rate_per_package" value="<?php echo e(old('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>
                        </div>
                        <?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="error-message"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- สถานะ -->
                    <div class="form-group">
                        <label class="form-label">สถานะ</label>
                        <div class="radio-group">
                            <label class="radio-option active">
                                <input type="radio" name="is_active" value="1" 
                                       <?php echo e(old('is_active', '1') === '1' ? 'checked' : ''); ?>>
                                <span class="radio-custom"></span>
                                <span class="radio-label">
                                    <i class="fas fa-check-circle text-green-500"></i>
                                    ใช้งานอยู่
                                </span>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="is_active" value="0" 
                                       <?php echo e(old('is_active') === '0' ? 'checked' : ''); ?>>
                                <span class="radio-custom"></span>
                                <span class="radio-label">
                                    <i class="fas fa-times-circle text-red-500"></i>
                                    ปิดใช้งาน
                                </span>
                            </label>
                        </div>
                    </div>

                    <!-- ตัวอย่างการคำนวณ -->
                    <div class="form-group full-width">
                        <label class="form-label">ตัวอย่างการคำนวณ</label>
                        <div class="calculation-preview-card">
                            <div class="calculation-header">
                                <i class="fas fa-calculator"></i>
                                <span>ตัวอย่างการคำนวณค่าคอมมิชชั่น</span>
                            </div>
                            <div id="calculation-preview" class="calculation-content">
                                <div class="text-gray-600">กรอกข้อมูลเพื่อดูตัวอย่างการคำนวณ</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Existing Rates Preview -->
                <div id="existing-rates" class="existing-rates-section" style="display: none;">
                    <h4 class="existing-rates-title">
                        <i class="fas fa-list-alt text-blue-500"></i>
                        อัตราที่มีอยู่แล้ว
                    </h4>
                    <div id="existing-rates-content" class="existing-rates-content">
                        <!-- จะแสดงผ่าน JavaScript -->
                    </div>
                </div>

                <!-- Enhanced Submit Section -->
                <div class="form-actions">
                    <div class="actions-left">
                        <div class="progress-indicator">
                            <div class="progress-step active">
                                <i class="fas fa-percentage"></i>
                                <span>ข้อมูลอัตรา</span>
                            </div>
                            <div class="progress-step">
                                <i class="fas fa-calculator"></i>
                                <span>ทดสอบการคำนวณ</span>
                            </div>
                            <div class="progress-step">
                                <i class="fas fa-check"></i>
                                <span>เสร็จสิ้น</span>
                            </div>
                        </div>
                    </div>
                    <div class="actions-right">
                        <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" id="submitBtn">
                            <i class="fas fa-save"></i>บันทึก
                            <span class="btn-loading" style="display: none;">
                                <i class="fas fa-spinner fa-spin"></i>
                            </span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Enhanced Styles -->
<style>
/* Fix Horizontal Scrollbar */
* {
    box-sizing: border-box;
}

.content-container {
    max-width: 100vw;
    overflow-x: hidden;
    padding-left: 1rem;
    padding-right: 1rem;
    box-sizing: border-box;
}

/* Form Grid Layout */
.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    margin-bottom: 2rem;
}

.form-group.full-width {
    grid-column: 1 / -1;
}

/* Enhanced Form Elements */
.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-label {
    font-weight: 600;
    color: var(--dark-gray);
    font-size: 0.95rem;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.form-label.required::after {
    content: '*';
    color: #ef4444;
    font-weight: bold;
}

.input-with-icon {
    position: relative;
    display: flex;
    align-items: center;
}

.input-icon {
    position: absolute;
    left: 1rem;
    color: var(--gray);
    font-size: 1rem;
    z-index: 1;
}

.form-control {
    width: 100%;
    padding: 1rem 1.25rem 1rem 3rem;
    border: 2px solid var(--medium-gray);
    border-radius: var(--radius-lg);
    font-family: inherit;
    font-size: 1rem;
    transition: var(--transition-fast);
    background: var(--white);
    line-height: 1.5;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary-orange);
    box-shadow: 0 0 0 4px rgba(255, 107, 53, 0.1);
    transform: translateY(-1px);
}

.form-control::placeholder {
    color: var(--gray);
    opacity: 0.7;
}

/* Radio Group Styling */
.radio-group {
    display: flex;
    gap: 1.5rem;
    margin-top: 0.5rem;
}

.radio-option {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    cursor: pointer;
    padding: 0.75rem 1rem;
    border: 2px solid var(--medium-gray);
    border-radius: var(--radius-md);
    transition: var(--transition-fast);
    flex: 1;
    position: relative;
}

.radio-option:hover {
    border-color: var(--primary-orange);
    background: rgba(255, 107, 53, 0.02);
}

.radio-option.active {
    border-color: var(--primary-orange);
    background: rgba(255, 107, 53, 0.05);
}

.radio-option input[type="radio"] {
    display: none;
}

.radio-custom {
    width: 20px;
    height: 20px;
    border: 2px solid var(--medium-gray);
    border-radius: 50%;
    position: relative;
    transition: var(--transition-fast);
}

.radio-option input[type="radio"]:checked + .radio-custom {
    border-color: var(--primary-orange);
    background: var(--primary-orange);
}

.radio-option input[type="radio"]:checked + .radio-custom::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8px;
    height: 8px;
    background: white;
    border-radius: 50%;
}

.radio-label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 500;
    color: var(--dark-gray);
}

/* Calculation Preview Card */
.calculation-preview-card {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 1px solid #bae6fd;
    border-radius: var(--radius-lg);
    overflow: hidden;
}

.calculation-header {
    background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
    color: white;
    padding: 1rem 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-weight: 600;
}

.calculation-content {
    padding: 1.5rem;
    font-size: 0.95rem;
}

/* Existing Rates Section */
.existing-rates-section {
    margin-top: 2rem;
    padding-top: 2rem;
    border-top: 2px solid var(--medium-gray);
}

.existing-rates-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--dark-gray);
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.existing-rates-content {
    display: grid;
    gap: 0.75rem;
}

.existing-rate-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    background: white;
    border: 1px solid var(--medium-gray);
    border-radius: var(--radius-md);
    transition: var(--transition-fast);
}

.existing-rate-item:hover {
    border-color: var(--primary-orange);
    background: rgba(255, 107, 53, 0.02);
    transform: translateY(-1px);
}

.existing-rate-info {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.existing-rate-tier {
    background: var(--primary-gradient);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: var(--radius-full);
    font-weight: 600;
    font-size: 0.875rem;
}

.existing-rate-details {
    font-size: 0.95rem;
    color: var(--dark-gray);
}

.existing-rate-status {
    font-size: 0.875rem;
    font-weight: 500;
}

.existing-rate-status.active {
    color: #059669;
}

.existing-rate-status.inactive {
    color: #dc2626;
}

/* Error Message Styling */
.error-message {
    color: #ef4444;
    font-size: 0.875rem;
    margin-top: 0.25rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.error-message::before {
    content: '⚠';
    color: #ef4444;
}

/* Help Text Styling */
.help-text {
    color: var(--gray);
    font-size: 0.875rem;
    margin-top: 0.25rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.help-text::before {
    content: 'ℹ';
    color: #3b82f6;
    font-weight: bold;
}

/* Form Actions */
.form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 2rem;
    border-top: 2px solid var(--medium-gray);
    margin-top: 2rem;
}

.actions-left {
    flex: 1;
}

.actions-right {
    display: flex;
    gap: 1rem;
}

/* Progress Indicator */
.progress-indicator {
    display: flex;
    gap: 2rem;
}

.progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    opacity: 0.4;
    transition: var(--transition-fast);
}

.progress-step.active {
    opacity: 1;
}

.progress-step i {
    width: 40px;
    height: 40px;
    background: #e5e7eb;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
    color: #6b7280;
    transition: var(--transition-fast);
}

.progress-step.active i {
    background: var(--primary-gradient);
    color: white;
}

.progress-step span {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--gray);
    text-align: center;
}

.progress-step.active span {
    color: var(--dark-gray);
    font-weight: 600;
}

/* Button Enhancements */
.btn {
    position: relative;
    overflow: hidden;
}

.btn-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.btn.loading .btn-loading {
    display: block;
}

.btn.loading i:not(.btn-loading i) {
    opacity: 0;
}

.btn-secondary {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    color: white;
    border: 2px solid transparent;
}

.btn-secondary:hover {
    background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
}

/* Responsive Design */
@media (max-width: 1024px) {
    .form-grid {
        grid-template-columns: 1fr;
        gap: 1.5rem;
    }
    
    .progress-indicator {
        display: none;
    }
    
    .form-actions {
        flex-direction: column;
        gap: 1rem;
        align-items: stretch;
    }
    
    .actions-right {
        width: 100%;
        justify-content: center;
    }
}

@media (max-width: 768px) {
    .content-container {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
    }
    
    .radio-group {
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .radio-option {
        justify-content: flex-start;
    }
    
    .form-control {
        padding: 0.875rem 1rem 0.875rem 2.75rem;
    }
    
    .input-icon {
        left: 0.875rem;
        font-size: 0.9rem;
    }
    
    .calculation-header {
        padding: 0.875rem 1.25rem;
        font-size: 0.95rem;
    }
    
    .calculation-content {
        padding: 1.25rem;
    }
}

@media (max-width: 480px) {
    .content-container {
        padding-left: 0.25rem;
        padding-right: 0.25rem;
    }
    
    .form-grid {
        gap: 1rem;
    }
    
    .actions-right {
        flex-direction: column;
    }
    
    .btn {
        width: 100%;
        justify-content: center;
    }
    
    .existing-rate-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.75rem;
    }
    
    .existing-rate-status {
        align-self: flex-end;
    }
}
</style>

<!-- Enhanced JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Enhanced functionality
document.addEventListener('DOMContentLoaded', function() {
    initializeForm();
    setupValidation();
    setupInteractions();
});

// Initialize form
function initializeForm() {
    // Radio button interactions
    const radioOptions = document.querySelectorAll('.radio-option');
    radioOptions.forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio) {
                radio.checked = true;
                updateRadioStates();
            }
        });
    });
    
    // Initial radio state
    updateRadioStates();
}

// Setup form validation
function setupValidation() {
    const form = document.getElementById('commissionForm');
    const submitBtn = document.getElementById('submitBtn');
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            submitForm();
        }
    });
    
    // Real-time validation
    const inputs = form.querySelectorAll('input[required], select[required]');
    inputs.forEach(input => {
        input.addEventListener('blur', () => validateField(input));
        input.addEventListener('input', () => clearFieldError(input));
        input.addEventListener('change', () => clearFieldError(input));
    });
}

// Setup interactions
function setupInteractions() {
    // Form field focus effects
    const formControls = document.querySelectorAll('.form-control');
    formControls.forEach(control => {
        control.addEventListener('focus', function() {
            this.parentElement.classList.add('focused');
        });
        
        control.addEventListener('blur', function() {
            this.parentElement.classList.remove('focused');
        });
    });
}

// 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="commission-tier-box">
                <ul class="commission-tier-list">
                    <li class="commission-tier-item">
                        <span class="tier-count">ขั้นนี้</span>
                        <span class="tier-label">:</span>
                        <span class="tier-range">${rangeText} ชิ้น</span>
                        <span class="tier-mult">×</span>
                        <span class="tier-rate">${rate.toFixed(2)}</span>
                        <span class="tier-currency">บาท/ชิ้น</span>
                    </li>
                </ul>
                
                <div class="mt-4 p-3 bg-orange-50 rounded-lg">
                    <div class="commission-total">
                        <i class="fas fa-calculator"></i>
                        <span class="label">ตัวอย่าง: หากมีพัสดุ ${exampleCount} ชิ้น</span>
                        <div class="mt-2">
                            <div>พัสดุในขั้นนี้: <strong>${calculatedPackages} ชิ้น</strong></div>
                            <div>ค่าคอมมิชชั่น: <strong class="text-orange-600">${exampleCommission.toFixed(2)} บาท</strong></div>
                        </div>
                    </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 => {
                        const rangeText = rate.max_packages ? `${rate.min_packages} - ${rate.max_packages}` : `${rate.min_packages}+`;
                        const statusClass = rate.is_active ? 'active' : 'inactive';
                        const statusText = rate.is_active ? 'ใช้งานอยู่' : 'ปิดใช้งาน';
                        
                        html += `
                            <div class="existing-rate-item">
                                <div class="existing-rate-info">
                                    <div class="existing-rate-tier">ขั้นที่ ${rate.tier}</div>
                                    <div class="existing-rate-details">
                                        ${rangeText} ชิ้น = ${rate.rate_per_package} บาท/ชิ้น
                                    </div>
                                </div>
                                <div class="existing-rate-status ${statusClass}">${statusText}</div>
                            </div>
                        `;
                    });
                    
                    document.getElementById('existing-rates-content').innerHTML = html;
                    document.getElementById('existing-rates').style.display = 'block';
                } 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);

// Validate individual field
function validateField(field) {
    const value = field.value.trim();
    let isValid = true;
    let message = '';
    
    // Required field validation
    if (field.hasAttribute('required') && !value) {
        isValid = false;
        message = 'กรุณากรอกข้อมูลในช่องนี้';
    }
    
    // Specific validations
    if (field.id === 'tier' && value && parseInt(value) < 1) {
        isValid = false;
        message = 'ขั้นต้องเป็นจำนวนเต็มบวก';
    }
    
    if (field.id === 'min_packages' && value && parseInt(value) < 0) {
        isValid = false;
        message = 'จำนวนพัสดุขั้นต่ำต้องเป็นจำนวนที่ไม่น้อยกว่า 0';
    }
    
    if (field.id === 'rate_per_package' && value && parseFloat(value) < 0) {
        isValid = false;
        message = 'อัตราค่าคอมมิชชั่นต้องเป็นจำนวนที่ไม่น้อยกว่า 0';
    }
    
    // Update field appearance
    if (isValid) {
        field.classList.remove('border-red-500');
        field.classList.add('border-green-500');
        removeFieldError(field);
    } else {
        field.classList.remove('border-green-500');
        field.classList.add('border-red-500');
        showFieldError(field, message);
    }
    
    return isValid;
}

// Clear field error styling
function clearFieldError(field) {
    field.classList.remove('border-red-500', 'border-green-500');
    removeFieldError(field);
}

// Show field error
function showFieldError(field, message) {
    removeFieldError(field);
    
    const errorElement = document.createElement('p');
    errorElement.className = 'error-message';
    errorElement.textContent = message;
    
    field.parentElement.parentElement.appendChild(errorElement);
}

// Remove field error
function removeFieldError(field) {
    const errorElement = field.parentElement.parentElement.querySelector('.error-message');
    if (errorElement) {
        errorElement.remove();
    }
}

// Validate entire form
function validateForm() {
    const warehouseCode = document.getElementById('warehouse_code').value;
    const vehicleType = document.getElementById('vehicle_type').value;
    const tier = document.getElementById('tier').value;
    const minPackages = parseInt(document.getElementById('min_packages').value);
    const maxPackages = parseInt(document.getElementById('max_packages').value);
    const rate = parseFloat(document.getElementById('rate_per_package').value);
    
    if (!warehouseCode) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ครบถ้วน',
            text: 'กรุณาเลือกคลังสินค้า',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('warehouse_code').focus();
        return false;
    }
    
    if (!vehicleType) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ครบถ้วน',
            text: 'กรุณาเลือกประเภทรถ',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('vehicle_type').focus();
        return false;
    }
    
    if (!tier || tier < 1) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ถูกต้อง',
            text: 'กรุณาระบุขั้นที่ถูกต้อง',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('tier').focus();
        return false;
    }
    
    if (isNaN(minPackages) || minPackages < 0) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ถูกต้อง',
            text: 'กรุณาระบุจำนวนพัสดุขั้นต่ำที่ถูกต้อง',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('min_packages').focus();
        return false;
    }
    
    if (maxPackages && maxPackages <= minPackages) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ถูกต้อง',
            text: 'จำนวนพัสดุสูงสุดต้องมากกว่าจำนวนขั้นต่ำ',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('max_packages').focus();
        return false;
    }
    
    if (isNaN(rate) || rate < 0) {
        Swal.fire({
            icon: 'error',
            title: 'ข้อมูลไม่ถูกต้อง',
            text: 'กรุณาระบุอัตราค่าคอมมิชชั่นที่ถูกต้อง',
            confirmButtonColor: '#FF6B35'
        });
        document.getElementById('rate_per_package').focus();
        return false;
    }
    
    return true;
}

// Submit form with loading state
function submitForm() {
    const submitBtn = document.getElementById('submitBtn');
    const form = document.getElementById('commissionForm');
    
    // Show loading state
    submitBtn.classList.add('loading');
    submitBtn.disabled = true;
    
    // Show confirmation
    Swal.fire({
        title: 'ยืนยันการบันทึก',
        text: 'คุณต้องการบันทึกอัตราค่าคอมมิชชั่นใหม่นี้หรือไม่?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#FF6B35',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'บันทึก',
        cancelButtonText: 'ยกเลิก',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    form.submit();
                    resolve();
                }, 1000);
            });
        }
    }).then((result) => {
        if (!result.isConfirmed) {
            // Reset button state if cancelled
            submitBtn.classList.remove('loading');
            submitBtn.disabled = false;
        }
    });
}

// Update radio button states
function updateRadioStates() {
    const radioOptions = document.querySelectorAll('.radio-option');
    radioOptions.forEach(option => {
        const radio = option.querySelector('input[type="radio"]');
        if (radio && radio.checked) {
            option.classList.add('active');
        } else {
            option.classList.remove('active');
        }
    });
}

// Show success/error messages from session
<?php if(session('success')): ?>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'success',
            title: 'สำเร็จ!',
            text: '<?php echo e(session('success')); ?>',
            confirmButtonColor: '#FF6B35'
        });
    });
<?php endif; ?>

<?php if(session('error')): ?>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'error',
            title: 'เกิดข้อผิดพลาด!',
            text: '<?php echo e(session('error')); ?>',
            confirmButtonColor: '#FF6B35'
        });
    });
<?php endif; ?>

// Load existing rates on page load if values are pre-filled
document.addEventListener('DOMContentLoaded', function() {
    loadExistingRates();
    updateCalculationPreview();
});

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + S to save
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        if (validateForm()) {
            submitForm();
        }
    }
    
    // Escape to cancel
    if (e.key === 'Escape') {
        window.location.href = '<?php echo e(route('admin.commission-rates.index')); ?>';
    }
});

// Auto-save draft functionality
let autoSaveTimer;
function startAutoSave() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => {
        const formData = new FormData(document.getElementById('commissionForm'));
        const data = Object.fromEntries(formData);
        localStorage.setItem('commission_rate_draft', JSON.stringify(data));
    }, 2000);
}

// Load draft on page load
document.addEventListener('DOMContentLoaded', function() {
    const draft = localStorage.getItem('commission_rate_draft');
    if (draft) {
        try {
            const data = JSON.parse(draft);
            Object.keys(data).forEach(key => {
                const field = document.querySelector(`[name="${key}"]`);
                if (field && !field.value) {
                    field.value = data[key];
                    if (field.type === 'radio' && field.value === data[key]) {
                        field.checked = true;
                    }
                }
            });
            updateRadioStates();
            updateCalculationPreview();
            loadExistingRates();
        } catch (e) {
            console.log('Could not load draft');
        }
    }
    
    // Track form changes for auto-save
    const form = document.getElementById('commissionForm');
    form.addEventListener('input', startAutoSave);
    form.addEventListener('change', startAutoSave);
});

// Clear draft on successful submission
window.addEventListener('beforeunload', function() {
    if (document.getElementById('commissionForm').checkValidity()) {
        localStorage.removeItem('commission_rate_draft');
    }
});

// Initialize calculation preview updates
document.addEventListener('DOMContentLoaded', function() {
    ['min_packages', 'max_packages', 'rate_per_package'].forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', updateCalculationPreview);
            element.addEventListener('change', updateCalculationPreview);
        }
    });
    
    ['warehouse_code', 'vehicle_type'].forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('change', loadExistingRates);
        }
    });
});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\my-laravel-app\resources\views/admin/commission-rates/create.blade.php ENDPATH**/ ?>