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

{% block title %}M-Pesa Callbacks{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">M-Pesa Callback Logs</h1>
                <a href="{% url 'payments:dashboard' %}" class="btn btn-outline-secondary">
                    <span>←</span> Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card shadow mb-4">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-primary">Filters</h6>
        </div>
        <div class="card-body">
            <form method="get" class="row">
                <div class="col-md-3">
                    <select name="type" class="form-control">
                        <option value="">All Types</option>
                        {% for value, label in callback_types %}
                            <option value="{{ value }}" {% if filters.type == value %}selected{% endif %}>
                                {{ label }}
                            </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-3">
                    <select name="processed" class="form-control">
                        <option value="">All Status</option>
                        <option value="true" {% if filters.processed == 'true' %}selected{% endif %}>Processed</option>
                        <option value="false" {% if filters.processed == 'false' %}selected{% endif %}>Pending</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary">
                        <span>🔍</span> Apply Filters
                    </button>
                    <a href="{% url 'payments:callbacks' %}" class="btn btn-secondary">
                        <span>✕</span> Clear
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Callbacks Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                Callback Logs
                <span class="badge badge-info">{{ page_obj.paginator.count }} total</span>
            </h6>
        </div>
        <div class="card-body">
            {% if page_obj %}
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Type</th>
                                <th>Transaction</th>
                                <th>Who Paid</th>
                                <th>Phone</th>
                                <th>Amount</th>
                                <th>Repayment</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for callback in page_obj %}
                                <tr>
                                    <td>
                                        <small>{{ callback.created_at|date:"Y-m-d H:i:s" }}</small>
                                    </td>
                                    <td>
                                        {% if callback.callback_type == 'validation' %}
                                            <span class="badge badge-info">Validation</span>
                                        {% else %}
                                            <span class="badge badge-success">Confirmation</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.transaction %}
                                            <a href="{% url 'payments:transaction_detail' callback.transaction.id %}">
                                                {{ callback.transaction.trans_id|default:"N/A" }}
                                            </a>
                                            <br>
                                            <small class="text-muted">
                                                ID: {{ callback.transaction.bill_ref_number|default:"N/A" }}
                                            </small>
                                        {% else %}
                                            <span class="text-muted">Not linked</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.transaction and callback.transaction.borrower %}
                                            <strong>{{ callback.transaction.borrower.get_full_name|default:callback.transaction.borrower.email }}</strong>
                                            <br>
                                            <small class="text-muted">
                                                ID: {{ callback.transaction.borrower.id_number|default:"N/A" }}
                                            </small>
                                        {% elif callback.transaction %}
                                            <span class="text-warning">
                                                <span>⚠️</span> Not matched
                                            </span>
                                            {% if callback.transaction.bill_ref_number %}
                                                <br>
                                                <small class="text-muted">
                                                    Bill Ref: {{ callback.transaction.bill_ref_number }}
                                                </small>
                                            {% endif %}
                                            <br>
                                            <button type="button" 
                                                    class="btn btn-sm btn-primary mt-1" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#matchModal{{ callback.transaction.id }}"
                                                    title="Manually match to a specific loan">
                                                <span>💰</span> Match to Loan
                                            </button>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.transaction %}
                                            {% with phone=callback.transaction.msisdn|default:callback.transaction.phone_number %}
                                                {% if phone %}
                                                    {% if phone|length > 17 or 'a' in phone|lower or 'b' in phone|lower or 'c' in phone|lower or 'd' in phone|lower or 'e' in phone|lower or 'f' in phone|lower %}
                                                        <span class="badge badge-warning" title="Hashed/Encrypted Phone Number">
                                                            <span>🔒</span> {{ phone|truncatechars:20 }}
                                                        </span>
                                                        <br>
                                                        <small class="text-muted">(Matched by ID)</small>
                                                    {% else %}
                                                        <small>{{ phone|truncatechars:15 }}</small>
                                                    {% endif %}
                                                {% else %}
                                                    <span class="text-muted">N/A</span>
                                                {% endif %}
                                            {% endwith %}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.transaction %}
                                            <strong>KES {{ callback.transaction.amount|floatformat:2|intcomma }}</strong>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.transaction and callback.transaction.repayment %}
                                            <span class="badge badge-success">
                                                <span>🧾</span> {{ callback.transaction.repayment.receipt_number }}
                                            </span>
                                            <br>
                                            <a href="{% url 'loans:loan_detail' callback.transaction.repayment.loan.id %}" 
                                               class="text-muted">
                                                <small>Loan: {{ callback.transaction.repayment.loan.loan_number|default:"N/A" }}</small>
                                            </a>
                                            <br>
                                            <a href="{% url 'loans:repayments' %}" class="text-primary">
                                                <small><span>📋</span> View in Repayments</small>
                                            </a>
                                        {% elif callback.transaction %}
                                            <span class="badge badge-secondary">
                                                <span>✕</span> No Repayment
                                            </span>
                                            {% if callback.transaction.processing_notes %}
                                                <br>
                                                <small class="text-muted" title="{{ callback.transaction.processing_notes }}">
                                                    {{ callback.transaction.processing_notes|truncatewords:5 }}
                                                </small>
                                            {% endif %}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if callback.processed %}
                                            <span class="badge badge-success">
                                                <span>✓</span> Processed
                                            </span>
                                        {% else %}
                                            <span class="badge badge-warning">
                                                <span>⏰</span> Pending
                                            </span>
                                        {% endif %}
                                        {% if callback.transaction %}
                                            <br>
                                            <small class="text-muted">
                                                {{ callback.transaction.get_status_display }}
                                            </small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-info" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#callbackModal{{ callback.id }}"
                                                title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        {% if callback.transaction and not callback.transaction.repayment %}
                                            <a href="{% url 'payments:reprocess_transaction' callback.transaction.id %}?redirect_to=payments:callbacks" 
                                               class="btn btn-sm btn-warning"
                                               title="Retry Matching Payment (useful if ID was added after payment)">
                                                <span>↷</span> Retry
                                            </a>
                                        {% endif %}
                                    </td>
                                </tr>

                                <!-- Modal for callback details -->
                                <div class="modal fade" id="callbackModal{{ callback.id }}" tabindex="-1" role="dialog">
                                    <div class="modal-dialog modal-lg" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title">
                                                    Callback Details - {{ callback.callback_type|title }}
                                                </h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                                            </div>
                                            <div class="modal-body">
                                                {% if callback.transaction %}
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <h6>Transaction Details</h6>
                                                            <ul class="list-unstyled">
                                                                <li><strong>Transaction ID:</strong> {{ callback.transaction.trans_id|default:"N/A" }}</li>
                                                                <li><strong>Amount:</strong> KES {{ callback.transaction.amount|floatformat:2|intcomma }}</li>
                                                                <li><strong>Status:</strong> {{ callback.transaction.get_status_display }}</li>
                                                                <li><strong>Bill Ref (ID):</strong> {{ callback.transaction.bill_ref_number|default:"N/A" }}</li>
                                                                <li><strong>Phone:</strong> {{ callback.transaction.msisdn|default:callback.transaction.phone_number|default:"N/A" }}</li>
                                                            </ul>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <h6>Borrower Information</h6>
                                                            {% if callback.transaction.borrower %}
                                                                <ul class="list-unstyled">
                                                                    <li><strong>Name:</strong> {{ callback.transaction.borrower.get_full_name }}</li>
                                                                    <li><strong>Email:</strong> {{ callback.transaction.borrower.email }}</li>
                                                                    <li><strong>ID Number:</strong> {{ callback.transaction.borrower.id_number|default:"N/A" }}</li>
                                                                    <li><strong>Phone:</strong> {{ callback.transaction.borrower.phone_number|default:"N/A" }}</li>
                                                                    <li>
                                                                        <a href="{% url 'users:client_detail' callback.transaction.borrower.id %}" 
                                                                           class="btn btn-sm btn-primary">
                                                                            <span>👤</span> View Client
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            {% else %}
                                                                <p class="text-warning">
                                                                    <span>⚠️</span> Borrower not matched
                                                                </p>
                                                                {% if callback.transaction.processing_notes %}
                                                                    <p class="text-muted"><small>{{ callback.transaction.processing_notes }}</small></p>
                                                                {% endif %}
                                                                <button type="button" 
                                                                        class="btn btn-sm btn-primary" 
                                                                        data-bs-dismiss="modal"
                                                                        data-bs-toggle="modal" 
                                                                        data-bs-target="#matchModal{{ callback.transaction.id }}">
                                                                    <span>💰</span> Match to Loan
                                                                </button>
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                    
                                                    {% if callback.transaction.repayment %}
                                                        <div class="alert alert-success">
                                                            <h6><span>✓</span> Repayment Created</h6>
                                                            <ul class="list-unstyled mb-0">
                                                                <li><strong>Receipt Number:</strong> 
                                                                    <span class="badge badge-success">{{ callback.transaction.repayment.receipt_number }}</span>
                                                                </li>
                                                                <li><strong>Loan:</strong> 
                                                                    <a href="{% url 'loans:loan_detail' callback.transaction.repayment.loan.id %}">
                                                                        {{ callback.transaction.repayment.loan.loan_number }}
                                                                    </a>
                                                                </li>
                                                                <li><strong>Payment Date:</strong> {{ callback.transaction.repayment.payment_date|date:"Y-m-d H:i:s" }}</li>
                                                                <li><strong>Payment Method:</strong> {{ callback.transaction.repayment.get_payment_method_display }}</li>
                                                                <li><strong>Payment Source:</strong> {{ callback.transaction.repayment.get_payment_source_display }}</li>
                                                                <li>
                                                                    <a href="{% url 'loans:repayments' %}" class="btn btn-sm btn-primary">
                                                                        <span>📋</span> View All Repayments
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    {% else %}
                                                        <div class="alert alert-danger">
                                                            <h6><span>✕</span> No Repayment Created</h6>
                                                            {% if callback.transaction.processing_notes %}
                                                                <p><strong>Reason:</strong> {{ callback.transaction.processing_notes }}</p>
                                                            {% endif %}
                                                            <p class="mb-2">
                                                                <small class="text-muted">
                                                                    <span>ℹ️</span> 
                                                                    If the ID number was added after this payment was made, click Retry to match it now.
                                                                </small>
                                                            </p>
                                                            <a href="{% url 'payments:reprocess_transaction' callback.transaction.id %}?redirect_to=payments:callbacks" 
                                                               class="btn btn-sm btn-warning">
                                                                <span>↷</span> Retry Matching
                                                            </a>
                                                        </div>
                                                    {% endif %}
                                                    
                                                    <hr>
                                                {% endif %}
                                                
                                                <h6>Raw Callback Data:</h6>
                                                <pre class="bg-light p-3" style="max-height: 300px; overflow-y: auto;">{{ callback.raw_data|pprint }}</pre>
                                                
                                                {% if callback.response_sent %}
                                                    <h6 class="mt-3">Response Sent to M-Pesa:</h6>
                                                    <pre class="bg-light p-3">{{ callback.response_sent|pprint }}</pre>
                                                {% endif %}

                                                <h6 class="mt-3">Callback Metadata:</h6>
                                                <ul>
                                                    <li><strong>Time:</strong> {{ callback.created_at|date:"Y-m-d H:i:s" }}</li>
                                                    <li><strong>IP Address:</strong> {{ callback.ip_address|default:"N/A" }}</li>
                                                    <li><strong>User Agent:</strong> {{ callback.user_agent|default:"N/A"|truncatechars:50 }}</li>
                                                    <li><strong>Processed:</strong> {{ callback.processed|yesno:"Yes,No" }}</li>
                                                </ul>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Modal for manual matching -->
                                {% if callback.transaction and not callback.transaction.borrower %}
                                <div class="modal fade" id="matchModal{{ callback.transaction.id }}" tabindex="-1" role="dialog">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header bg-primary text-white">
                                                <h5 class="modal-title">
                                                    <span>💰</span> Manually Match Payment to Loan
                                                </h5>
                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">
                                            </div>
                                            <form method="post" action="{% url 'payments:manual_match_payment' callback.transaction.id %}">
                                                {% csrf_token %}
                                                <div class="modal-body">
                                                    <div class="alert alert-info">
                                                        <strong>Payment Details:</strong><br>
                                                        <span>💰</span> Amount: <strong>KES {{ callback.transaction.amount|floatformat:2|intcomma }}</strong><br>
                                                        <span>📱</span> Phone: {{ callback.transaction.msisdn|default:callback.transaction.phone_number|default:"N/A" }}<br>
                                                        <span>🆔</span> Bill Ref: {{ callback.transaction.bill_ref_number|default:"N/A" }}<br>
                                                        <span>🕐</span> Time: {{ callback.transaction.created_at|date:"Y-m-d H:i:s" }}
                                                    </div>
                                                    
                                                    <div class="form-group">
                                                        <label for="loan_select_{{ callback.transaction.id }}">
                                                            <strong>Select Loan:</strong>
                                                        </label>
                                                        <select name="loan_id" 
                                                                id="loan_select_{{ callback.transaction.id }}" 
                                                                class="form-control" 
                                                                required>
                                                            <option value="">-- Select a loan --</option>
                                                            {% for loan in active_loans %}
                                                                <option value="{{ loan.id }}" 
                                                                        data-borrower="{{ loan.borrower.get_full_name }}"
                                                                        data-outstanding="{{ loan.outstanding_amount }}">
                                                                    {{ loan.loan_number }} - {{ loan.borrower.get_full_name }}
                                                                    {% if loan.borrower.id_number %}(ID: {{ loan.borrower.id_number }}){% endif %}
                                                                    - Outstanding: KES {{ loan.outstanding_amount|floatformat:2|intcomma }}
                                                                    - Due: {{ loan.due_date|date:"Y-m-d" }}
                                                                </option>
                                                            {% endfor %}
                                                        </select>
                                                        <small class="form-text text-muted">
                                                            Search by loan number, borrower name, or ID number
                                                        </small>
                                                    </div>
                                                    
                                                    <div class="alert alert-warning">
                                                        <span>⚠️</span> <strong>Important:</strong> This will:
                                                        <ul class="mb-0">
                                                            <li>Link this payment to the selected loan</li>
                                                            <li>Attempt to process the payment automatically</li>
                                                            <li>Create a repayment if the borrower has an active loan</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                        Cancel
                                                    </button>
                                                    <button type="submit" class="btn btn-primary">
                                                        <span>✓</span> Match & Process Payment
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                {% if page_obj.has_other_pages %}
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            {% if page_obj.has_previous %}
                                <li class="page-item">
                                    <a class="page-link" href="?page=1{% if filters.type %}&type={{ filters.type }}{% endif %}{% if filters.processed %}&processed={{ filters.processed }}{% endif %}">First</a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if filters.type %}&type={{ filters.type }}{% endif %}{% if filters.processed %}&processed={{ filters.processed }}{% endif %}">Previous</a>
                                </li>
                            {% endif %}

                            <li class="page-item active">
                                <span class="page-link">
                                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
                                </span>
                            </li>

                            {% if page_obj.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if filters.type %}&type={{ filters.type }}{% endif %}{% if filters.processed %}&processed={{ filters.processed }}{% endif %}">Next</a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if filters.type %}&type={{ filters.type }}{% endif %}{% if filters.processed %}&processed={{ filters.processed }}{% endif %}">Last</a>
                                </li>
                            {% endif %}
                        </ul>
                    </nav>
                {% endif %}
            {% else %}
                <div class="alert alert-info">
                    <span>ℹ️</span> No callback logs found.
                </div>
            {% endif %}
        </div>
    </div>
</div>

<style>
/* Make the select dropdown more user-friendly */
select[id^="loan_select_"] {
    height: auto;
    max-height: 300px;
}
</style>

<script>
// Add search functionality to loan select dropdowns
document.addEventListener('DOMContentLoaded', function() {
    // Make select dropdowns searchable by adding a filter input
    const selectElements = document.querySelectorAll('select[id^="loan_select_"]');
    
    selectElements.forEach(function(select) {
        // Store original options
        const originalOptions = Array.from(select.options);
        
        // Create search input
        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'form-control mb-2';
        searchInput.placeholder = 'Type to search loans...';
        
        // Insert search input before select
        select.parentNode.insertBefore(searchInput, select);
        
        // Filter options on input
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            
            // Clear current options
            select.innerHTML = '<option value="">-- Select a loan --</option>';
            
            // Filter and add matching options
            originalOptions.slice(1).forEach(function(option) {
                const text = option.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    select.appendChild(option.cloneNode(true));
                }
            });
        });
    });
});
</script>
{% endblock %}
