@extends('layouts.app')

@section('content')
<div class="finance-form-container">
    <div class="form-header">
        <h1 class="form-title">
            <i class="fas {{ isset($record) ? 'fa-edit' : 'fa-plus-circle' }}"></i>
            {{ isset($record) ? 'แก้ไขรายการ' : 'เพิ่มรายการใหม่' }}
        </h1>
        <a href="{{ route('finance.records.index') }}" class="btn-back">
            <i class="fas fa-arrow-left"></i> กลับ
        </a>
    </div>

    <form method="POST" 
          action="{{ isset($record) ? route('finance.records.update', $record) : route('finance.records.store') }}"
          class="finance-form">
        @csrf
        @if(isset($record))
            @method('PUT')
        @endif

        <!-- Type Selection (for create only) -->
        @if(!isset($record))
        <div class="type-selector">
            <label class="type-option">
                <input type="radio" name="type" value="income" {{ $type === 'income' ? 'checked' : '' }}>
                <div class="type-card income">
                    <i class="fas fa-arrow-circle-up"></i>
                    <span>รายรับ</span>
                </div>
            </label>
            <label class="type-option">
                <input type="radio" name="type" value="expense" {{ $type === 'expense' ? 'checked' : '' }}>
                <div class="type-card expense">
                    <i class="fas fa-arrow-circle-down"></i>
                    <span>รายจ่าย</span>
                </div>
            </label>
        </div>
        @else
            <input type="hidden" name="type" value="{{ $record->type }}">
        @endif

        <div class="form-grid">
            <!-- Date -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-calendar"></i> วันที่
                </label>
                <input type="date" 
                       name="record_date" 
                       class="form-control @error('record_date') is-invalid @enderror"
                       value="{{ old('record_date', isset($record) ? $record->record_date->format('Y-m-d') : date('Y-m-d')) }}"
                       required>
                @error('record_date')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Category -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-tag"></i> หมวดหมู่
                </label>
                <select name="category" 
                        class="form-control category-select @error('category') is-invalid @enderror"
                        required>
                    <option value="">-- เลือกหมวดหมู่ --</option>
                    @foreach($categories as $value => $name)
                        <option value="{{ $value }}" 
                                {{ old('category', isset($record) ? $record->category : '') == $value ? 'selected' : '' }}>
                            {{ $name }}
                        </option>
                    @endforeach
                </select>
                @error('category')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Amount -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-coins"></i> จำนวนเงิน
                </label>
                <div class="input-group">
                    <span class="input-addon">฿</span>
                    <input type="number" 
                           name="amount" 
                           class="form-control amount-input @error('amount') is-invalid @enderror"
                           value="{{ old('amount', isset($record) ? $record->amount : '') }}"
                           step="0.01"
                           min="0"
                           placeholder="0.00"
                           required>
                </div>
                @error('amount')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Note -->
            <div class="form-group full-width">
                <label class="form-label">
                    <i class="fas fa-sticky-note"></i> หมายเหตุ
                </label>
                <textarea name="note" 
                          class="form-control @error('note') is-invalid @enderror"
                          rows="3"
                          placeholder="รายละเอียดเพิ่มเติม (ถ้ามี)">{{ old('note', isset($record) ? $record->note : '') }}</textarea>
                @error('note')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Recurring (for create only) -->
            @if(!isset($record))
            <div class="form-group full-width">
                <label class="checkbox-label">
                    <input type="checkbox" 
                           name="is_recurring" 
                           value="1"
                           id="recurringCheck"
                           {{ old('is_recurring') ? 'checked' : '' }}>
                    <span>รายการซ้ำ (สร้างรายการล่วงหน้า)</span>
                </label>
                
                <div id="recurringOptions" style="display: {{ old('is_recurring') ? 'block' : 'none' }}; margin-top: 1rem;">
                    <select name="recurring_type" class="form-control">
                        <option value="daily" {{ old('recurring_type') == 'daily' ? 'selected' : '' }}>ทุกวัน</option>
                        <option value="weekly" {{ old('recurring_type') == 'weekly' ? 'selected' : '' }}>ทุกสัปดาห์</option>
                        <option value="monthly" {{ old('recurring_type') == 'monthly' ? 'selected' : '' }}>ทุกเดือน</option>
                        <option value="yearly" {{ old('recurring_type') == 'yearly' ? 'selected' : '' }}>ทุกปี</option>
                    </select>
                    <small class="form-text">ระบบจะสร้างรายการล่วงหน้า 3 เดือน</small>
                </div>
            </div>
            @endif
        </div>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i>
                {{ isset($record) ? 'บันทึกการแก้ไข' : 'บันทึกรายการ' }}
            </button>
            <a href="{{ route('finance.records.index') }}" class="btn btn-secondary">
                <i class="fas fa-times"></i> ยกเลิก
            </a>
        </div>
    </form>

    <!-- Category Preview -->
    <div class="category-preview">
        <h3>หมวดหมู่ที่มี</h3>
        <div id="categoryList" class="category-list">
            <!-- Will be populated by JS -->
        </div>
    </div>
</div>

@push('styles')
<style>
.finance-form-container {
    max-width: 800px;
    margin: 2rem auto;
    padding: 0 1rem;
}

.form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
}

.form-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #1f2937;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-back {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #6b7280;
    text-decoration: none;
    font-weight: 500;
    transition: color 0.3s;
}

.btn-back:hover {
    color: #667eea;
}

.finance-form {
    background: white;
    border-radius: 20px;
    padding: 2rem;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
}

/* Type Selector */
.type-selector {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    margin-bottom: 2rem;
}

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

.type-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    padding: 2rem;
    border: 2px solid #e5e7eb;
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.3s;
    text-align: center;
}

.type-card i {
    font-size: 3rem;
}

.type-card span {
    font-size: 1.1rem;
    font-weight: 600;
}

.type-card.income {
    color: #10b981;
}

.type-card.expense {
    color: #ef4444;
}

.type-option input[type="radio"]:checked + .type-card.income {
    border-color: #10b981;
    background: #10b98110;
}

.type-option input[type="radio"]:checked + .type-card.expense {
    border-color: #ef4444;
    background: #ef444410;
}

/* Form Grid */
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
}

.form-group {
    display: flex;
    flex-direction: column;
}

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

.form-label {
    font-weight: 600;
    color: #374151;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.form-control {
    padding: 0.75rem 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 1rem;
    transition: all 0.3s;
    background: #f9fafb;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-control.is-invalid {
    border-color: #ef4444;
}

.invalid-feedback {
    color: #ef4444;
    font-size: 0.875rem;
    margin-top: 0.25rem;
}

/* Input Group */
.input-group {
    display: flex;
    align-items: stretch;
}

.input-addon {
    display: flex;
    align-items: center;
    padding: 0 1rem;
    background: #f3f4f6;
    border: 2px solid #e5e7eb;
    border-right: none;
    border-radius: 12px 0 0 12px;
    color: #6b7280;
    font-weight: 600;
}

.input-group .form-control {
    border-radius: 0 12px 12px 0;
}

.amount-input {
    text-align: right;
    font-size: 1.2rem;
    font-weight: 600;
}

/* Checkbox */
.checkbox-label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    font-weight: 500;
    color: #374151;
}

.checkbox-label input[type="checkbox"] {
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.form-text {
    font-size: 0.875rem;
    color: #6b7280;
    margin-top: 0.5rem;
}

/* Form Actions */
.form-actions {
    display: flex;
    gap: 1rem;
    margin-top: 2rem;
    padding-top: 2rem;
    border-top: 1px solid #e5e7eb;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
    background: #f3f4f6;
    color: #6b7280;
}

.btn-secondary:hover {
    background: #e5e7eb;
}

/* Category Preview */
.category-preview {
    margin-top: 2rem;
    background: #f9fafb;
    border-radius: 16px;
    padding: 1.5rem;
}

.category-preview h3 {
    font-size: 1.1rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 1rem;
}

.category-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.category-item {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    background: white;
    border-radius: 20px;
    font-size: 0.875rem;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.category-item i {
    font-size: 1rem;
}

/* Responsive */
@media (max-width: 768px) {
    .finance-form-container {
        padding: 0 0.5rem;
    }
    
    .finance-form {
        padding: 1.5rem;
    }
    
    .type-selector {
        grid-template-columns: 1fr;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Type selector
    const typeInputs = document.querySelectorAll('input[name="type"]');
    const categorySelect = document.querySelector('.category-select');
    
    typeInputs.forEach(input => {
        input.addEventListener('change', function() {
            loadCategories(this.value);
        });
    });

    // Recurring checkbox
    const recurringCheck = document.getElementById('recurringCheck');
    const recurringOptions = document.getElementById('recurringOptions');
    
    if (recurringCheck) {
        recurringCheck.addEventListener('change', function() {
            recurringOptions.style.display = this.checked ? 'block' : 'none';
        });
    }

    // Load categories based on type
    function loadCategories(type) {
        fetch(`{{ route('finance.records.categories') }}?type=${type}`)
            .then(response => response.json())
            .then(categories => {
                categorySelect.innerHTML = '<option value="">-- เลือกหมวดหมู่ --</option>';
                categories.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.slug;
                    option.textContent = cat.name;
                    categorySelect.appendChild(option);
                });
                
                updateCategoryPreview(categories);
            });
    }

    // Update category preview
    function updateCategoryPreview(categories) {
        const categoryList = document.getElementById('categoryList');
        categoryList.innerHTML = '';
        
        categories.forEach(cat => {
            const item = document.createElement('div');
            item.className = 'category-item';
            item.style.color = cat.color;
            item.innerHTML = `<i class="fas ${cat.icon}"></i> ${cat.name}`;
            categoryList.appendChild(item);
        });
    }

    // Initial load
    const currentType = document.querySelector('input[name="type"]:checked');
    if (currentType) {
        loadCategories(currentType.value);
    }

    // Amount input formatting
    const amountInput = document.querySelector('.amount-input');
    if (amountInput) {
        amountInput.addEventListener('input', function() {
            // Remove non-numeric except decimal point
            this.value = this.value.replace(/[^0-9.]/g, '');
            
            // Ensure only one decimal point
            const parts = this.value.split('.');
            if (parts.length > 2) {
                this.value = parts[0] + '.' + parts.slice(1).join('');
            }
            
            // Limit to 2 decimal places
            if (parts[1] && parts[1].length > 2) {
                this.value = parts[0] + '.' + parts[1].substring(0, 2);
            }
        });
    }
});
</script>
@endpush
@endsection