<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';

try {
    $transactionId = $_GET['transaction_id'] ?? $_POST['transaction_id'] ?? null;
    $appointmentId = $_GET['appointment_id'] ?? $_POST['appointment_id'] ?? null;
    
    if (!$transactionId) {
        throw new Exception('Transaction ID is required');
    }
    
    $pdo = getDBConnection();
    
    // Check if payment record exists
    $stmt = $pdo->prepare("
        SELECT * FROM payments 
        WHERE transaction_id = ? 
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$transactionId]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$payment) {
        // Create a new payment record with pending status
        $stmt = $pdo->prepare("
            INSERT INTO payments (
                transaction_id, 
                appointment_id, 
                amount, 
                status, 
                payment_method, 
                created_at
            ) VALUES (?, ?, ?, 'PENDING', 'PHONEPE', NOW())
        ");
        $stmt->execute([$transactionId, $appointmentId, 0]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Payment record created',
            'payment_status' => 'PENDING',
            'transaction_id' => $transactionId,
            'appointment_id' => $appointmentId
        ]);
        exit;
    }
    
    // Return payment status
    echo json_encode([
        'success' => true,
        'message' => 'Payment status retrieved',
        'payment_status' => $payment['status'],
        'transaction_id' => $payment['transaction_id'],
        'appointment_id' => $payment['appointment_id'],
        'amount' => $payment['amount'],
        'payment_method' => $payment['payment_method'],
        'created_at' => $payment['created_at']
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
