@extends('layouts.app')

@section('title', 'Create Savings Account')
@section('page-title', 'Create Savings Account')

@section('content')
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">Create Savings Account</h5>
    </div>
    <div class="card-body">
        <div class="alert alert-info">
            <i class="bi bi-info-circle"></i> <strong>How it works:</strong>
            <ol class="mb-0 mt-2">
                <li>Select a <strong>Savings Scheme</strong> (defines type, interest rate, duration)</li>
                <li>Select <strong>Customer</strong></li>
                <li>Enter amount details based on scheme type</li>
                <li>For <strong>RD</strong>: Collect monthly installments via Savings Collections</li>
                <li>For <strong>FD/MIS</strong>: Pay principal amount upfront</li>
            </ol>
        </div>
        
        @if($savingsSchemes->isEmpty())
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle"></i> No active savings schemes available. 
                <a href="{{ route('partner.savings-schemes.create') }}" class="alert-link">Create a savings scheme first</a>.
            </div>
        @else
        
        <form action="{{ route('partner.savings.store') }}" method="POST" id="savingsForm">
            @csrf
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="savings_scheme_id" class="form-label">Savings Scheme *</label>
                    <select class="form-select @error('savings_scheme_id') is-invalid @enderror" 
                            id="savings_scheme_id" name="savings_scheme_id" required>
                        <option value="">Select Savings Scheme</option>
                        @foreach($savingsSchemes as $scheme)
                            <option value="{{ $scheme->id }}" 
                                    data-type="{{ $scheme->savings_type }}"
                                    data-interest-rate="{{ $scheme->interest_rate }}"
                                    data-interest-type="{{ $scheme->interest_type ?? 'compound' }}"
                                    data-duration="{{ $scheme->duration_value }}"
                                    data-duration-type="{{ $scheme->duration_type ?? 'monthly' }}"
                                    data-compounding="{{ $scheme->compounding_frequency ?? 'monthly' }}"
                                    data-min="{{ $scheme->min_amount }}"
                                    data-max="{{ $scheme->max_amount }}"
                                    data-installment="{{ $scheme->installment_amount }}"
                                    {{ old('savings_scheme_id') == $scheme->id ? 'selected' : '' }}>
                                [{{ $scheme->savings_type }}] {{ $scheme->name }} 
                                ({{ $scheme->interest_rate }}% | {{ $scheme->duration_value }} {{ $scheme->savings_type === 'RD' ? $scheme->duration_type : 'months' }})
                            </option>
                        @endforeach
                    </select>
                    @error('savings_scheme_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                    <small class="text-muted">Scheme defines the type, interest rate, and duration</small>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="customer_id" class="form-label">Customer *</label>
                    <select class="form-select @error('customer_id') is-invalid @enderror" 
                            id="customer_id" name="customer_id" required>
                        <option value="">Select Customer</option>
                        @foreach($customers as $customer)
                            <option value="{{ $customer->id }}" {{ old('customer_id') == $customer->id ? 'selected' : '' }}>
                                {{ $customer->name }} ({{ $customer->customer_code }})
                            </option>
                        @endforeach
                    </select>
                    @error('customer_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <!-- Scheme Details Display -->
            <div id="scheme-details" class="mb-3" style="display: none;">
                <div class="card bg-light">
                    <div class="card-body">
                        <h6 class="mb-3">Scheme Details</h6>
                        <div class="row">
                            <div class="col-md-3">
                                <strong>Type:</strong> <span id="display-type" class="badge bg-primary"></span>
                            </div>
                            <div class="col-md-3">
                                <strong>Interest Rate:</strong> <span id="display-rate"></span>% p.a.
                            </div>
                            <div class="col-md-3">
                                <strong>Duration:</strong> <span id="display-duration"></span> months
                            </div>
                            <div class="col-md-3">
                                <strong>Compounding:</strong> <span id="display-compounding"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- RD Specific Fields -->
            <div id="rd-fields" class="type-fields" style="display: none;">
                <div class="alert alert-primary">
                    <strong>RD (Recurring Deposit):</strong> Customer will deposit <span id="rd-frequency-text">regular</span> installments. 
                    Collect installments via Savings Collections after account creation.
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="monthly_deposit" class="form-label"><span id="rd-deposit-label">Deposit</span> Amount *</label>
                        <input type="number" step="0.01" 
                               class="form-control @error('monthly_deposit') is-invalid @enderror" 
                               id="monthly_deposit" name="monthly_deposit" 
                               value="{{ old('monthly_deposit') }}" 
                               placeholder="Enter deposit amount">
                        <small class="text-muted" id="rd-limits"></small>
                        @error('monthly_deposit')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div id="rd-calculation" class="mb-3" style="display: none;">
                    <div class="card bg-light">
                        <div class="card-body">
                            <h6>Calculation Preview</h6>
                            <p><strong>Total Deposits:</strong> ₹<span id="rd-total-deposits">0</span></p>
                            <p><strong>Maturity Amount:</strong> <span class="text-success">₹<span id="rd-maturity">0</span></span></p>
                            <p class="mb-0"><strong>Total Interest:</strong> ₹<span id="rd-interest">0</span></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- FD Specific Fields -->
            <div id="fd-fields" class="type-fields" style="display: none;">
                <div class="alert alert-success">
                    <strong>FD (Fixed Deposit):</strong> One-time lump sum deposit. Principal + interest returned at maturity.
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="principal_amount_fd" class="form-label">Principal Amount *</label>
                        <input type="number" step="0.01" 
                               class="form-control @error('principal_amount') is-invalid @enderror" 
                               id="principal_amount_fd" name="principal_amount" 
                               value="{{ old('principal_amount') }}" 
                               placeholder="Enter principal amount">
                        <small class="text-muted" id="fd-limits"></small>
                        @error('principal_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="payment_method_fd" class="form-label">Payment Method *</label>
                        <select class="form-select" id="payment_method_fd" name="payment_method">
                            <option value="cash" {{ old('payment_method') == 'cash' ? 'selected' : '' }}>Cash</option>
                            <option value="bank_transfer" {{ old('payment_method') == 'bank_transfer' ? 'selected' : '' }}>Bank Transfer</option>
                            <option value="cheque" {{ old('payment_method') == 'cheque' ? 'selected' : '' }}>Cheque</option>
                            <option value="other" {{ old('payment_method') == 'other' ? 'selected' : '' }}>Other</option>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="reference_number_fd" class="form-label">Reference Number</label>
                        <input type="text" class="form-control" id="reference_number_fd" 
                               name="reference_number" value="{{ old('reference_number') }}" 
                               placeholder="Transaction/Cheque number">
                    </div>
                </div>
                <div id="fd-calculation" class="mb-3" style="display: none;">
                    <div class="card bg-light">
                        <div class="card-body">
                            <h6>Calculation Preview</h6>
                            <p><strong>Principal:</strong> ₹<span id="fd-principal">0</span></p>
                            <p><strong>Maturity Amount:</strong> <span class="text-success">₹<span id="fd-maturity">0</span></span></p>
                            <p class="mb-0"><strong>Total Interest:</strong> ₹<span id="fd-interest">0</span></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- MIS Specific Fields -->
            <div id="mis-fields" class="type-fields" style="display: none;">
                <div class="alert alert-warning">
                    <strong>MIS (Monthly Income Scheme):</strong> One-time deposit. Monthly interest payouts. Principal returned at maturity.
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="principal_amount_mis" class="form-label">Principal Amount *</label>
                        <input type="number" step="0.01" 
                               class="form-control @error('principal_amount') is-invalid @enderror" 
                               id="principal_amount_mis" name="principal_amount" 
                               value="{{ old('principal_amount') }}" 
                               placeholder="Enter principal amount">
                        <small class="text-muted" id="mis-limits"></small>
                        @error('principal_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="payment_method_mis" class="form-label">Payment Method *</label>
                        <select class="form-select" id="payment_method_mis" name="payment_method">
                            <option value="cash" {{ old('payment_method') == 'cash' ? 'selected' : '' }}>Cash</option>
                            <option value="bank_transfer" {{ old('payment_method') == 'bank_transfer' ? 'selected' : '' }}>Bank Transfer</option>
                            <option value="cheque" {{ old('payment_method') == 'cheque' ? 'selected' : '' }}>Cheque</option>
                            <option value="other" {{ old('payment_method') == 'other' ? 'selected' : '' }}>Other</option>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="reference_number_mis" class="form-label">Reference Number</label>
                        <input type="text" class="form-control" id="reference_number_mis" 
                               name="reference_number" value="{{ old('reference_number') }}" 
                               placeholder="Transaction/Cheque number">
                    </div>
                </div>
                <div id="mis-calculation" class="mb-3" style="display: none;">
                    <div class="card bg-light">
                        <div class="card-body">
                            <h6>Calculation Preview</h6>
                            <p><strong>Principal:</strong> ₹<span id="mis-principal">0</span></p>
                            <p><strong>Monthly Interest Payout:</strong> <span class="text-success">₹<span id="mis-monthly">0</span></span></p>
                            <p><strong>Total Interest Payouts:</strong> ₹<span id="mis-total-interest">0</span></p>
                            <p class="mb-0"><strong>Maturity Amount:</strong> ₹<span id="mis-maturity">0</span> (Principal returned)</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="deposit_date" class="form-label">Deposit Date *</label>
                    <input type="date" class="form-control @error('deposit_date') is-invalid @enderror" 
                           id="deposit_date" name="deposit_date" 
                           value="{{ old('deposit_date', date('Y-m-d')) }}" required>
                    @error('deposit_date')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <div class="mb-3">
                <label for="notes" class="form-label">Notes</label>
                <textarea class="form-control" id="notes" name="notes" rows="3">{{ old('notes') }}</textarea>
            </div>
            
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Create Savings Account
                </button>
                <a href="{{ route('partner.savings.index') }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
        
        @endif
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const schemeSelect = document.getElementById('savings_scheme_id');
    const schemeDetails = document.getElementById('scheme-details');
    const rdFields = document.getElementById('rd-fields');
    const fdFields = document.getElementById('fd-fields');
    const misFields = document.getElementById('mis-fields');
    
    let currentScheme = null;
    
    schemeSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        
        if (!this.value) {
            schemeDetails.style.display = 'none';
            rdFields.style.display = 'none';
            fdFields.style.display = 'none';
            misFields.style.display = 'none';
            return;
        }
        
        currentScheme = {
            type: selectedOption.dataset.type,
            rate: parseFloat(selectedOption.dataset.interestRate),
            interestType: selectedOption.dataset.interestType || 'compound',
            duration: parseInt(selectedOption.dataset.duration),
            durationType: selectedOption.dataset.durationType || 'monthly',
            compounding: selectedOption.dataset.compounding || 'monthly',
            min: parseFloat(selectedOption.dataset.min) || 0,
            max: parseFloat(selectedOption.dataset.max) || 0,
            installment: parseFloat(selectedOption.dataset.installment) || 0,
        };
        
        // Show scheme details
        document.getElementById('display-type').textContent = currentScheme.type;
        document.getElementById('display-rate').textContent = currentScheme.rate;
        document.getElementById('display-duration').textContent = currentScheme.duration;
        document.getElementById('display-compounding').textContent = currentScheme.compounding || 'N/A';
        schemeDetails.style.display = 'block';
        
        // Hide all type fields
        rdFields.style.display = 'none';
        fdFields.style.display = 'none';
        misFields.style.display = 'none';
        
        // Show relevant fields
        if (currentScheme.type === 'RD') {
            rdFields.style.display = 'block';
            
            // Update labels based on frequency
            const freqLabel = currentScheme.durationType === 'daily' ? 'Daily' :
                            currentScheme.durationType === 'weekly' ? 'Weekly' : 'Monthly';
            document.getElementById('rd-frequency-text').textContent = freqLabel.toLowerCase();
            document.getElementById('rd-deposit-label').textContent = freqLabel + ' Deposit';
            
            if (currentScheme.installment > 0) {
                document.getElementById('monthly_deposit').value = currentScheme.installment;
                calculateRD();
            }
            updateLimits('rd', currentScheme.min, currentScheme.max);
        } else if (currentScheme.type === 'FD') {
            fdFields.style.display = 'block';
            updateLimits('fd', currentScheme.min, currentScheme.max);
        } else if (currentScheme.type === 'MIS') {
            misFields.style.display = 'block';
            updateLimits('mis', currentScheme.min, currentScheme.max);
        }
    });
    
    function updateLimits(type, min, max) {
        let text = '';
        if (min > 0) text += `Min: ₹${min.toLocaleString('en-IN')}`;
        if (max > 0) text += ` | Max: ₹${max.toLocaleString('en-IN')}`;
        document.getElementById(type + '-limits').textContent = text;
    }
    
    // RD Calculation
    document.getElementById('monthly_deposit')?.addEventListener('input', calculateRD);
    
    function calculateRD() {
        if (!currentScheme || currentScheme.type !== 'RD') return;
        
        const installment = parseFloat(document.getElementById('monthly_deposit').value) || 0;
        if (installment <= 0) {
            document.getElementById('rd-calculation').style.display = 'none';
            return;
        }
        
        const duration = currentScheme.duration;
        const rate = currentScheme.rate;
        const interestType = currentScheme.interestType;
        const totalDeposits = installment * duration;
        
        let maturity, interest;
        
        if (interestType === 'simple') {
            // Simple Interest RD: Interest = (P × n × (n + 1) × r) / (2 × 12 × 100)
            interest = (installment * duration * (duration + 1) * rate) / (2 * 12 * 100);
            maturity = totalDeposits + interest;
        } else {
            // Compound Interest RD
            const durationMonths = currentScheme.durationType === 'daily' ? Math.ceil(duration / 30) :
                                  currentScheme.durationType === 'weekly' ? Math.ceil(duration / 4) : duration;
            
            const annualRate = rate / 100;
            const compounding = currentScheme.compounding || 'monthly';
            const n = compounding === 'monthly' ? 12 : (compounding === 'quarterly' ? 4 : 1);
            const years = durationMonths / 12;
            const periodicRate = annualRate / n;
            const totalPeriods = n * years;
            
            const installmentsPerYear = currentScheme.durationType === 'daily' ? 365 :
                                       currentScheme.durationType === 'weekly' ? 52 : 12;
            
            if (periodicRate > 0) {
                maturity = installment * installmentsPerYear * 
                          ((Math.pow(1 + periodicRate, totalPeriods) - 1) / periodicRate) * 
                          (1 + periodicRate) / (installmentsPerYear / n);
            } else {
                maturity = totalDeposits;
            }
            interest = maturity - totalDeposits;
        }
        
        document.getElementById('rd-total-deposits').textContent = totalDeposits.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('rd-maturity').textContent = maturity.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('rd-interest').textContent = interest.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('rd-calculation').style.display = 'block';
    }
    
    // FD Calculation
    document.getElementById('principal_amount_fd')?.addEventListener('input', calculateFD);
    
    function calculateFD() {
        if (!currentScheme || currentScheme.type !== 'FD') return;
        
        const principal = parseFloat(document.getElementById('principal_amount_fd').value) || 0;
        if (principal <= 0) {
            document.getElementById('fd-calculation').style.display = 'none';
            return;
        }
        
        const years = currentScheme.duration / 12;
        const rate = currentScheme.rate / 100;
        const interestType = currentScheme.interestType;
        
        let maturity, interest;
        
        if (interestType === 'simple') {
            // Simple Interest FD: A = P × (1 + r×t)
            interest = principal * rate * years;
            maturity = principal + interest;
        } else {
            // Compound Interest FD: A = P × (1 + r/n)^(n×t)
            const n = currentScheme.compounding === 'monthly' ? 12 : 
                     (currentScheme.compounding === 'quarterly' ? 4 : 1);
            maturity = principal * Math.pow(1 + (rate / n), n * years);
            interest = maturity - principal;
        }
        
        document.getElementById('fd-principal').textContent = principal.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('fd-maturity').textContent = maturity.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('fd-interest').textContent = interest.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('fd-calculation').style.display = 'block';
    }
    
    // MIS Calculation
    document.getElementById('principal_amount_mis')?.addEventListener('input', calculateMIS);
    
    function calculateMIS() {
        if (!currentScheme || currentScheme.type !== 'MIS') return;
        
        const principal = parseFloat(document.getElementById('principal_amount_mis').value) || 0;
        if (principal <= 0) {
            document.getElementById('mis-calculation').style.display = 'none';
            return;
        }
        
        const monthlyInterest = (principal * currentScheme.rate / 100) / 12;
        const totalInterest = monthlyInterest * currentScheme.duration;
        
        document.getElementById('mis-principal').textContent = principal.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('mis-monthly').textContent = monthlyInterest.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('mis-total-interest').textContent = totalInterest.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('mis-maturity').textContent = principal.toLocaleString('en-IN', {minimumFractionDigits: 2});
        document.getElementById('mis-calculation').style.display = 'block';
    }
    
    // Trigger on page load if scheme is pre-selected
    if (schemeSelect.value) {
        schemeSelect.dispatchEvent(new Event('change'));
    }
});
</script>
@endpush
@endsection
