@extends('layouts.app')

@section('title', 'Edit Savings Scheme')
@section('page-title', 'Edit Savings Scheme')

@section('content')
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">Edit Savings Scheme</h5>
    </div>
    <div class="card-body">
        <div class="alert alert-info">
            <i class="bi bi-info-circle"></i> <strong>Note:</strong> You cannot change the savings type (RD/FD/MIS) if accounts exist under this scheme.
        </div>
        
        <form action="{{ route('partner.savings-schemes.update', $savingsScheme) }}" method="POST" id="schemeForm">
            @csrf
            @method('PUT')
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="name" class="form-label">Scheme Name *</label>
                    <input type="text" class="form-control @error('name') is-invalid @enderror" 
                           id="name" name="name" value="{{ old('name', $savingsScheme->name) }}" required>
                    @error('name')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="savings_type" class="form-label">Savings Type *</label>
                    <select class="form-select @error('savings_type') is-invalid @enderror" id="savings_type" name="savings_type" required {{ $savingsScheme->savings()->count() > 0 ? 'disabled' : '' }}>
                        <option value="RD" {{ old('savings_type', $savingsScheme->savings_type) == 'RD' ? 'selected' : '' }}>RD - Recurring Deposit</option>
                        <option value="FD" {{ old('savings_type', $savingsScheme->savings_type) == 'FD' ? 'selected' : '' }}>FD - Fixed Deposit</option>
                        <option value="MIS" {{ old('savings_type', $savingsScheme->savings_type) == 'MIS' ? 'selected' : '' }}>MIS - Monthly Income Scheme</option>
                    </select>
                    @if($savingsScheme->savings()->count() > 0)
                        <input type="hidden" name="savings_type" value="{{ $savingsScheme->savings_type }}">
                        <small class="text-muted">Cannot change type when accounts exist</small>
                    @endif
                    @error('savings_type')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">Description</label>
                <textarea class="form-control" id="description" name="description" rows="3">{{ old('description', $savingsScheme->description) }}</textarea>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="interest_rate" class="form-label">Interest Rate (% per annum) *</label>
                    <input type="number" step="0.01" class="form-control @error('interest_rate') is-invalid @enderror" 
                           id="interest_rate" name="interest_rate" value="{{ old('interest_rate', $savingsScheme->interest_rate) }}" 
                           placeholder="e.g., 6.5" required>
                    @error('interest_rate')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="interest_type" class="form-label">Interest Type *</label>
                    <select class="form-select @error('interest_type') is-invalid @enderror" id="interest_type" name="interest_type" required>
                        <option value="compound" {{ old('interest_type', $savingsScheme->interest_type ?? 'compound') === 'compound' ? 'selected' : '' }}>Compound Interest</option>
                        <option value="simple" {{ old('interest_type', $savingsScheme->interest_type) === 'simple' ? 'selected' : '' }}>Simple Interest</option>
                    </select>
                    @error('interest_type')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <!-- Compounding Frequency (for Compound Interest only) -->
            <div id="compounding-section" class="row" style="display: none;">
                <div class="col-md-6 mb-3">
                    <label for="compounding_frequency" class="form-label">Compounding Frequency *</label>
                    <select class="form-select" id="compounding_frequency" name="compounding_frequency">
                        <option value="">Select Frequency</option>
                        <option value="monthly" {{ old('compounding_frequency', $savingsScheme->compounding_frequency ?? 'monthly') === 'monthly' ? 'selected' : '' }}>Monthly</option>
                        <option value="quarterly" {{ old('compounding_frequency', $savingsScheme->compounding_frequency) === 'quarterly' ? 'selected' : '' }}>Quarterly</option>
                        <option value="yearly" {{ old('compounding_frequency', $savingsScheme->compounding_frequency) === 'yearly' ? 'selected' : '' }}>Yearly</option>
                    </select>
                    <small class="text-muted">Required only for Compound Interest</small>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3" id="duration-type-field" style="display: none;">
                    <label for="duration_type" class="form-label">Collection Frequency *</label>
                    <select class="form-select @error('duration_type') is-invalid @enderror" id="duration_type" name="duration_type" required>
                        <option value="">Select Frequency</option>
                        <option value="daily" {{ old('duration_type', $savingsScheme->duration_type) === 'daily' ? 'selected' : '' }}>Daily</option>
                        <option value="weekly" {{ old('duration_type', $savingsScheme->duration_type) === 'weekly' ? 'selected' : '' }}>Weekly</option>
                        <option value="monthly" {{ old('duration_type', $savingsScheme->duration_type ?? 'monthly') === 'monthly' ? 'selected' : '' }}>Monthly</option>
                    </select>
                    <small class="text-muted">How often customer will deposit</small>
                    @error('duration_type')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="duration_value" class="form-label">Duration (Number of Installments) *</label>
                    <input type="number" class="form-control @error('duration_value') is-invalid @enderror" 
                           id="duration_value" name="duration_value" value="{{ old('duration_value', $savingsScheme->duration_value) }}" 
                           placeholder="e.g., 12" required>
                    <small class="text-muted" id="duration-hint">Number of times customer will deposit</small>
                    @error('duration_value')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <!-- RD Specific Fields -->
            <div id="rd-fields" class="type-specific-fields" style="display: none;">
                <div class="alert alert-primary">
                    <strong>RD Specific:</strong> Set the fixed installment amount for this scheme.
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="installment_amount" class="form-label"><span id="installment-label">Installment</span> Amount *</label>
                        <input type="number" step="0.01" class="form-control @error('installment_amount') is-invalid @enderror" 
                               id="installment_amount" name="installment_amount" value="{{ old('installment_amount', $savingsScheme->installment_amount) }}" 
                               placeholder="e.g., 5000">
                        <small class="text-muted" id="installment-hint">Fixed amount to be deposited per installment</small>
                        @error('installment_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
            
            <!-- FD/MIS Specific Fields -->
            <div id="fd-mis-fields" class="type-specific-fields" style="display: none;">
                <div class="alert alert-success">
                    <strong>FD/MIS Specific:</strong> Set minimum and maximum principal amount limits.
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="min_amount" class="form-label">Minimum Amount *</label>
                        <input type="number" step="0.01" class="form-control @error('min_amount') is-invalid @enderror" 
                               id="min_amount" name="min_amount" value="{{ old('min_amount', $savingsScheme->min_amount) }}" 
                               placeholder="e.g., 10000">
                        @error('min_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="max_amount" class="form-label">Maximum Amount (Optional)</label>
                        <input type="number" step="0.01" class="form-control @error('max_amount') is-invalid @enderror" 
                               id="max_amount" name="max_amount" value="{{ old('max_amount', $savingsScheme->max_amount) }}" 
                               placeholder="e.g., 1000000">
                        @error('max_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="status" class="form-label">Status *</label>
                    <select class="form-select" id="status" name="status" required>
                        <option value="active" {{ old('status', $savingsScheme->status) === 'active' ? 'selected' : '' }}>Active</option>
                        <option value="inactive" {{ old('status', $savingsScheme->status) === 'inactive' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>
            </div>
            
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Update Savings Scheme
                </button>
                <a href="{{ route('partner.savings-schemes.index') }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const savingsType = document.getElementById('savings_type');
    const interestType = document.getElementById('interest_type');
    const durationType = document.getElementById('duration_type');
    const durationTypeField = document.getElementById('duration-type-field');
    const compoundingSection = document.getElementById('compounding-section');
    const rdFields = document.getElementById('rd-fields');
    const fdMisFields = document.getElementById('fd-mis-fields');
    const installmentLabel = document.getElementById('installment-label');
    const installmentHint = document.getElementById('installment-hint');
    const durationHint = document.getElementById('duration-hint');
    
    // Track if user has manually selected duration_type
    let userSelectedDurationType = true; // Set to true since we're editing
    let lastDurationTypeValue = durationType.value || '{{ $savingsScheme->duration_type ?? "monthly" }}';
    
    function updateFormFields() {
        const type = savingsType.value;
        const interest = interestType.value;
        
        // Hide all type-specific fields
        rdFields.style.display = 'none';
        fdMisFields.style.display = 'none';
        compoundingSection.style.display = 'none';
        durationTypeField.style.display = 'none';
        
        // Show relevant fields based on type
        if (type === 'RD') {
            rdFields.style.display = 'block';
            durationTypeField.style.display = 'block';
            
            // Preserve duration_type value
            if (!durationType.value) {
                durationType.value = lastDurationTypeValue || 'monthly';
            } else {
                lastDurationTypeValue = durationType.value;
            }
            
            if (interest === 'compound') {
                compoundingSection.style.display = 'block';
            }
            updateRDLabels();
        } else if (type === 'FD') {
            fdMisFields.style.display = 'block';
            if (interest === 'compound') {
                compoundingSection.style.display = 'block';
            }
            durationHint.textContent = 'Number of months for the FD';
        } else if (type === 'MIS') {
            fdMisFields.style.display = 'block';
            // MIS always uses simple interest
            interestType.value = 'simple';
            interestType.disabled = true;
            durationHint.textContent = 'Number of months for the MIS';
        } else {
            // Reset MIS restriction
            interestType.disabled = false;
        }
    }
    
    function updateRDLabels() {
        const frequency = durationType.value;
        
        if (frequency === 'daily') {
            installmentLabel.textContent = 'Daily Deposit';
            installmentHint.textContent = 'Fixed amount to be deposited every day';
            durationHint.textContent = 'Number of days customer will deposit';
        } else if (frequency === 'weekly') {
            installmentLabel.textContent = 'Weekly Deposit';
            installmentHint.textContent = 'Fixed amount to be deposited every week';
            durationHint.textContent = 'Number of weeks customer will deposit';
        } else {
            installmentLabel.textContent = 'Monthly Deposit';
            installmentHint.textContent = 'Fixed amount to be deposited every month';
            durationHint.textContent = 'Number of months customer will deposit';
        }
    }
    
    savingsType.addEventListener('change', function() {
        updateFormFields();
    });
    
    interestType.addEventListener('change', function() {
        const type = savingsType.value;
        const interest = interestType.value;
        
        if (type === 'RD' || type === 'FD') {
            if (interest === 'compound') {
                compoundingSection.style.display = 'block';
            } else {
                compoundingSection.style.display = 'none';
            }
        }
        
        if (type === 'MIS') {
            interestType.value = 'simple';
            interestType.disabled = true;
        } else {
            interestType.disabled = false;
        }
    });
    
    durationType.addEventListener('change', function() {
        userSelectedDurationType = true;
        lastDurationTypeValue = this.value;
        updateRDLabels();
    });
    
    // Initialize form on page load
    if (savingsType.value) {
        updateFormFields();
    }
});
</script>
@endpush
@endsection
