@extends('layouts.app')

@section('content')
<div class="calculator-container"><br><br>
    <!-- Page Header -->
    <div class="page-header">
        <div class="page-header-content">
            <h1 class="page-title">
                <i class="fas fa-calculator"></i>
                คำนวณค่าคอมมิชชั่น
            </h1>
            <p class="page-subtitle">
                คำนวณค่าคอมมิชชั่นจากจำนวนพัสดุที่จัดส่ง
            </p>
        </div>
        <a href="{{ route('vehicle.dashboard') }}" class="btn btn-outline">
            <i class="fas fa-arrow-left"></i> กลับหน้าหลัก
        </a>
    </div>

    <div class="calculator-grid">
        <!-- Calculator Form -->
        <div class="calculator-card">
            <div class="card-header">
                <i class="fas fa-edit"></i>
                กรอกจำนวนพัสดุ
            </div>
            <div class="card-body">
                <form id="calculatorForm" method="POST" action="{{ route('vehicle.calculator') }}">
                    @csrf
                    
                    <!-- User Info Display -->
                    <div class="info-display">
                        <div class="info-row">
                            <span class="info-label">
                                <i class="fas fa-warehouse"></i> คลัง:
                            </span>
                            <span class="info-value">{{ auth()->user()->warehouse->name ?? auth()->user()->warehouse_code }}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">
                                <i class="fas fa-{{ auth()->user()->role == '2wheel' ? 'motorcycle' : 'truck' }}"></i> ประเภท:
                            </span>
                            <span class="info-value">{{ auth()->user()->role == '2wheel' ? 'รถ 2 ล้อ' : 'รถ 4 ล้อ' }}</span>
                        </div>
                    </div>

                    <!-- Parcel Input -->
                    <div class="form-group">
                        <label class="form-label">จำนวนพัสดุ (ชิ้น)</label>
                        <div class="input-wrapper">
                            <input type="number" 
                                   id="parcel_count" 
                                   name="parcel_count" 
                                   class="form-control large-input" 
                                   min="1" 
                                   max="9999"
                                   value="{{ old('parcel_count', request('parcel_count', '')) }}"
                                   placeholder="0"
                                   required>
                            <span class="input-suffix">ชิ้น</span>
                        </div>
                        <span class="form-hint">กรอกจำนวนพัสดุที่ต้องการคำนวณ</span>
                    </div>

                    <!-- Quick Select Buttons -->
                    <div class="quick-select">
                        <span class="quick-label">เลือกด่วน:</span>
                        <div class="quick-buttons">
                            <button type="button" class="quick-btn" data-value="50">50</button>
                            <button type="button" class="quick-btn" data-value="100">100</button>
                            <button type="button" class="quick-btn" data-value="150">150</button>
                            <button type="button" class="quick-btn" data-value="200">200</button>
                            <button type="button" class="quick-btn" data-value="300">300</button>
                            <button type="button" class="quick-btn" data-value="500">500</button>
                        </div>
                    </div>

                    <!-- Calculate Button -->
                    <button type="submit" class="btn btn-primary btn-calculate">
                        <i class="fas fa-calculator"></i>
                        คำนวณค่าคอมมิชชั่น
                    </button>
                </form>
            </div>
        </div>

        <!-- Commission Rates Table -->
        <div class="rates-card">
            <div class="card-header">
                <i class="fas fa-list"></i>
                อัตราค่าคอมมิชชั่น
            </div>
            <div class="card-body">
                @if($commissionRates->count() > 0)
                <div class="rates-table-wrapper">
                    <table class="rates-table">
                        <thead>
                            <tr>
                                <th>ขั้น</th>
                                <th>จำนวนพัสดุ</th>
                                <th>อัตรา/ชิ้น</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($commissionRates as $rate)
                            <tr class="rate-row" data-min="{{ $rate->min_packages }}" data-max="{{ $rate->max_packages }}">
                                <td class="tier-cell">
                                    <span class="tier-badge">{{ $rate->tier }}</span>
                                </td>
                                <td class="range-cell">{{ $rate->range_display }}</td>
                                <td class="rate-cell">
                                    <span class="rate-amount">{{ number_format($rate->rate_per_package, 2) }}</span>
                                    <span class="rate-unit">บาท</span>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                @else
                <div class="no-rates">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>ยังไม่มีการตั้งค่าอัตราค่าคอมมิชชั่น</p>
                </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Result Display (if calculated) -->
    @if(isset($result))
    <div class="result-section" id="resultSection">
        <div class="result-card">
            <div class="result-header">
                <h2 class="result-title">
                    <i class="fas fa-check-circle"></i>
                    ผลการคำนวณ
                </h2>
                <span class="result-parcels">{{ number_format($result['package_count']) }} พัสดุ</span>
            </div>
            
            <div class="result-total">
                <span class="total-label">ค่าคอมมิชชั่นทั้งหมด</span>
                <div class="total-amount">
                    <span class="currency">฿</span>
                    <span class="amount">{{ number_format($result['total_commission'], 2) }}</span>
                </div>
                <span class="average-rate">
                    เฉลี่ย {{ number_format($result['average_per_package'], 2) }} บาท/ชิ้น
                </span>
            </div>

            @if(count($result['breakdown']) > 0)
            <div class="breakdown-section">
                <h3 class="breakdown-title">รายละเอียดการคำนวณ</h3>
                <div class="breakdown-list">
                    @foreach($result['breakdown'] as $tier)
                    <div class="breakdown-item">
                        <div class="breakdown-info">
                            <span class="breakdown-tier">ขั้นที่ {{ $tier['tier'] }}</span>
                            <span class="breakdown-range">{{ $tier['range'] }}</span>
                        </div>
                        <div class="breakdown-calc">
                            <span class="breakdown-count">{{ number_format($tier['packages_in_tier']) }} ชิ้น</span>
                            <span class="breakdown-multiply">×</span>
                            <span class="breakdown-rate">{{ number_format($tier['rate_per_package'], 2) }} บาท</span>
                            <span class="breakdown-equals">=</span>
                            <span class="breakdown-total">{{ number_format($tier['tier_commission'], 2) }} บาท</span>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
            @endif

            <div class="result-actions">
                <button type="button" class="btn btn-outline" onclick="clearResult()">
                    <i class="fas fa-redo"></i> คำนวณใหม่
                </button>
                <button type="button" class="btn btn-primary" onclick="saveAsDelivery()">
                    <i class="fas fa-save"></i> บันทึกเป็นการจัดส่ง
                </button>
            </div>
        </div>
    </div>
    @endif
</div>

@push('styles')
<style>
/* Container */
.calculator-container {
    max-width: 100%;
    margin: 0;
    padding: 1rem;
    width: 100%;
    box-sizing: border-box;
}

/* Page Header */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: var(--white);
    border-radius: var(--radius-lg);
    padding: 1.25rem 1.5rem;
    margin-bottom: 1.5rem;
    box-shadow: var(--shadow-sm);
}

.page-title {
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--dark-gray);
    margin: 0;
}

.page-subtitle {
    font-size: 0.9rem;
    color: var(--gray);
    margin: 0.25rem 0 0 0;
}

/* Grid Layout */
.calculator-grid {
    display: grid;
    grid-template-columns: 1fr minmax(300px, 400px);
    gap: 1.5rem;
    margin-bottom: 2rem;
}

/* Cards */
.calculator-card,
.rates-card {
    background: var(--white);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-sm);
    overflow: hidden;
}

.card-header {
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.05) 0%, rgba(255, 140, 97, 0.05) 100%);
    padding: 1rem 1.25rem;
    font-weight: 600;
    font-size: 1.05rem;
    color: var(--dark-gray);
    border-bottom: 1px solid var(--medium-gray);
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.card-body {
    padding: 1.5rem;
}

/* Info Display */
.info-display {
    background: var(--light-gray);
    border-radius: var(--radius-md);
    padding: 1rem;
    margin-bottom: 1.5rem;
}

.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.25rem 0;
}

.info-label {
    color: var(--gray);
    font-size: 0.9rem;
}

.info-value {
    font-weight: 600;
    color: var(--dark-gray);
}

/* Form */
.form-group {
    margin-bottom: 1.5rem;
}

.form-label {
    display: block;
    font-weight: 500;
    color: var(--dark-gray);
    margin-bottom: 0.5rem;
}

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

.large-input {
    width: 100%;
    padding: 1rem 3rem 1rem 1.5rem;
    font-size: 1.5rem;
    font-weight: 600;
    border: 2px solid var(--medium-gray);
    border-radius: var(--radius-md);
    text-align: center;
    transition: var(--transition-fast);
}

.large-input:focus {
    outline: none;
    border-color: var(--primary-orange);
    box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.input-suffix {
    position: absolute;
    right: 1rem;
    color: var(--gray);
    font-size: 1rem;
}

.form-hint {
    display: block;
    color: var(--gray);
    font-size: 0.875rem;
    margin-top: 0.5rem;
    text-align: center;
}

/* Quick Select */
.quick-select {
    margin-bottom: 1.5rem;
}

.quick-label {
    display: block;
    font-size: 0.875rem;
    color: var(--gray);
    margin-bottom: 0.5rem;
}

.quick-buttons {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(60px, 1fr));
    gap: 0.5rem;
}

.quick-btn {
    padding: 0.5rem;
    border: 2px solid var(--medium-gray);
    background: var(--white);
    border-radius: var(--radius-md);
    font-weight: 600;
    color: var(--gray);
    cursor: pointer;
    transition: var(--transition-fast);
}

.quick-btn:hover {
    border-color: var(--primary-orange);
    color: var(--primary-orange);
    transform: translateY(-1px);
}

.quick-btn.active {
    background: var(--primary-orange);
    border-color: var(--primary-orange);
    color: var(--white);
}

/* Buttons */
.btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: var(--radius-md);
    font-weight: 500;
    font-size: 0.95rem;
    cursor: pointer;
    transition: var(--transition-fast);
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
}

.btn-primary {
    background: var(--primary-gradient);
    color: var(--white);
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: var(--shadow-md);
}

.btn-outline {
    background: var(--white);
    border: 2px solid var(--medium-gray);
    color: var(--gray);
}

.btn-outline:hover {
    border-color: var(--primary-orange);
    color: var(--primary-orange);
}

.btn-calculate {
    width: 100%;
    padding: 1rem;
    font-size: 1.1rem;
}

/* Rates Table */
.rates-table-wrapper {
    overflow-x: auto;
}

.rates-table {
    width: 100%;
    border-collapse: collapse;
}

.rates-table th {
    background: var(--light-gray);
    padding: 0.75rem;
    font-weight: 600;
    font-size: 0.875rem;
    color: var(--dark-gray);
    text-align: left;
}

.rates-table td {
    padding: 0.75rem;
    border-bottom: 1px solid var(--medium-gray);
}

.rate-row {
    transition: var(--transition-fast);
}

.rate-row:hover {
    background: rgba(255, 107, 53, 0.05);
}

.rate-row.highlight {
    background: rgba(255, 107, 53, 0.1);
    border-left: 3px solid var(--primary-orange);
}

.tier-badge {
    display: inline-block;
    background: var(--primary-orange);
    color: var(--white);
    padding: 0.25rem 0.75rem;
    border-radius: var(--radius-full);
    font-size: 0.875rem;
    font-weight: 600;
}

.rate-amount {
    font-weight: 600;
    color: #10b981;
}

.rate-unit {
    color: var(--gray);
    font-size: 0.875rem;
}

/* No Rates */
.no-rates {
    text-align: center;
    padding: 2rem;
    color: var(--gray);
}

.no-rates i {
    font-size: 2rem;
    margin-bottom: 0.5rem;
    opacity: 0.5;
}

/* Result Section */
.result-section {
    margin-top: 2rem;
    animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.result-card {
    background: var(--white);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-md);
    overflow: hidden;
    border: 2px solid var(--primary-orange);
}

.result-header {
    background: linear-gradient(135deg, #FF6B35 0%, #FF8C61 100%);
    color: var(--white);
    padding: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.result-title {
    font-size: 1.25rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.result-parcels {
    font-size: 1rem;
    opacity: 0.9;
}

.result-total {
    padding: 2rem;
    text-align: center;
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.05) 0%, rgba(255, 140, 97, 0.05) 100%);
}

.total-label {
    display: block;
    font-size: 1rem;
    color: var(--gray);
    margin-bottom: 0.5rem;
}

.total-amount {
    display: flex;
    align-items: baseline;
    justify-content: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
}

.currency {
    font-size: 2rem;
    color: var(--primary-orange);
}

.amount {
    font-size: 3rem;
    font-weight: 700;
    color: var(--primary-orange);
}

.average-rate {
    font-size: 0.875rem;
    color: var(--gray);
}

/* Breakdown */
.breakdown-section {
    padding: 1.5rem;
    border-top: 1px solid var(--medium-gray);
}

.breakdown-title {
    font-size: 1rem;
    font-weight: 600;
    color: var(--dark-gray);
    margin-bottom: 1rem;
}

.breakdown-list {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.breakdown-item {
    background: var(--light-gray);
    border-radius: var(--radius-md);
    padding: 1rem;
}

.breakdown-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
}

.breakdown-tier {
    font-weight: 600;
    color: var(--primary-orange);
}

.breakdown-range {
    color: var(--gray);
}

.breakdown-calc {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.95rem;
}

.breakdown-count {
    font-weight: 600;
}

.breakdown-multiply,
.breakdown-equals {
    color: var(--gray);
}

.breakdown-rate {
    color: #10b981;
}

.breakdown-total {
    font-weight: 600;
    color: var(--dark-gray);
    margin-left: auto;
}

/* Result Actions */
.result-actions {
    padding: 1.5rem;
    background: var(--light-gray);
    display: flex;
    gap: 1rem;
    justify-content: center;
}

/* Responsive */
@media (max-width: 992px) {
    .calculator-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .calculator-container {
        padding: 0.75rem;
    }
    
    .page-header {
        flex-direction: column;
        gap: 1rem;
        padding: 1rem;
    }
    
    .page-title {
        font-size: 1.25rem;
    }
    
    .card-body {
        padding: 1rem;
    }
    
    .large-input {
        font-size: 1.25rem;
        padding: 0.75rem 2.5rem 0.75rem 1rem;
    }
    
    .quick-buttons {
        grid-template-columns: repeat(3, 1fr);
    }
    
    .total-amount .amount {
        font-size: 2.5rem;
    }
    
    .breakdown-calc {
        flex-wrap: wrap;
        font-size: 0.875rem;
    }
    
    .result-actions {
        flex-direction: column;
    }
    
    .result-actions .btn {
        width: 100%;
        justify-content: center;
    }
}

/* Ensure content fits viewport */
* {
    box-sizing: border-box;
}

.main-content {
    overflow-x: hidden;
}
</style>
@endpush

@push('scripts')
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Quick select buttons
document.querySelectorAll('.quick-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const value = this.getAttribute('data-value');
        document.getElementById('parcel_count').value = value;
        
        // Update active state
        document.querySelectorAll('.quick-btn').forEach(b => b.classList.remove('active'));
        this.classList.add('active');
        
        // Highlight matching rate rows
        highlightRateRows(parseInt(value));
    });
});

// Highlight rate rows based on parcel count
function highlightRateRows(count) {
    document.querySelectorAll('.rate-row').forEach(row => {
        const min = parseInt(row.getAttribute('data-min'));
        const max = row.getAttribute('data-max') ? parseInt(row.getAttribute('data-max')) : Infinity;
        
        if (count >= min && count <= max) {
            row.classList.add('highlight');
        } else {
            row.classList.remove('highlight');
        }
    });
}

// Input change event
document.getElementById('parcel_count').addEventListener('input', function() {
    const value = parseInt(this.value) || 0;
    highlightRateRows(value);
    
    // Update quick button active state
    document.querySelectorAll('.quick-btn').forEach(btn => {
        if (parseInt(btn.getAttribute('data-value')) === value) {
            btn.classList.add('active');
        } else {
            btn.classList.remove('active');
        }
    });
});

// Form submit with SweetAlert
document.getElementById('calculatorForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const parcelCount = document.getElementById('parcel_count').value;
    
    if (!parcelCount || parcelCount < 1) {
        Swal.fire({
            icon: 'warning',
            title: 'กรุณากรอกจำนวนพัสดุ',
            text: 'จำนวนพัสดุต้องมากกว่า 0',
            confirmButtonColor: '#FF6B35'
        });
        return;
    }
    
    // Show loading
    Swal.fire({
        title: 'กำลังคำนวณ...',
        html: 'กรุณารอสักครู่',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Submit form
    setTimeout(() => {
        this.submit();
    }, 500);
});

// Clear result
function clearResult() {
    document.getElementById('parcel_count').value = '';
    document.getElementById('resultSection').style.display = 'none';
    document.querySelectorAll('.quick-btn').forEach(btn => btn.classList.remove('active'));
    document.querySelectorAll('.rate-row').forEach(row => row.classList.remove('highlight'));
}

// Save as delivery
function saveAsDelivery() {
    const parcelCount = {{ isset($result) ? $result['package_count'] : 0 }};
    const commission = {{ isset($result) ? $result['total_commission'] : 0 }};
    
    Swal.fire({
        title: 'บันทึกเป็นการจัดส่ง?',
        html: `
            <div style="text-align: left;">
                <p><strong>จำนวนพัสดุ:</strong> ${parcelCount.toLocaleString()} ชิ้น</p>
                <p><strong>ค่าคอมมิชชั่น:</strong> ${commission.toLocaleString('th-TH', { minimumFractionDigits: 2 })} บาท</p>
                <p><strong>วันที่:</strong> ${new Date().toLocaleDateString('th-TH')}</p>
            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#FF6B35',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'บันทึก',
        cancelButtonText: 'ยกเลิก'
    }).then((result) => {
        if (result.isConfirmed) {
            // Redirect to create delivery with pre-filled data
            const form = document.createElement('form');
            form.method = 'GET';
            form.action = '{{ route("vehicle.deliveries.create") }}';
            
            const parcelInput = document.createElement('input');
            parcelInput.type = 'hidden';
            parcelInput.name = 'parcel_count';
            parcelInput.value = parcelCount;
            form.appendChild(parcelInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const currentValue = document.getElementById('parcel_count').value;
    if (currentValue) {
        highlightRateRows(parseInt(currentValue));
    }
    
    // Smooth scroll to result if exists
    @if(isset($result))
    setTimeout(() => {
        document.getElementById('resultSection').scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start' 
        });
    }, 100);
    @endif
});
</script>
@endpush
@endsection