<?php
/**
 * STRIPE CHECKOUT – DONATION SERVER
 * Wipe Tears Africa
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);

// --------------------
// CONFIG
// --------------------
$STRIPE_SECRET_KEY = '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'; 

$SUCCESS_URL = 'https://www.wipetearsafrica.org/donate-success.php';
$CANCEL_URL  = 'https://www.wipetearsafrica.org/donate-cancel.php';

// --------------------
// ONLY ACCEPT POST
// --------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// --------------------
// SANITIZE INPUT
// --------------------
$fullname = trim($_POST['full_name'] ?? '');
$email    = trim($_POST['email'] ?? '');

// Handle preset OR custom amount
$amount = 0;
if (!empty($_POST['amount_custom']) && floatval($_POST['amount_custom']) > 0) {
    $amount = floatval($_POST['amount_custom']);
} else {
    $amount = floatval($_POST['amount'] ?? 0);
}

// --------------------
// VALIDATION
// --------------------
if ($fullname === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || $amount <= 0) {
    exit('Invalid donation details');
}

// Convert amount to cents
$amount_cents = (int) round($amount * 100);

// --------------------
// CREATE STRIPE CHECKOUT SESSION (NO SDK)
// --------------------
$data = [
    'payment_method_types' => ['card'],
    'mode' => 'payment',
    'customer_email' => $email,
    'line_items' => [[
        'price_data' => [
            'currency' => 'usd',
            'product_data' => [
                'name' => 'Donation – Wipe Tears Africa',
                'description' => 'Donor: ' . $fullname,
            ],
            'unit_amount' => $amount_cents,
        ],
        'quantity' => 1,
    ]],
    'success_url' => $SUCCESS_URL,
    'cancel_url'  => $CANCEL_URL,
];

// --------------------
// CURL REQUEST TO STRIPE
// --------------------
$ch = curl_init('https://api.stripe.com/v1/checkout/sessions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $STRIPE_SECRET_KEY,
    'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);

// --------------------
// ERROR CHECK
// --------------------
if ($http_code !== 200 || !isset($result['url'])) {
    echo 'Stripe error. Please try again later.';
    exit;
}

// --------------------
// REDIRECT TO STRIPE CHECKOUT
// --------------------
header('Location: ' . $result['url']);
exit;
