{% extends 'base.html' %}
{% load static %}

{% block title %}Add Existing Loan{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto py-8">
    <div class="bg-white shadow rounded-lg p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold flex items-center">
                <span>+</span> Add Existing Loan
            </h2>
            <a href="{% url 'loans:loans' %}" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                <span>←</span>
                Back to Loans
            </a>
        </div>
        
        <form method="post" id="addLoanForm" class="space-y-6">
            {% csrf_token %}
            
            <!-- Client Selection -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Client Information</h3>
                <div class="mb-4">
                    <label for="client" class="block text-sm font-medium text-gray-700">Select Client</label>
                    <div class="relative mt-1">
                        <input type="text" id="clientSearch" placeholder="Search clients by name, email, or phone..." 
                               class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
                        <select id="client" name="client" class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                            <option value="">-- Select a client --</option>
                            {% for borrower in borrowers %}
                                <option value="{{ borrower.pk }}" data-name="{{ borrower.get_full_name }}" data-email="{{ borrower.email }}" data-phone="{{ borrower.phone_number }}">
                                    {{ borrower.get_full_name }} ({{ borrower.email }}, {{ borrower.phone_number }})
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div id="selectedClientInfo" class="mt-3 hidden">
                        <div class="bg-blue-50 border border-blue-200 rounded-md p-3">
                            <h4 class="text-sm font-medium text-blue-900">Selected Client</h4>
                            <div class="mt-2 text-sm text-blue-800">
                                <p><strong>Name:</strong> <span id="clientName"></span></p>
                                <p><strong>Email:</strong> <span id="clientEmail"></span></p>
                                <p><strong>Phone:</strong> <span id="clientPhone"></span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Loan Details -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Loan Details</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="loan_number" class="block text-sm font-medium text-gray-700">Loan Number</label>
                        <input type="text" id="loan_number" name="loan_number" 
                               placeholder="e.g., LOAN-2024-001" 
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                    </div>
                    <div>
                        <label for="amount" class="block text-sm font-medium text-gray-700">Amount (KES)</label>
                        <input type="number" id="amount" name="amount" step="0.01" min="1" 
                               placeholder="0.00" 
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                    </div>
                </div>
            </div>

            <!-- Dates -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Important Dates</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="disbursement_date" class="block text-sm font-medium text-gray-700">Disbursement Date</label>
                        <input type="date" id="disbursement_date" name="disbursement_date" 
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                    </div>
                    <div>
                        <label for="due_date" class="block text-sm font-medium text-gray-700">Due Date</label>
                        <input type="date" id="due_date" name="due_date" 
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                    </div>
                </div>
            </div>

            <!-- Status -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Loan Status</h3>
                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700">Current Status</label>
                    <select id="status" name="status" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50" required>
                        <option value="">-- Select status --</option>
                        <option value="active">Active</option>
                        <option value="paid">Paid</option>
                        <option value="defaulted">Defaulted</option>
                        <option value="rolled_over">Rolled Over</option>
                        <option value="written_off">Written Off</option>
                    </select>
                    <p class="mt-1 text-sm text-gray-500">Select the current status of this existing loan</p>
                </div>
            </div>

            <!-- Submit Button -->
            <div class="flex justify-end space-x-3">
                <a href="{% url 'loans:loans' %}" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                    Cancel
                </a>
                <button type="submit" class="inline-flex items-center px-4 py-2 bg-primary text-white text-sm font-medium rounded-md shadow-sm hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    <span>💾</span> Add Loan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const clientSearch = document.getElementById('clientSearch');
    const clientSelect = document.getElementById('client');
    const selectedClientInfo = document.getElementById('selectedClientInfo');
    const clientName = document.getElementById('clientName');
    const clientEmail = document.getElementById('clientEmail');
    const clientPhone = document.getElementById('clientPhone');
    const form = document.getElementById('addLoanForm');
    const disbursementDate = document.getElementById('disbursement_date');
    const dueDate = document.getElementById('due_date');

    // Set default dates
    const today = new Date().toISOString().split('T')[0];
    disbursementDate.value = today;
    
    // Set due date to 30 days from today
    const dueDateObj = new Date();
    dueDateObj.setDate(dueDateObj.getDate() + 30);
    dueDate.value = dueDateObj.toISOString().split('T')[0];

    // Client search functionality
    clientSearch.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const options = clientSelect.querySelectorAll('option');
        
        options.forEach(option => {
            if (option.value === '') return; // Skip placeholder option
            
            const text = option.text.toLowerCase();
            if (text.includes(searchTerm)) {
                option.style.display = '';
            } else {
                option.style.display = 'none';
            }
        });
    });

    // Show selected client info
    clientSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        
        if (this.value) {
            clientName.textContent = selectedOption.dataset.name;
            clientEmail.textContent = selectedOption.dataset.email;
            clientPhone.textContent = selectedOption.dataset.phone;
            selectedClientInfo.classList.remove('hidden');
        } else {
            selectedClientInfo.classList.add('hidden');
        }
    });

    // Form validation
    form.addEventListener('submit', function(e) {
        let isValid = true;
        
        // Check if client is selected
        if (!clientSelect.value) {
            clientSelect.classList.add('border-red-500');
            isValid = false;
        } else {
            clientSelect.classList.remove('border-red-500');
        }
        
        // Check if due date is after disbursement date
        if (dueDate.value && disbursementDate.value && dueDate.value <= disbursementDate.value) {
            dueDate.classList.add('border-red-500');
            alert('Due date must be after disbursement date');
            isValid = false;
        } else {
            dueDate.classList.remove('border-red-500');
        }
        
        // Check if amount is valid
        const amount = parseFloat(document.getElementById('amount').value);
        if (!amount || amount <= 0) {
            document.getElementById('amount').classList.add('border-red-500');
            isValid = false;
        } else {
            document.getElementById('amount').classList.remove('border-red-500');
        }
        
        if (!isValid) {
            e.preventDefault();
        }
    });

    // Auto-generate loan number
    document.getElementById('loan_number').addEventListener('focus', function() {
        if (!this.value) {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            this.value = `LOAN-${year}${month}${day}-001`;
        }
    });
});
</script>
{% endblock %}