/**
 * Payment Module - M-Pesa Integration
 * Handles M-Pesa payment and WhatsApp order automation
 */

class PaymentHandler {
  constructor() {
    this.isProcessing = false;
    this.MPESA_BUSINESS_NUMBER = '0712072925';
  }

  /**
   * Process checkout with M-Pesa
   * @param {Object} checkoutData - Checkout form data
   * @param {Array} cartItems - Items in cart
   */
  async processCheckout(checkoutData, cartItems) {
    // Validate cart
    const validation = cart.validate();
    if (!validation.isValid) {
      showNotification(validation.errors[0], 'error');
      return;
    }

    // Validate all required fields
    if (!checkoutData.fullName || !checkoutData.email || !checkoutData.phone || !checkoutData.deliveryLocation || !checkoutData.mpesaCode) {
      showNotification('Please fill in all required fields including M-Pesa details (full name & time sent)', 'error');
      return;
    }

    // Validate phone number format
    if (!checkoutData.phone.match(/^\+?254[0-9]{9}$|^0[0-9]{9}$/)) {
      showNotification('Please enter a valid phone number (e.g., +254712345678 or 0712345678)', 'error');
      return;
    }

    // Validate M-Pesa details are not empty
    if (checkoutData.mpesaCode.trim().length === 0) {
      showNotification('Please enter your M-Pesa details (full name & time sent)', 'error');
      return;
    }

    this.isProcessing = true;

    try {
      const cartTotal = cart.getTotal();
      
      // Capture cart items BEFORE clearing
      const cartItems = cart.getItems();

      // Prepare WhatsApp order data with M-Pesa reference
      const orderData = {
        name: checkoutData.fullName,
        email: checkoutData.email,
        phone: checkoutData.phone,
        deliveryLocation: checkoutData.deliveryLocation,
        deliveryAddress: checkoutData.address || 'Not provided',
        cartItems: cartItems,
        total: cartTotal,
        mpesaCode: checkoutData.mpesaCode,
        timestamp: new Date().toLocaleString(),
      };

      // Generate WhatsApp message with M-Pesa code
      const message = formatWhatsAppOrderMessage(
        orderData.cartItems,
        orderData.total,
        {
          name: orderData.name,
          email: orderData.email,
          phone: orderData.phone,
          deliveryLocation: orderData.deliveryLocation,
        },
        orderData.mpesaCode
      );

      // Send to WhatsApp
      const encodedMessage = encodeURIComponent(message);
      const whatsappUrl = `https://wa.me/${CONFIG.whatsappNumber.replace('+', '')}?text=${encodedMessage}`;

      // Open WhatsApp
      window.open(whatsappUrl, '_blank');

      // Clear cart, form fields, and close checkout modal
      cart.clear();
      updateCartUI();
      
      // Clear all form fields including M-Pesa code - ensure it's NEVER saved
      const formFields = ['fullName', 'email', 'phone', 'deliveryLocation', 'address', 'mpesaCode'];
      formFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) field.value = '';
      });
      const saveCheckbox = document.getElementById('save-address');
      if (saveCheckbox) saveCheckbox.checked = false;
      
      closeCartModal();

      // Show order confirmation
      this.showOrderConfirmation(orderData);

      // Redirect to homepage (index.html) after a short delay
      setTimeout(() => {
        window.location.href = 'index.html';
      }, 2000);

    } catch (error) {
      console.error('Checkout error:', error);
      showNotification('An error occurred. Please try again.', 'error');
    } finally {
      this.isProcessing = false;
    }
  }

  /**
   * Show order confirmation modal
   * @param {Object} orderInfo - Order information
   */
  showOrderConfirmation(orderInfo) {
    const modal = document.getElementById('order-confirmation-modal');
    if (!modal) return;

    // Build items list
    let itemsHTML = '<div style="margin-bottom: 15px;">';
    orderInfo.cartItems.forEach(item => {
      itemsHTML += `
        <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--border-color); font-size: 0.9rem;">
          <span>${item.name} x${item.quantity}</span>
          <span style="color: var(--accent-gold);">KES ${(item.price * item.quantity).toLocaleString()}</span>
        </div>
      `;
    });
    itemsHTML += '</div>';

    // Update modal content
    const content = modal.querySelector('.modal-body');
    if (content) {
      content.innerHTML = `
        <div class="confirmation-success" style="text-align: center; padding: 20px;">
          <div style="font-size: 3rem; color: #4caf50; margin-bottom: 15px;">✓</div>
          <h3 style="color: var(--accent-gold); margin-bottom: 10px;">Order Confirmed!</h3>
          <p style="color: var(--text-light); margin-bottom: 20px;">
            Thank you ${orderInfo.name}, your order has been placed!
          </p>
          
          <div style="background-color: var(--secondary-dark); padding: 15px; border-radius: 5px; margin-bottom: 20px; text-align: left;">
            <h4 style="color: var(--accent-gold); margin-top: 0;">Order Summary</h4>
            ${itemsHTML}
            <div style="padding-top: 10px; border-top: 2px solid var(--border-color); font-weight: bold;">
              <div style="display: flex; justify-content: space-between; color: var(--accent-gold); font-size: 1.1rem;">
                <span>Total:</span>
                <span>KES ${orderInfo.total.toLocaleString()}</span>
              </div>
            </div>
            <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid var(--border-color);">
              <p style="margin: 5px 0; color: var(--text-light);"><strong>Payment Method:</strong> M-Pesa</p>
              <p style="margin: 5px 0; color: var(--text-light);"><strong>Payment Name & Time:</strong> <span style="color: #4caf50; font-weight: bold;">${orderInfo.mpesaCode}</span></p>
              <p style="margin: 5px 0; color: var(--text-light);"><strong>Delivery Location:</strong> ${orderInfo.deliveryLocation}</p>
              <p style="margin: 5px 0; color: var(--text-muted); font-size: 0.85rem;"><strong>Timestamp:</strong> ${orderInfo.timestamp}</p>
            </div>
          </div>

          <div style="background-color: rgba(76, 175, 80, 0.1); padding: 12px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid #4caf50;">
            <p style="color: #4caf50; margin: 0; font-weight: bold;">✓ Cart Cleared</p>
            <p style="color: #4caf50; margin: 5px 0;">✓ Order Sent to WhatsApp</p>
            <p style="color: #4caf50; margin: 5px 0;">✓ Payment details received (name & time)</p>
          </div>

          <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 20px;">
            🔄 Redirecting to homepage in 5 seconds...
          </p>
          <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 20px;">
            Our team will contact you via WhatsApp at <strong>${orderInfo.phone}</strong> to confirm delivery details.
          </p>
          <button onclick="location.href='index.html';" style="
            padding: 10px 20px;
            background-color: var(--accent-gold);
            color: var(--primary-dark);
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
          ">Continue Shopping</button>
        </div>
      `;
    }

    // Show modal
    modal.classList.add('active');
  }
}

/**
 * Create global payment handler instance
 */
const paymentHandler = new PaymentHandler();

/**
 * Helper function to open checkout
 */
function openCheckout() {
  if (cart.isEmpty()) {
    showNotification('Your cart is empty', 'error');
    return;
  }

  // Update total amounts in checkout form
  const cartTotal = cart.getTotal();
  const totalElement = document.getElementById('total-amount');
  const mpesaAmountElement = document.getElementById('mpesa-amount');
  
  if (totalElement) totalElement.textContent = cartTotal.toLocaleString();
  if (mpesaAmountElement) mpesaAmountElement.textContent = cartTotal.toLocaleString();

  const checkoutModal = document.getElementById('checkout-modal');
  if (checkoutModal) {
    checkoutModal.classList.add('active');
  }
}

/**
 * Helper function to close modal
 * @param {string} modalId - Modal element ID
 */
function closeModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.classList.remove('active');
  }
}

/**
 * Helper function to close checkout modal
 */
function closeCheckoutModal() {
  closeModal('checkout-modal');
}

/**
 * Helper function to close cart modal
 */
function closeCartModal() {
  closeModal('cart-modal');
}

/**
 * Handle checkout form submission
 */
function handleCheckoutSubmit(event) {
  event.preventDefault();

  const fullName = document.getElementById('fullName')?.value.trim();
  const email = document.getElementById('email')?.value.trim();
  const phone = document.getElementById('phone')?.value.trim();
  const deliveryLocation = document.getElementById('deliveryLocation')?.value.trim();
  const address = document.getElementById('address')?.value.trim();
  const mpesaCode = document.getElementById('mpesaCode')?.value.trim();

  if (!fullName || !email || !phone || !deliveryLocation) {
    showNotification('Please fill in all required fields', 'error');
    return;
  }

  if (!mpesaCode) {
    showNotification('Please enter your M-Pesa confirmation code', 'error');
    return;
  }

  if (!phone.match(/^\+?254[0-9]{9}$|^0[0-9]{9}$/)) {
    showNotification('Please enter a valid phone number (e.g., +254712345678 or 0712345678)', 'error');
    return;
  }

  const checkoutData = {
    fullName,
    email,
    phone,
    deliveryLocation,
    address,
    mpesaCode,
  };

  paymentHandler.processCheckout(checkoutData, cart.getItems());
}

/**
 * Initialize payment handlers
 */
function initPaymentHandlers() {
  const checkoutForm = document.getElementById('checkout-form');
  if (checkoutForm) {
    checkoutForm.addEventListener('submit', handleCheckoutSubmit);
  }

  window.paymentHandler = paymentHandler;
}

// Auto-initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  initPaymentHandlers();
});
