// payment-success.component.ts - Updated version
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';

interface TransactionDetails {
  transactionId: string;
  paymentId: string;
  status: string;
  amount: string;
  customerName: string;
  customerEmail: string;
  customerPhone: string;
  products: string;
  paymentMode: string;
  transactionDate: string;
  bankRefNumber: string;
}

@Component({
  selector: 'app-payment-success',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './payment-success.component.html',
  styleUrls: ['./payment-success.component.scss']
})
export class PaymentSuccessComponent implements OnInit {
  transactionDetails: TransactionDetails | null = null;
  loading = true;
  error = '';
  dispensing = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private http: HttpClient
  ) {}

  ngOnInit() {
    // Get all query parameters from PayU response
    this.route.queryParams.subscribe(params => {
      console.log('PayU Response Parameters:', params);
      this.processPaymentResponse(params);
    });
  }

  processPaymentResponse(params: any) {
    if (!params.txnid || !params.status) {
      this.error = 'Invalid payment response received';
      this.loading = false;
      return;
    }

    // Process the payment data directly (no backend verification needed)
    this.transactionDetails = {
      transactionId: params.txnid,
      paymentId: params.mihpayid || params.payuMoneyId || 'N/A',
      status: params.status,
      amount: params.amount,
      customerName: `${params.firstname || ''} ${params.lastname || ''}`.trim(),
      customerEmail: params.email || '',
      customerPhone: params.phone || '',
      products: params.productinfo || '',
      paymentMode: params.mode || 'Online',
      transactionDate: new Date().toLocaleString(),
      bankRefNumber: params.bank_ref_num || ''
    };
    
    this.loading = false;
    
    // Process dispensing if payment successful
    if (params.status === 'success') {
      this.processMachineDispensing(params);
    }
  }

  processMachineDispensing(params: any) {
    // Extract machine dispensing instructions from UDF fields
    const machineId = params.udf1; // Machine ID stored in UDF1
    const cartData = params.udf2; // Cart data stored in UDF2
    
    if (machineId && cartData && !this.dispensing) {
      this.dispensing = true;
      
      try {
        const parsedCartData = JSON.parse(cartData);
        
        // Create dispensing instructions
        const dispensingInstructions = parsedCartData.map((item: any) => ({
          slotId: item.slotId,
          rowId: item.slotId ? item.slotId[0] : '',
          column: item.slotId ? parseInt(item.slotId.substring(1)) : 0,
          quantity: item.quantity,
          productName: item.productName
        }));
        
        this.http.post(`${environment.apiUrl}/dispense-products`, {
          transactionId: params.txnid,
          machineId: machineId,
          paymentStatus: params.status,
          dispensingInstructions: dispensingInstructions
        }).subscribe({
          next: (response) => {
            console.log('Dispensing initiated:', response);
            // Clear cart from session storage
            sessionStorage.removeItem('pendingCart');
            sessionStorage.removeItem('pendingMachineId');
            
            setTimeout(() => {
              this.dispensing = false;
            }, 3000);
          },
          error: (error) => {
            console.error('Dispensing error:', error);
            this.dispensing = false;
          }
        });
      } catch (e) {
        console.error('Error parsing cart data:', e);
        this.dispensing = false;
      }
    }
  }

  goToMachine() {
    // Get machine ID from transaction details
    const machineId = this.route.snapshot.queryParams['udf1'];
    
    if (machineId) {
      this.router.navigate(['/machine-slots', machineId]);
    } else {
      // Fallback - you might need to adjust this route based on your app structure
      this.router.navigate(['/login']);
    }
  }

  printReceipt() {
    window.print();
  }
}