{% extends 'base.html' %}

{% block content %}
  <h2>Online Payment Management</h2>
  
  <div class="card">
    <h3>Payment Submissions</h3>
    
    <!-- Info Alert for Legacy Records -->
    <div style="background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 8px; padding: 16px; margin-bottom: 20px;">
      <div style="display: flex; align-items: center; gap: 12px;">
        <div style="font-size: 24px;">💡</div>
        <div>
          <p style="margin: 0 0 8px 0; font-weight: 600; color: #0369a1;">Payment Proof System Update</p>
          <p style="margin: 0; color: #0369a1; font-size: 14px;">
            Some older payment records may show "File Not Available" because they were created before proper file storage was implemented. 
            New uploads will work correctly. You can still approve/reject payments based on the reference ID and other details.
          </p>
        </div>
      </div>
    </div>
    
    <!-- Live Search -->
    <div class="card" style="margin-bottom: 16px;">
      <input type="text" id="payment-search" placeholder="🔍 Search payments by date, customer, payment method, amount, reference ID, status..." 
             style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">
    </div>
    
    {% if payments %}
      <table class="table" id="payments-table">
        <thead>
          <tr>
            <th>Date</th>
            <th>Customer</th>
            <th>Payment Method</th>
            <th>Amount</th>
            <th>Reference ID</th>
            <th>Screenshot</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {% for payment in payments %}
            <tr>
              <td>{{ payment.date|date_format }}</td>
              <td>
                <strong>{{ payment.customer.name }}</strong><br>
                <small style="color: #666;">{{ payment.customer.email }}</small>
              </td>
              <td>
                <strong>{{ payment.account.name }}</strong><br>
                <small style="color: #666;">{{ payment.account.bank_name or 'N/A' }}</small>
              </td>
              <td>{{ payment.amount|currency }}</td>
              <td><code>{{ payment.reference_id }}</code></td>
              <td>
                {% if payment.screenshot_path %}
                  {% if payment.screenshot_path.startswith('uploaded_') %}
                    <button onclick="viewScreenshot('{{ payment.screenshot_path }}', '{{ payment.reference_id }}')" class="btn-outline" style="font-size: 11px; padding: 4px 8px; background: #f0f9ff; border-color: #0ea5e9; color: #0369a1;">
                      📷 View
                    </button>
                  {% else %}
                    <button onclick="viewScreenshot('{{ payment.screenshot_path }}', '{{ payment.reference_id }}')" class="btn-outline" style="font-size: 11px; padding: 4px 8px; background: #fef3c7; border-color: #f59e0b; color: #92400e;">
                      🔗 Link
                    </button>
                  {% endif %}
                {% else %}
                  <span style="color: #9ca3af; font-size: 12px;">No proof</span>
                {% endif %}
              </td>
              <td>
                {% if payment.status == 'pending' %}
                  <span style="color: #f59e0b;">⏳ Pending</span>
                {% elif payment.status == 'approved' %}
                  <span style="color: #059669;">✅ Approved</span>
                {% elif payment.status == 'rejected' %}
                  <span style="color: #dc2626;">❌ Rejected</span>
                {% endif %}
              </td>
              <td>
                {% if payment.status == 'pending' %}
                  <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    <button onclick="showApproveModal({{ payment.id }})" class="btn-primary" style="font-size: 12px;">Approve</button>
                    <button onclick="showRejectModal({{ payment.id }})" class="btn-outline" style="font-size: 12px; color: #dc2626;">Reject</button>
                  </div>
                {% else %}
                  <span class="muted">-</span>
                {% endif %}
              </td>
            </tr>
            <!-- Payment Details Row -->
            <tr style="background-color: #f9fafb;">
              <td colspan="8">
                <div style="padding: 12px;">
                  <strong>Payment Details:</strong><br>
                  {% if payment.note %}
                    <div style="margin: 8px 0;">
                      <strong>Customer Notes:</strong> {{ payment.note }}
                    </div>
                  {% endif %}
                  {% if payment.admin_notes %}
                    <div style="margin: 8px 0;">
                      <strong>Admin Notes:</strong> {{ payment.admin_notes }}
                    </div>
                  {% endif %}
                  <div style="margin: 8px 0; font-size: 12px; color: #666;">
                    Submitted: {{ payment.created_at|date_format }} at {{ payment.created_at.strftime('%H:%M') }}
                  </div>
                </div>
              </td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    {% else %}
      <p style="color: #666; text-align: center; padding: 20px;">No online payment submissions yet.</p>
    {% endif %}
  </div>

  <!-- Approve Modal -->
  <div id="approveModal" class="modal" style="display: none;">
    <div class="modal-content">
      <h3>Approve Payment</h3>
      <form id="approveForm" method="post">
        <div class="field">
          <label class="label">Admin Notes (Optional)</label>
          <textarea name="notes" rows="3" placeholder="Any notes about this approval"></textarea>
        </div>
        <div style="margin-top: 20px; display: flex; gap: 12px;">
          <button type="submit" class="btn-primary">Confirm Approval</button>
          <button type="button" onclick="hideModal('approveModal')" class="btn-outline">Cancel</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Reject Modal -->
  <div id="rejectModal" class="modal" style="display: none;">
    <div class="modal-content">
      <h3>Reject Payment</h3>
      <form id="rejectForm" method="post">
        <div class="field">
          <label class="label">Reason for Rejection</label>
          <textarea name="notes" rows="3" placeholder="Please provide a reason for rejection" required></textarea>
        </div>
        <div style="margin-top: 20px; display: flex; gap: 12px;">
          <button type="submit" class="btn-outline" style="color: #dc2626;">Confirm Rejection</button>
          <button type="button" onclick="hideModal('rejectModal')" class="btn-outline">Cancel</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Screenshot Viewer Modal -->
  <div id="screenshotModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 800px; max-height: 90vh; overflow-y: auto;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>Screenshot Proof</h3>
        <button onclick="hideModal('screenshotModal')" class="btn-outline" style="padding: 8px 12px;">✕</button>
      </div>
      <div id="screenshotContent">
        <!-- Screenshot content will be loaded here -->
      </div>
    </div>
  </div>

  <style>
    .modal {
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
    }
    .modal-content {
      background-color: white;
      margin: 15% auto;
      padding: 20px;
      border-radius: 8px;
      width: 80%;
      max-width: 500px;
    }
    .field textarea {
      width: 100%;
      padding: 8px;
      border: 1px solid #d1d5db;
      border-radius: 4px;
      font-family: inherit;
    }
  </style>

  <script>
    let currentPaymentId = null;

    function showApproveModal(paymentId) {
      currentPaymentId = paymentId;
      document.getElementById('approveForm').action = `/admin/online-payment/${paymentId}/approve`;
      document.getElementById('approveModal').style.display = 'block';
    }

    function showRejectModal(paymentId) {
      currentPaymentId = paymentId;
      document.getElementById('rejectForm').action = `/admin/online-payment/${paymentId}/reject`;
      document.getElementById('rejectModal').style.display = 'block';
    }

    function hideModal(modalId) {
      document.getElementById(modalId).style.display = 'none';
    }

    function viewScreenshot(screenshotPath, referenceId) {
      const modal = document.getElementById('screenshotModal');
      const content = document.getElementById('screenshotContent');
      
      // Show loading
      content.innerHTML = '<p>Loading screenshot...</p>';
      modal.style.display = 'block';
      
      // Check if it's a file upload or a link
      if (screenshotPath.startsWith('uploaded_')) {
        // It's a file upload - check if file exists first
        fetch(`/uploads/${screenshotPath}`)
          .then(response => {
            if (response.ok) {
              // File exists - show the image
              content.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                  <h4>Payment Proof - ${referenceId}</h4>
                  <div style="margin: 20px 0;">
                    <img src="/uploads/${screenshotPath}" alt="Payment Proof" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                  </div>
                  <div style="text-align: left; background: #f9fafb; padding: 16px; border-radius: 8px; margin-top: 20px;">
                    <p><strong>Reference ID:</strong> ${referenceId}</p>
                    <p><strong>File Type:</strong> Screenshot/Proof Image</p>
                    <p><strong>Upload Status:</strong> File received successfully</p>
                    <p><strong>File:</strong> ${screenshotPath}</p>
                  </div>
                </div>
              `;
            } else {
              // File doesn't exist - show error
              showFileError(screenshotPath, referenceId);
            }
          })
          .catch(error => {
            console.error('Error checking file:', error);
            showFileError(screenshotPath, referenceId);
          });
      } else {
        // It's a link - try to display the image
        content.innerHTML = `
          <div style="text-align: center; padding: 20px;">
            <h4>Payment Proof - ${referenceId}</h4>
            <div style="margin: 20px 0;">
              <img src="${screenshotPath}" alt="Payment Proof" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" onerror="this.style.display='none'; document.getElementById('linkError').style.display='block';">
              <div id="linkError" style="display: none; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; padding: 20px; color: #dc2626;">
                <p><strong>⚠️ Image could not be loaded</strong></p>
                <p>The screenshot link appears to be invalid or inaccessible.</p>
                <p><strong>Link:</strong> <a href="${screenshotPath}" target="_blank" style="color: #dc2626;">${screenshotPath}</a></p>
              </div>
            </div>
            <div style="text-align: left; background: #f9fafb; padding: 16px; border-radius: 8px; margin-top: 20px;">
              <p><strong>Reference ID:</strong> ${referenceId}</p>
              <p><strong>Source:</strong> External Link</p>
              <p><strong>Link:</strong> <a href="${screenshotPath}" target="_blank" style="color: #2563eb;">${screenshotPath}</a></p>
            </div>
          </div>
        `;
      }
    }

    function showFileError(filename, referenceId) {
      const content = document.getElementById('screenshotContent');
      content.innerHTML = `
        <div style="text-align: center; padding: 20px;">
          <h4>Payment Proof - ${referenceId}</h4>
          <div style="background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; padding: 20px; color: #dc2626; margin: 20px 0;">
            <div style="font-size: 48px; color: #fca5a5; margin-bottom: 16px;">📷</div>
            <p><strong>⚠️ File Not Available</strong></p>
            <p>This payment proof was submitted before proper file storage was implemented.</p>
            <p><strong>File:</strong> ${filename}</p>
          </div>
          <div style="text-align: left; background: #f9fafb; padding: 16px; border-radius: 8px; margin-top: 20px;">
            <p><strong>Reference ID:</strong> ${referenceId}</p>
            <p><strong>File Type:</strong> Screenshot/Proof Image</p>
            <p><strong>Upload Status:</strong> File not available (legacy record)</p>
            <p><strong>File:</strong> ${filename}</p>
            <div style="margin-top: 16px; padding: 12px; background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 6px;">
              <p style="margin: 0; color: #0369a1; font-size: 14px;"><strong>💡 Note:</strong> This is a legacy payment record. New uploads will work properly with the current system.</p>
            </div>
          </div>
        </div>
      `;
    }

    // Close modal when clicking outside
    window.onclick = function(event) {
      if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
      }
    }
    
    // Initialize live search
    document.addEventListener('DOMContentLoaded', function() {
      initLiveSearch('payment-search', 'payments-table');
    });
  </script>
{% endblock %}
