<?php
// PayPal credentials
$clientId = "AaLGC7ZxUxzRNpXCiiwPtzcwpnIP_e7pZ5tCglOa16D-iCBgYO8VUWSR-og87FLFecQdL_kqzeobXj_f";  // Replace with your PayPal Client ID
$secret = "EJfjPKYh_8E0M0aRQF2mHvcRUn_Rv1kuuFizJUkX5JTCioljbeO7Dy4cG3YH4fEvD5oKmqGM3chSeavJ";       // Replace with your PayPal Secret

// Set PayPal's environment (sandbox for testing, live for production)
$paypalMode = "sandbox";  // Use 'sandbox' for testing, 'live' for production

// For EFT Payments: Set your bank details (just as an example)
$bankDetails = [
    'account_name' => 'Your Bank Name',
    'account_number' => '1234567890',
    'routing_number' => '987654321',
    'bank_address' => '123 Bank St, Your City, Your Country'
];

// Handle form submissions (either for PayPal checkout or EFT)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['payment_method']) && $_POST['payment_method'] == 'paypal') {
        // Handle PayPal Payment
        $paymentAmount = $_POST['amount'];  // Payment amount from the form
        processPaypalPayment($paymentAmount, $clientId, $secret, $paypalMode);
    } elseif (isset($_POST['payment_method']) && $_POST['payment_method'] == 'eft') {
        // Handle EFT (Electronic Funds Transfer) Payment
        $paymentAmount = $_POST['amount'];  // Payment amount from the form
        handleEftPayment($paymentAmount, $bankDetails);
    }
}

// Function to process PayPal payment using PayPal Checkout API
function processPaypalPayment($amount, $clientId, $secret, $paypalMode) {
    // Set PayPal API endpoint
    $apiUrl = $paypalMode == 'sandbox' ? 'https://api.sandbox.paypal.com/v1/payments/payment' : 'https://api.paypal.com/v1/payments/payment';

    // Prepare PayPal payment request data
    $paymentData = [
        'intent' => 'sale',
        'payer' => [
            'payment_method' => 'paypal'
        ],
        'transactions' => [
            [
                'amount' => [
                    'total' => $amount,
                    'currency' => 'USD',
                ],
                'description' => 'Payment for your order'
            ]
        ],
        'redirect_urls' => [
            'return_url' => 'http://localhost/success.php',
            'cancel_url' => 'http://localhost/cancel.php'
        ]
    ];

    // Convert the array to JSON format for PayPal API request
    $paymentJson = json_encode($paymentData);

    // Prepare PayPal authentication headers
    $headers = [
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode("$clientId:$secret")
    ];

    // Send POST request to PayPal API
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $paymentJson);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($ch);
    curl_close($ch);

    // Decode the response
    $responseObj = json_decode($response);

    // Handle the response (e.g., redirect the user to PayPal for approval)
    if (isset($responseObj->links)) {
        foreach ($responseObj->links as $link) {
            if ($link->rel == 'approval_url') {
                header("Location: " . $link->href);
                exit;
            }
        }
    } else {
        echo "Error: Unable to create payment. " . $responseObj->message;
    }
}

// Function to handle EFT payment (this example is a mock-up for EFT handling)
function handleEftPayment($amount, $bankDetails) {
    echo "<h3>EFT Payment Details</h3>";
    echo "<p>Payment Amount: $" . $amount . "</p>";
    echo "<p>Bank Name: " . $bankDetails['account_name'] . "</p>";
    echo "<p>Account Number: " . $bankDetails['account_number'] . "</p>";
    echo "<p>Routing Number: " . $bankDetails['routing_number'] . "</p>";
    echo "<p>Bank Address: " . $bankDetails['bank_address'] . "</p>";
    echo "<p>Please transfer the funds to the above account and send the payment reference number to us.</p>";
    echo "<p><strong>Important:</strong> EFT payments are manually verified and processed. Please wait for confirmation.</p>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Page</title>
    <script src="https://www.paypal.com/sdk/js?client-id=<?= $clientId ?>&components=buttons&currency=USD"></script>
</head>
<body>

    <h1>Payment Options</h1>

    <form method="post" action="">
        <label for="amount">Amount ($):</label>
        <input type="number" name="amount" id="amount" value="20.00" required>

        <br><br>
        <h3>Pay with PayPal:</h3>
        <button type="submit" name="payment_method" value="paypal">Pay with PayPal</button>

        <br><br>
        <h3>Pay with EFT:</h3>
        <button type="submit" name="payment_method" value="eft">Pay with EFT</button>
    </form>

    <div id="paypal-button-container"></div>

    <script>
        // PayPal button render (only for PayPal payments)
        paypal.Buttons({
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: document.getElementById("amount").value
                        }
                    }]
                });
            },
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    alert('Payment successful for ' + details.payer.name.given_name);
                    window.location.href = "success.php";  // Redirect after success
                });
            },
            onCancel: function(data) {
                alert('Payment was canceled');
                window.location.href = "cancel.php";  // Redirect after cancel
            }
        }).render('#paypal-button-container'); // Render the PayPal button here
    </script>

</body>
</html>