{% extends "admin/base_admin.html" %}

{% block title %}Bulk Import - Admin Panel{% endblock %}

{% block page_title %}Bulk Import{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- Navigation -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center space-x-8">
                    <h1 class="text-xl font-semibold text-gray-900 dark:text-white">
                        <i class="fas fa-user-shield text-primary-600 mr-2"></i>
                        Admin Panel
                    </h1>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="{{ url_for('admin_contributions') }}" class="text-primary-600 hover:text-primary-500 text-sm font-medium">
                        ← Back to Contributions
                    </a>
                    <span class="text-sm text-gray-500 dark:text-gray-400">Welcome, {{ current_user.full_name }}</span>
                    <a href="{{ url_for('logout') }}" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Content -->
    <div class="max-w-4xl mx-auto py-6 sm:px-6 lg:px-8">
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white mb-4">
                    <i class="fas fa-upload text-primary-600 mr-2"></i>
                    Bulk Import Historical Data (January 2024 onwards)
                </h3>
                
                <div class="mb-6 p-4 bg-blue-50 dark:bg-blue-900 rounded-lg">
                    <h4 class="text-sm font-medium text-blue-800 dark:text-blue-200 mb-2">Bulk Import for Multiple Members</h4>
                    <p class="text-sm text-blue-700 dark:text-blue-300">
                        Select multiple members and months to quickly add historical contributions. The same amount will be applied to all selected members for each month.
                    </p>
                </div>
                
                <form method="POST" class="space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Select Members</label>
                        <div class="space-y-2 max-h-48 overflow-y-auto border border-gray-300 dark:border-gray-600 rounded-md p-3 bg-gray-50 dark:bg-gray-700">
                            <div class="mb-3">
                                <label class="flex items-center space-x-2">
                                    <input type="checkbox" id="select_all_members" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                                           onchange="toggleAllMembers(this)">
                                    <span class="text-sm font-medium text-gray-900 dark:text-gray-300">Select All Members</span>
                                </label>
                            </div>
                            <div class="border-t border-gray-200 dark:border-gray-600 pt-3">
                                {% for member in members %}
                                <label class="flex items-center space-x-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-600 rounded">
                                    <input type="checkbox" name="member_ids" value="{{ member.id }}" class="member-checkbox h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                                    <div class="flex-1">
                                        <div class="text-sm font-medium text-gray-900 dark:text-gray-300">
                                            {% if member.custom_id %}
                                                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-2">{{ member.custom_id }}</span>
                                            {% endif %}
                                            {{ member.full_name }}
                                        </div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400">@{{ member.username }}</div>
                                    </div>
                                </label>
                                {% endfor %}
                            </div>
                        </div>
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Select one or more members to bulk import contributions for</p>
                    </div>
                    
                    <!-- Import Mode Selection -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Import Mode</label>
                        <div class="flex space-x-4 mb-6">
                            <label class="flex items-center">
                                <input type="radio" name="import_mode" value="simple" checked onchange="toggleImportMode('simple')" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300">
                                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Same Amount for All Months</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="import_mode" value="advanced" onchange="toggleImportMode('advanced')" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300">
                                <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Different Amounts for Different Months</span>
                            </label>
                        </div>
                    </div>

                    <!-- Simple Import Mode -->
                    <div id="simple_import" class="">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Quick Monthly Import</label>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                            <div>
                                <label for="start_month" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Start Month</label>
                                <select name="start_month" id="start_month"
                                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                    <option value="">Select start month</option>
                                    {% set month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] %}
                                    {% for year in range(2024, 2026) %}
                                        {% for month in range(1, 13) %}
                                            {% set month_date = '%04d-%02d-01'|format(year, month) %}
                                            {% set month_name = month_names[month-1] + ' ' + year|string %}
                                            <option value="{{ month_date }}">{{ month_name }}</option>
                                        {% endfor %}
                                    {% endfor %}
                                </select>
                            </div>
                            
                            <div>
                                <label for="end_month" class="block text-sm font-medium text-gray-700 dark:text-gray-300">End Month</label>
                                <select name="end_month" id="end_month"
                                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                    <option value="">Select end month</option>
                                    {% for year in range(2024, 2026) %}
                                        {% for month in range(1, 13) %}
                                            {% set month_date = '%04d-%02d-01'|format(year, month) %}
                                            {% set month_name = month_names[month-1] + ' ' + year|string %}
                                            <option value="{{ month_date }}">{{ month_name }}</option>
                                        {% endfor %}
                                    {% endfor %}
                                </select>
                            </div>
                            
                            <div>
                                <label for="monthly_amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Monthly Amount (৳)</label>
                                <div class="mt-1 space-y-2">
                                    <input type="number" name="monthly_amount" id="monthly_amount" step="0.01" min="0"
                                           class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                    <div class="flex gap-1">
                                        <button type="button" onclick="document.getElementById('monthly_amount').value = 4000" class="px-2 py-1 text-xs font-medium rounded bg-blue-600 text-white hover:bg-blue-700">৳4,000</button>
                                        <button type="button" onclick="document.getElementById('monthly_amount').value = 5000" class="px-2 py-1 text-xs font-medium rounded bg-green-600 text-white hover:bg-green-700">৳5,000</button>
                                        <button type="button" onclick="document.getElementById('monthly_amount').value = 6000" class="px-2 py-1 text-xs font-medium rounded bg-purple-600 text-white hover:bg-purple-700">৳6,000</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="p-3 bg-green-50 dark:bg-green-900 rounded-lg">
                            <h4 class="text-sm font-medium text-green-800 dark:text-green-200 mb-1">Simple Process:</h4>
                            <ol class="text-xs text-green-700 dark:text-green-300 space-y-1">
                                <li>1. Select start month (e.g., January 2024)</li>
                                <li>2. Select end month (e.g., April 2025)</li>
                                <li>3. Enter monthly amount or click preset</li>
                                <li>4. All months between start and end will use the same amount</li>
                            </ol>
                        </div>
                    </div>
                    
                    <!-- Advanced Import Mode -->
                    <div id="advanced_import" class="hidden">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Advanced: Select Individual Months with Different Amounts</label>
                        
                        <div class="space-y-4 max-h-96 overflow-y-auto border border-gray-300 dark:border-gray-600 rounded-md p-4">
                            {% for year in range(2024, 2026) %}
                                <div>
                                    <h4 class="font-medium text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700 pb-2 mb-3">{{ year }}</h4>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        {% set month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] %}
                                        {% for month in range(1, 13) %}
                                            {% set month_date = '%04d-%02d-01'|format(year, month) %}
                                            {% set month_name = month_names[month-1] %}
                                            <div class="flex items-center space-x-3 p-2 bg-gray-50 dark:bg-gray-700 rounded">
                                                <input type="checkbox" name="months" id="month_{{ year }}_{{ month }}" value="{{ month_date }}"
                                                       class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                                                       onchange="toggleAmountField('{{ year }}_{{ month }}')">
                                                <label for="month_{{ year }}_{{ month }}" class="flex-1 text-sm text-gray-900 dark:text-gray-300">
                                                    {{ month_name }}
                                                </label>
                                                <input type="number" name="amount_{{ year }}_{{ month }}" id="amount_{{ year }}_{{ month }}" 
                                                       step="0.01" min="0" placeholder="Amount (৳)" disabled
                                                       class="w-24 text-sm border-gray-300 rounded shadow-sm focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800">
                                            </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                        <div class="mt-2 p-3 bg-yellow-50 dark:bg-yellow-900 rounded-lg">
                            <h4 class="text-sm font-medium text-yellow-800 dark:text-yellow-200 mb-1">Advanced Import Instructions:</h4>
                            <ol class="text-xs text-yellow-700 dark:text-yellow-300 space-y-1">
                                <li>1. Check the months you want to import</li>
                                <li>2. Enter different amounts for each month as needed</li>
                                <li>3. Use preset buttons below to fill ALL checked months with the same amount</li>
                                <li>4. Months without amounts will be skipped</li>
                            </ol>
                            <div class="mt-3 flex gap-2">
                                <button type="button" onclick="fillAllCheckedMonths(4000)" class="px-3 py-1 text-xs font-medium rounded bg-blue-600 text-white hover:bg-blue-700">Fill All: ৳4,000</button>
                                <button type="button" onclick="fillAllCheckedMonths(5000)" class="px-3 py-1 text-xs font-medium rounded bg-green-600 text-white hover:bg-green-700">Fill All: ৳5,000</button>
                                <button type="button" onclick="fillAllCheckedMonths(6000)" class="px-3 py-1 text-xs font-medium rounded bg-purple-600 text-white hover:bg-purple-700">Fill All: ৳6,000</button>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <label for="contribution_type" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Contribution Type</label>
                        <select name="contribution_type" id="contribution_type" required
                                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="monthly">Monthly Contribution</option>
                            <option value="penalty">Penalty</option>
                            <option value="bonus">Bonus Payment</option>
                            <option value="special">Special Collection</option>
                        </select>
                    </div>
                    
                    <div>
                        <label for="description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
                        <textarea name="description" id="description" rows="2"
                                  class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                                  placeholder="Historical data import from January 2024"></textarea>
                    </div>
                    
                    <div class="flex justify-end space-x-3">
                        <a href="{{ url_for('admin_contributions') }}" 
                           class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600">
                            Cancel
                        </a>
                        <button type="submit"
                                class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700">
                            <i class="fas fa-upload mr-2"></i>Import for Selected Members
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle amount field when checkbox is checked/unchecked
function toggleAmountField(monthId) {
    const checkbox = document.getElementById(`month_${monthId}`);
    const amountField = document.getElementById(`amount_${monthId}`);
    
    if (checkbox.checked) {
        amountField.disabled = false;
        amountField.focus();
        amountField.required = true;
    } else {
        amountField.disabled = true;
        amountField.value = '';
        amountField.required = false;
    }
}

// Select/deselect all months for a year
document.querySelectorAll('h4').forEach(function(yearHeader) {
    yearHeader.addEventListener('click', function() {
        const year = this.textContent;
        const yearCheckboxes = document.querySelectorAll(`input[id*="month_${year}"]`);
        const allChecked = Array.from(yearCheckboxes).every(cb => cb.checked);
        
        yearCheckboxes.forEach(function(checkbox) {
            checkbox.checked = !allChecked;
            const monthId = checkbox.id.replace('month_', '');
            toggleAmountField(monthId);
        });
    });
    
    // Add visual cue that year headers are clickable
    yearHeader.style.cursor = 'pointer';
    yearHeader.title = 'Click to select/deselect all months for this year';
});

// Toggle all members selection
function toggleAllMembers(selectAllCheckbox) {
    const memberCheckboxes = document.querySelectorAll('.member-checkbox');
    memberCheckboxes.forEach(function(checkbox) {
        checkbox.checked = selectAllCheckbox.checked;
    });
}

// Update select all checkbox when individual member checkboxes change
document.querySelectorAll('.member-checkbox').forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        const allMemberCheckboxes = document.querySelectorAll('.member-checkbox');
        const checkedMemberCheckboxes = document.querySelectorAll('.member-checkbox:checked');
        const selectAllCheckbox = document.getElementById('select_all_members');
        
        if (checkedMemberCheckboxes.length === allMemberCheckboxes.length) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else if (checkedMemberCheckboxes.length > 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        }
    });
});

// Apply preset amount to all checked months
function applyAmountToSelected(amount) {
    const checkedMonths = document.querySelectorAll('input[name="months"]:checked');
    if (checkedMonths.length === 0) {
        alert('Please select months first by checking the checkboxes.');
        return;
    }
    
    checkedMonths.forEach(function(checkbox) {
        const monthId = checkbox.id.replace('month_', '');
        const amountField = document.getElementById(`amount_${monthId}`);
        if (amountField && !amountField.disabled) {
            amountField.value = amount;
        }
    });
    
    // Show confirmation
    const monthCount = checkedMonths.length;
    const totalAmount = amount * monthCount;
    showNotification(`Applied ৳${amount.toLocaleString()} to ${monthCount} selected months. Total: ৳${totalAmount.toLocaleString()}`);
}

// Clear all amount fields
function clearAllAmounts() {
    const amountFields = document.querySelectorAll('input[id^="amount_"]');
    amountFields.forEach(function(field) {
        field.value = '';
    });
    showNotification('All amounts cleared');
}

// Show temporary notification
function showNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg z-50';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(function() {
        notification.remove();
    }, 3000);
}

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const checkedMembers = document.querySelectorAll('.member-checkbox:checked');
    if (checkedMembers.length === 0) {
        e.preventDefault();
        alert('Please select at least one member.');
        return;
    }
    
    const checkedBoxes = document.querySelectorAll('input[name="months"]:checked');
    if (checkedBoxes.length === 0) {
        e.preventDefault();
        alert('Please select at least one month.');
        return;
    }
    
    let hasEmptyAmount = false;
    checkedBoxes.forEach(function(checkbox) {
        const monthId = checkbox.id.replace('month_', '');
        const amountField = document.getElementById(`amount_${monthId}`);
        if (!amountField.value || parseFloat(amountField.value) <= 0) {
            hasEmptyAmount = true;
        }
    });
    
    if (hasEmptyAmount) {
        e.preventDefault();
        alert('Please enter a valid amount for all selected months.');
        return;
    }
});
</script>
{% endblock %}