// payment.component.ts - Fixed version
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-payment',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './payment.component.html',
  styleUrls: ['./payment.component.scss']
})
export class PaymentComponent implements OnInit {
  payUParams: any = {
    key: 'VqvG3m',
    txnid: this.generateTxnId(),
    amount: '0.00',
    productinfo: '',
    firstname: '',
    email: '',
    phone: '',
    // Use PayU's test success/failure URLs for now
    surl: 'https://apiplayground-response.herokuapp.com/',  // Test success URL
    furl: 'https://apiplayground-response.herokuapp.com/',  // Test failure URL
    hash: ''
  };

  constructor(private http: HttpClient) {}

  ngOnInit(): void {}

  generateTxnId(): string {
    return 'txn_' + Math.random().toString(36).substr(2, 9);
  }

  submitPayUForm() {
    // Validate inputs
    if (!this.payUParams.firstname || !this.payUParams.email || !this.payUParams.phone || !this.payUParams.amount) {
      alert('Please fill all required fields.');
      return;
    }

    // Send to backend to generate hash
    this.http
      .post(`${environment.apiUrl}/create-payu-order`, this.payUParams)
      .subscribe(
        (response: any) => {
          console.log('PayU response:', response);
          
          // Update payUParams with response data
          this.payUParams = {
            ...this.payUParams,
            ...response
          };
          
          // Auto-submit form
          setTimeout(() => {
            this.submitFormToPayU();
          }, 100);
        },
        (error) => {
          console.error('Error generating hash:', error);
          alert('Failed to initiate payment. Please try again.');
        }
      );
  }

  private submitFormToPayU() {
    // Create form dynamically
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'https://test.payu.in/_payment';
    
    // Add all PayU parameters as hidden inputs
    Object.keys(this.payUParams).forEach(key => {
      if (this.payUParams[key]) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = this.payUParams[key];
        form.appendChild(input);
      }
    });

    // Submit form
    document.body.appendChild(form);
    form.submit();
  }
}