<?php
session_start();

// Your sandbox access token (replace with production token later)
$access_token = "gPAV9lMCptoUOwvZbf7pN_V0TFfYI4-2BL3kpKH5yKw";

// Read POST data from JS
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    echo "Invalid input!";
    exit;
}

$name = $input['name'] ?? '';
$phone = $input['phone'] ?? '';
$address = $input['address'] ?? '';
$notes = $input['notes'] ?? '';
$tip = $input['tip'] ?? 0;
$shipping = $input['shipping'] ?? 0;

// Calculate total amount from cart + tip + shipping
$cart = $_SESSION['cart'] ?? [];
$subtotal = 0;
foreach ($cart as $item) {
    $qty = intval($item['quantity']);
    $price = floatval($item['price']);
    $subtotal += $qty * $price;
}
$totalAmount = $subtotal + $tip + $shipping;

// STK Push payload
$payload = [
    "amount" => $totalAmount,
    "currency" => "KES",
    "payment_channel" => "M-PESA",
    "metadata" => [
        "name" => $name,
        "phone" => $phone,
        "address" => $address,
        "notes" => $notes,
        "order_id" => uniqid("TajiYetu_")
    ],
    "callback_url" => "https://yourdomain.com/payment_callback.php", // replace with your domain
    "external_id" => uniqid("order_")
];

// Send STK Push to Kopo Kopo
$ch = curl_init("https://sandbox.kopokopo.com/payments");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $access_token"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo "Payment request failed: " . curl_error($ch);
    exit;
}
curl_close($ch);

$result = json_decode($response, true);

// Handle response
if (isset($result['id'])) {
    $_SESSION['last_order'] = [
        'order_id' => $payload['metadata']['order_id'],
        'transaction_id' => $result['id'],
        'amount' => $totalAmount
    ];
    echo "✅ Payment request sent! Check your phone to complete the payment.";
} else {
    echo "❌ Payment failed: " . $response;
}
?>
