
<?php $__env->startSection('title', 'บันทึกการจัดส่งพัสดุ'); ?>

<?php $__env->startSection('content'); ?>
<main class="main-content" style="width:100%;max-width:100vw;min-width:0;margin:0;padding:0;overflow-x:hidden;">
    <div class="content-container" style="width:100%;max-width:100vw;min-width:0;padding:2rem;overflow-x:hidden;">
        
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">บันทึกการจัดส่งพัสดุ <?php echo e(\Carbon\Carbon::now()->isoFormat('MMMM YYYY')); ?></h1>
            <p class="page-subtitle">กรอกข้อมูลการจัดส่งพัสดุรายวันของคุณ</p>
        </div>
        
        <!-- Back Button -->
        <div class="mb-3">
            <a href="<?php echo e(route('vehicle.dashboard')); ?>" class="btn" style="background: var(--gray); color: white;">
                <i class="fas fa-arrow-left"></i> กลับหน้าแดชบอร์ด
            </a>
        </div><br>
        
        <div class="card" style="border-radius: 24px; box-shadow: var(--shadow-lg); overflow: hidden;">
            <div class="card-header" style="background: var(--primary-gradient); color: #fff; border-radius: 24px 24px 0 0; padding: 2rem;">
                <h3 style="margin: 0; font-weight: 500;">
                    <i class="fas fa-plus"></i> บันทึกการจัดส่งใหม่
                </h3>
            </div>
            
            <form method="POST" action="<?php echo e(route('vehicle.deliveries.store')); ?>" autocomplete="off" id="delivery-form" style="padding:2rem;">
                <?php echo csrf_field(); ?>

                <!-- วันที่จัดส่ง -->
                <div class="form-group mb-3">
                    <label for="delivery_date" class="form-label">
                        <i class="fas fa-calendar-alt"></i> วันที่จัดส่ง <span style="color: #e74c3c;">*</span>
                    </label>
                    <input type="date" name="delivery_date" id="delivery_date"
                        class="form-control <?php $__errorArgs = ['delivery_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        value="<?php echo e(old('delivery_date', date('Y-m-d'))); ?>" required>
                    <?php $__errorArgs = ['delivery_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <!-- จำนวนพัสดุ -->
                <div class="form-group mb-3">
                    <label for="parcel_count" class="form-label">
                        <i class="fas fa-box"></i> จำนวนพัสดุที่จัดส่งสำเร็จ (ชิ้น) <span style="color: #e74c3c;">*</span>
                    </label>
                    <input type="number" min="1" step="1"
                        class="form-control <?php $__errorArgs = ['parcel_count'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        id="parcel_count" name="parcel_count" placeholder="กรอกจำนวนพัสดุ"
                        value="<?php echo e(old('parcel_count')); ?>" required>
                    <?php $__errorArgs = ['parcel_count'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <!-- ข้อมูลผู้ใช้ (readonly) -->
                <div class="form-group mb-3">
                    <label class="form-label">
                        <i class="fas fa-user"></i> ข้อมูลของคุณ
                    </label>
                    <div style="background: #f8f9fa; padding: 1.5rem; border-radius: 12px; border: 1px solid var(--medium-gray);">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div>
                                <strong>ตำแหน่ง:</strong> 
                                <span class="badge" style="background: var(--primary-orange); color: white; margin-left: 0.5rem;">
                                    <?php echo e($user->role); ?>

                                </span>
                            </div>
                            <div>
                                <strong>คลัง:</strong> 
                                <span style="color: var(--dark-gray); font-weight: 500;">
                                    <?php echo e($user->warehouse->warehouse_name ?? $user->warehouse_code ?? '-'); ?>

                                </span>
                            </div>
                        </div>
                    </div>
                    <small class="form-text text-muted">
                        หากต้องการเปลี่ยนข้อมูล กรุณาแก้ไขที่หน้า 
                        <a href="<?php echo e(route('profile.edit')); ?>" style="color:var(--primary-orange);font-weight:500;">โปรไฟล์</a>
                    </small>
                </div>

                <!-- Preview ค่าคอม -->
                <div class="mb-4">
                    <label class="form-label">
                        <i class="fas fa-calculator"></i> การคำนวณค่าคอมมิชชั่น
                    </label>
                    <div id="commission-preview" style="background: #f8f9fa; border-radius: 12px; border: 1px solid var(--medium-gray); padding: 1.5rem;">
                        <div id="rate-info">
                            <div style="text-align: center; color: var(--gray); padding: 2rem;">
                                <i class="fas fa-calculator" style="font-size: 3rem; margin-bottom: 1rem; display: block; opacity: 0.5;"></i>
                                <p style="margin: 0; font-size: 1.1rem;">กรอกจำนวนพัสดุเพื่อดูการคำนวณค่าคอมมิชชั่น</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Commission Rates Info -->
                <?php if($commissionRates->isNotEmpty()): ?>
                <div class="mb-4">
                    <label class="form-label">
                        <i class="fas fa-info-circle"></i> อัตราค่าคอมมิชชั่นของคุณ
                    </label>
                    <div style="background: #e7f3ff; border-radius: 12px; border: 1px solid #b3d9ff; padding: 1.5rem;">
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                            <?php $__currentLoopData = $commissionRates; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $rate): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div style="background: white; padding: 1rem; border-radius: 8px; border-left: 4px solid var(--info);">
                                <div style="font-weight: 600; color: var(--dark-gray); margin-bottom: 0.5rem;">
                                    <?php if($rate->max_packages): ?>
                                        <?php echo e(number_format($rate->min_packages ?? 1)); ?> - <?php echo e(number_format($rate->max_packages)); ?> ชิ้น
                                    <?php else: ?>
                                        <?php echo e(number_format($rate->min_packages ?? 1)); ?>+ ชิ้น
                                    <?php endif; ?>
                                </div>
                                <div style="color: var(--success); font-weight: 600; font-size: 1.1rem;">
                                    <?php echo e(number_format($rate->rate_per_package ?? 0, 2)); ?> บาท/ชิ้น
                                </div>
                            </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="mb-4">
                    <div style="background: #fff3cd; border-radius: 12px; border: 1px solid #ffeaa7; padding: 1.5rem; text-align: center;">
                        <i class="fas fa-exclamation-triangle" style="color: #856404; font-size: 2rem; margin-bottom: 1rem;"></i>
                        <h6 style="color: #856404; margin-bottom: 0.5rem;">ยังไม่มีอัตราค่าคอมมิชชั่น</h6>
                        <p style="color: #856404; margin: 0; font-size: 0.9rem;">
                            กรุณาติดต่อผู้ดูแลระบบเพื่อกำหนดอัตราค่าคอมมิชชั่นสำหรับตำแหน่งและคลังของคุณ
                        </p>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Submit -->
                <div class="mt-4">
                    <button type="submit" class="btn btn-primary" 
                            style="width:100%; border-radius: 2rem; font-size: 1.1rem; font-weight:600; padding: 1rem;">
                        <i class="fas fa-save"></i> บันทึกข้อมูลการจัดส่ง
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const parcelInput = document.getElementById('parcel_count');
    const rateInfo = document.getElementById('rate-info');

    function fetchPreview() {
        const count = parcelInput.value;

        if (!count || count <= 0) {
            rateInfo.innerHTML = `
                <div style="text-align: center; color: var(--gray); padding: 2rem;">
                    <i class="fas fa-calculator" style="font-size: 3rem; margin-bottom: 1rem; display: block; opacity: 0.5;"></i>
                    <p style="margin: 0; font-size: 1.1rem;">กรอกจำนวนพัสดุเพื่อดูการคำนวณค่าคอมมิชชั่น</p>
                </div>
            `;
            return;
        }
        
        rateInfo.innerHTML = `
            <div style="text-align: center; color: var(--info); padding: 2rem;">
                <i class="fas fa-spinner fa-spin" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                <p style="margin: 0; font-size: 1.1rem;">กำลังคำนวณค่าคอมมิชชั่น...</p>
            </div>
        `;
        
        fetch("/commission-preview", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                parcel_count: count
            })
        })
        .then(res => {
            if (!res.ok) throw new Error('Network response was not ok');
            return res.json();
        })
        .then(data => {
            rateInfo.innerHTML = data.preview_html;
        })
        .catch((error) => {
            console.error('Error:', error);
            Swal.fire({
                toast:true, position:'top-end',
                icon: 'error',
                title: 'เกิดข้อผิดพลาด',
                text: 'ไม่สามารถคำนวณค่าคอมมิชชั่นได้ กรุณาลองใหม่อีกครั้ง'
            });
            rateInfo.innerHTML = `
                <div style="text-align: center; color: #F44336; padding: 2rem;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                    <p style="margin: 0; font-size: 1.1rem;">เกิดข้อผิดพลาดในการคำนวณ</p>
                    <button onclick="fetchPreview()" class="btn btn-sm" style="background: var(--info); color: white; margin-top: 1rem;">
                        <i class="fas fa-redo"></i> ลองใหม่
                    </button>
                </div>
            `;
        });
    }

    // Event listener for parcel count input
    parcelInput.addEventListener('input', function() {
        clearTimeout(this.timeout);
        this.timeout = setTimeout(fetchPreview, 500); // Debounce 500ms
    });

    // Validate delivery date for duplicates
    document.getElementById('delivery_date').addEventListener('change', function() {
        const date = this.value;
        if (!date) return;

        fetch("/api/validate-delivery-date", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                delivery_date: date
            })
        })
        .then(res => res.json())
        .then(data => {
            if (!data.valid) {
                Swal.fire({
                    icon: 'warning',
                    title: 'วันที่ซ้ำ',
                    text: data.message,
                    confirmButtonText: 'เข้าใจแล้ว'
                });
                this.style.borderColor = '#dc3545';
                this.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
            } else {
                this.style.borderColor = '#28a745';
                this.style.boxShadow = '0 0 0 0.2rem rgba(40, 167, 69, 0.25)';
            }
        })
        .catch(error => {
            console.error('Validation error:', error);
        });
    });

    // กรณีกรอกอัตโนมัติ/refresh
    if(parcelInput.value) {
        fetchPreview();
    }
});

// Show validation errors
<?php if($errors->any()): ?>
    Swal.fire({
        icon: 'error',
        title: 'ข้อมูลไม่ถูกต้อง',
        html: `<?php echo implode('<br>', $errors->all()); ?>`,
        confirmButtonText: 'ตกลง'
    });
<?php endif; ?>

// Show success message
<?php if(session('success')): ?>
    Swal.fire({
        icon: 'success',
        title: 'บันทึกสำเร็จ',
        text: '<?php echo e(session('success')); ?>',
        timer: 2000,
        showConfirmButton: false
    });
<?php endif; ?>
</script>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('styles'); ?>
<style>
.invalid-feedback {
    display: block;
    width: 100%;
    margin-top: 0.25rem;
    font-size: 0.875rem;
    color: #dc3545;
}

.form-control.is-invalid {
    border-color: #dc3545;
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

.badge {
    padding: 0.35rem 0.65rem;
    border-radius: 0.375rem;
    font-size: 0.75rem;
    font-weight: 600;
}

@media (max-width: 768px) {
    .form-group > div[style*="grid-template-columns"] {
        grid-template-columns: 1fr !important;
        gap: 0.75rem !important;
    }
    
    .commission-rates-grid {
        grid-template-columns: 1fr !important;
    }
}
</style>
<?php $__env->stopPush(); ?>
<?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/vehicle/deliveries/create.blade.php ENDPATH**/ ?>