@extends('layouts.admin')

@section('title', 'Add New Tax')

@section('content')
<div class="admin-page-header">
    <h1>Add New Tax</h1>
    <a href="{{ route('admin.taxes.index') }}" class="admin-btn-primary">
        <i class="bi bi-arrow-left"></i> Back to List
    </a>
</div>

<div class="admin-card">
    <div class="card-body">
        <form action="{{ route('admin.taxes.store') }}" method="POST" id="taxForm">
            @csrf

            <div class="admin-form-grid-2">
                <div>
                    <label class="admin-form-label">Tax Name *</label>
                    <input type="text" 
                           name="name" 
                           class="admin-form-control form-control @error('name') is-invalid @enderror" 
                           value="{{ old('name') }}" 
                           placeholder="e.g., GST, VAT, Sales Tax"
                           required
                           maxlength="255">
                    @error('name')
                        <div class="invalid-feedback" style="font-size: 11px;">{{ $message }}</div>
                    @enderror
                </div>

                <div>
                    <label class="admin-form-label">Tax Type *</label>
                    <select name="type" 
                            id="taxType" 
                            class="admin-form-control form-select no-select2 @error('type') is-invalid @enderror" 
                            required>
                        <option value="">Select Type</option>
                        <option value="single" {{ old('type') === 'single' ? 'selected' : '' }}>Single</option>
                        <option value="multiple" {{ old('type') === 'multiple' ? 'selected' : '' }}>Multiple</option>
                    </select>
                    @error('type')
                        <div class="invalid-feedback" style="font-size: 11px;">{{ $message }}</div>
                    @enderror
                    <small class="form-text text-muted" style="font-size: 11px;">
                        Single: One tax rate | Multiple: Multiple tax components
                    </small>
                </div>
            </div>

            <!-- Single Tax Type -->
            <div id="singleTaxSection" style="display: none; margin-top: 0.5rem;">
                <div class="admin-form-grid-4">
                    <div>
                        <label class="admin-form-label">Tax Rate (%) *</label>
                        <input type="number" 
                               name="rate" 
                               id="singleRate"
                               step="0.01"
                               min="0"
                               max="100"
                               class="admin-form-control form-control @error('rate') is-invalid @enderror" 
                               value="{{ old('rate') }}" 
                               placeholder="e.g., 18.00">
                        @error('rate')
                            <div class="invalid-feedback" style="font-size: 11px;">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Multiple Tax Type -->
            <div id="multipleTaxSection" style="display: none;">
                <div class="mb-3">
                    <label class="form-label fw-bold">Multiple Tax</label>
                    <div class="card">
                        <div class="card-body">
                            <div id="taxComponentsContainer">
                                <!-- Tax components will be added here dynamically -->
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-primary mt-2" id="addTaxComponentBtn">
                                <i class="bi bi-plus-circle"></i> Add Tax Component
                            </button>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Total Tax Rate (%)</label>
                        <input type="number" 
                               id="totalRate"
                               step="0.01"
                               readonly
                               disabled
                               class="form-control bg-light" 
                               value="0.00">
                        <small class="form-text text-muted">
                            Auto-calculated from components above
                        </small>
                    </div>
                </div>
            </div>

            <div class="admin-form-row-compact" style="margin-top: 0.5rem;">
                <div class="form-check">
                    <input type="hidden" name="is_active" value="0">
                    <input type="checkbox" 
                           name="is_active" 
                           class="form-check-input" 
                           id="isActive"
                           value="1" 
                           {{ old('is_active', true) ? 'checked' : '' }}>
                    <label class="form-check-label" for="isActive" style="font-size: 13px;">
                        Active
                    </label>
                </div>
            </div>

            <div style="margin-top: 1rem;">
                <button type="submit" class="admin-btn-primary">
                    <i class="bi bi-save"></i> Create Tax
                </button>
                <a href="{{ route('admin.taxes.index') }}" class="btn btn-outline-secondary btn-sm ms-2">
                    Cancel
                </a>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
(function() {
    const taxTypeSelect = document.getElementById('taxType');
    const singleTaxSection = document.getElementById('singleTaxSection');
    const multipleTaxSection = document.getElementById('multipleTaxSection');
    const singleRateInput = document.getElementById('singleRate');
    const totalRateInput = document.getElementById('totalRate');
    const addTaxComponentBtn = document.getElementById('addTaxComponentBtn');
    const taxComponentsContainer = document.getElementById('taxComponentsContainer');
    
    let componentCount = 0;

    // Handle tax type change
    taxTypeSelect.addEventListener('change', function() {
        const type = this.value;
        
        if (type === 'single') {
            singleTaxSection.style.display = 'block';
            multipleTaxSection.style.display = 'none';
            singleRateInput.required = true;
            singleRateInput.disabled = false;
            singleRateInput.setAttribute('name', 'rate');
            // Disable the multiple rate input so it doesn't get submitted
            totalRateInput.disabled = true;
            totalRateInput.removeAttribute('name');
        } else if (type === 'multiple') {
            singleTaxSection.style.display = 'none';
            multipleTaxSection.style.display = 'block';
            singleRateInput.required = false;
            singleRateInput.disabled = true;
            singleRateInput.removeAttribute('name');
            // Enable the total rate input
            totalRateInput.disabled = false;
            totalRateInput.setAttribute('name', 'rate');
            totalRateInput.required = false;
            
            // Add first component if none exist
            if (taxComponentsContainer.children.length === 0) {
                addTaxComponent();
            }
        } else {
            singleTaxSection.style.display = 'none';
            multipleTaxSection.style.display = 'none';
            singleRateInput.required = false;
            singleRateInput.disabled = true;
            singleRateInput.removeAttribute('name');
            totalRateInput.disabled = true;
            totalRateInput.removeAttribute('name');
        }
    });

    // Initialize on page load
    if (taxTypeSelect.value) {
        taxTypeSelect.dispatchEvent(new Event('change'));
    }

    // Add tax component
    addTaxComponentBtn.addEventListener('click', function() {
        addTaxComponent();
    });

    function addTaxComponent() {
        const componentId = componentCount++;
        const componentDiv = document.createElement('div');
        componentDiv.className = 'row mb-3 tax-component-row';
        componentDiv.dataset.componentId = componentId;
        
        componentDiv.innerHTML = `
            <div class="col-md-5">
                <input type="text" 
                       name="components[${componentId}][name]" 
                       class="form-control component-name" 
                       placeholder="Tax Name (e.g., CGST, SGST)"
                       required>
            </div>
            <div class="col-md-5">
                <input type="number" 
                       name="components[${componentId}][rate]" 
                       class="form-control component-rate" 
                       step="0.01"
                       min="0"
                       max="100"
                       placeholder="Rate (%)"
                       required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-sm btn-outline-danger remove-component" data-component-id="${componentId}">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        `;
        
        taxComponentsContainer.appendChild(componentDiv);
        
        // Add event listeners
        const removeBtn = componentDiv.querySelector('.remove-component');
        removeBtn.addEventListener('click', function() {
            componentDiv.remove();
            calculateTotalRate();
        });
        
        const rateInput = componentDiv.querySelector('.component-rate');
        rateInput.addEventListener('input', calculateTotalRate);
        
        // Load old values if editing
        @if(old('components'))
            const oldComponents = @json(old('components'));
            if (oldComponents && oldComponents[componentId]) {
                componentDiv.querySelector('.component-name').value = oldComponents[componentId].name || '';
                componentDiv.querySelector('.component-rate').value = oldComponents[componentId].rate || '';
            }
        @endif
    }

    // Calculate total rate
    function calculateTotalRate() {
        const rateInputs = document.querySelectorAll('.component-rate');
        let total = 0;
        
        rateInputs.forEach(input => {
            const value = parseFloat(input.value) || 0;
            total += value;
        });
        
        totalRateInput.value = total.toFixed(2);
    }

    // Load existing components if editing
    @if(old('type') === 'multiple' && old('components'))
        const oldComponents = @json(old('components'));
        oldComponents.forEach((component, index) => {
            componentCount = index;
            addTaxComponent();
            const lastRow = taxComponentsContainer.lastElementChild;
            lastRow.querySelector('.component-name').value = component.name || '';
            lastRow.querySelector('.component-rate').value = component.rate || '';
        });
        calculateTotalRate();
    @endif
})();
</script>
@endpush
@endsection

