{% extends 'base.html' %}

{% block content %}
  <h2>Online Payment</h2>
  
  <!-- Current Balance -->
  <div class="card" style="margin-bottom: 16px;">
    <h3>Your Account Status</h3>
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <div>
        <p style="margin: 8px 0; color: #666;">
          Current balance in your account
        </p>
      </div>
      <div style="font-size: 1.2em; font-weight: bold; color: {% if balance > 0 %}#dc2626{% else %}#059669{% endif %};">
        {{ balance|currency }}
      </div>
    </div>
    {% if balance > 0 %}
      <div style="margin-top: 12px;">
        <a href="{{ url_for('online_payment_submit') }}" class="btn-primary">Submit Payment Proof</a>
      </div>
    {% endif %}
  </div>

  <!-- Available Payment Methods -->
  <div class="card" style="margin-bottom: 16px;">
    <h3>Available Payment Methods</h3>
    {% if payment_accounts %}
      <div class="grid cols-2" style="gap: 16px;">
        {% for account in payment_accounts %}
          <div class="card" style="border: 1px solid #e5e7eb; padding: 16px;">
            <h4 style="margin: 0 0 8px 0; color: #059669;">{{ account.name }}</h4>
            {% if account.bank_name %}
              <p style="margin: 4px 0; color: #666;"><strong>Bank:</strong> {{ account.bank_name }}</p>
            {% endif %}
            {% if account.holder_name %}
              <p style="margin: 4px 0; color: #666;"><strong>Account Holder:</strong> {{ account.holder_name }}</p>
            {% endif %}
            {% if account.account_number %}
              <p style="margin: 4px 0; color: #666;"><strong>Account Number:</strong> {{ account.account_number }}</p>
            {% endif %}
            {% if account.ifsc_swift %}
              <p style="margin: 4px 0; color: #666;"><strong>IFSC/SWIFT:</strong> {{ account.ifsc_swift }}</p>
            {% endif %}
            {% if account.payment_instructions %}
              <div style="margin-top: 12px; padding: 12px; background-color: #f9fafb; border-radius: 6px;">
                <strong>Payment Instructions:</strong>
                <p style="margin: 8px 0 0 0; color: #374151;">{{ account.payment_instructions }}</p>
              </div>
            {% endif %}
          </div>
        {% endfor %}
      </div>
    {% else %}
      <p style="color: #666; text-align: center; padding: 20px;">No online payment methods available at the moment.</p>
    {% endif %}
  </div>

  <!-- Payment History -->
  <div class="card">
    <h3>Your Payment History</h3>
    {% if all_payments %}
      <!-- Status Summary -->
      <div style="display: flex; gap: 16px; margin-bottom: 20px; flex-wrap: wrap;">
        {% set pending_count = all_payments|selectattr('status', 'equalto', 'pending')|list|length %}
        {% set approved_count = all_payments|selectattr('status', 'equalto', 'approved')|list|length %}
        {% set rejected_count = all_payments|selectattr('status', 'equalto', 'rejected')|list|length %}
        
        <div style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 8px; padding: 12px; min-width: 120px; text-align: center;">
          <div style="font-size: 24px; color: #f59e0b;">⏳</div>
          <div style="font-weight: 600; color: #92400e;">{{ pending_count }}</div>
          <div style="font-size: 12px; color: #92400e;">Pending</div>
        </div>
        
        <div style="background: #d1fae5; border: 1px solid #059669; border-radius: 8px; padding: 12px; min-width: 120px; text-align: center;">
          <div style="font-size: 24px; color: #059669;">✅</div>
          <div style="font-weight: 600; color: #065f46;">{{ approved_count }}</div>
          <div style="font-size: 12px; color: #065f46;">Approved</div>
        </div>
        
        <div style="background: #fee2e2; border: 1px solid #dc2626; border-radius: 8px; padding: 12px; min-width: 120px; text-align: center;">
          <div style="font-size: 24px; color: #dc2626;">❌</div>
          <div style="font-weight: 600; color: #991b1b;">{{ rejected_count }}</div>
          <div style="font-size: 12px; color: #991b1b;">Rejected</div>
        </div>
      </div>

      <!-- Transactions Table -->
      <table class="table">
        <thead>
          <tr>
            <th>Date & Time</th>
            <th>Payment Method</th>
            <th>Amount</th>
            <th>Reference ID</th>
            <th>Status</th>
            <th>Admin Notes</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {% for payment in all_payments %}
            <tr style="background-color: {% if payment.status == 'approved' %}#f0fdf4{% elif payment.status == 'rejected' %}#fef2f2{% else %}#fffbeb{% endif %};">
              <td>
                <div style="font-weight: 600;">{{ payment.date|date_format }}</div>
                <small style="color: #666;">{{ payment.created_at.strftime('%H:%M') }}</small>
              </td>
              <td>
                <strong>{{ payment.account.name }}</strong>
                {% if payment.account.bank_name %}
                  <br><small style="color: #666;">{{ payment.account.bank_name }}</small>
                {% endif %}
              </td>
              <td>
                <span style="font-weight: 600; font-size: 1.1em;">{{ payment.amount|currency }}</span>
              </td>
              <td>
                <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 12px;">{{ payment.reference_id }}</code>
              </td>
              <td>
                {% if payment.status == 'pending' %}
                  <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">⏳ Pending</span>
                {% elif payment.status == 'approved' %}
                  <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">✅ Approved</span>
                {% elif payment.status == 'rejected' %}
                  <span style="background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;">❌ Rejected</span>
                {% endif %}
              </td>
              <td>
                {% if payment.admin_notes %}
                  <div style="max-width: 200px;">
                    <small style="color: #666; line-height: 1.4;">{{ payment.admin_notes }}</small>
                  </div>
                {% else %}
                  <span style="color: #9ca3af; font-size: 12px;">-</span>
                {% endif %}
              </td>
              <td>
                {% if payment.screenshot_path %}
                  <button onclick="viewScreenshot('{{ payment.screenshot_path }}', '{{ payment.reference_id }}')" class="btn-outline" style="font-size: 11px; padding: 4px 8px;">
                    📷 View
                  </button>
                {% else %}
                  <span style="color: #9ca3af; font-size: 12px;">No proof</span>
                {% endif %}
              </td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    {% else %}
      <div style="text-align: center; padding: 40px 20px;">
        <div style="font-size: 48px; color: #d1d5db; margin-bottom: 16px;">📊</div>
        <p style="color: #666; margin: 0 0 8px 0; font-size: 16px;">No payment submissions yet</p>
        <p style="color: #9ca3af; margin: 0; font-size: 14px;">Your payment history will appear here once you submit payment proofs</p>
      </div>
    {% endif %}
  </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;
    }
  </style>

  <script>
    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';
      }
    }
  </script>
{% endblock %}
