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

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

try {
    $pdo = getDBConnection();
    
    // Get payment ID from POST data
    $input = json_decode(file_get_contents('php://input'), true);
    $paymentId = $input['payment_id'] ?? null;
    
    if (!$paymentId) {
        throw new Exception('Payment ID is required');
    }
    
    // Get payment details with user information
    $query = "
        SELECT 
            p.*,
            a.user_name,
            a.user_mobile,
            a.appointment_date,
            a.time_slot,
            a.consultation_type
        FROM payments p
        LEFT JOIN appointments a ON p.appointment_id = a.id
        WHERE p.id = :payment_id
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([':payment_id' => $paymentId]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$payment) {
        throw new Exception('Payment not found');
    }
    
    $response = [
        'success' => true,
        'payment' => $payment
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Payment details error: " . $e->getMessage());
    
    $response = [
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ];
    
    echo json_encode($response);
}
?>
