<?php
// payment_callback.php - Handle M-Pesa callback (no UI, as it's a callback endpoint)
include_once 'config.php';

$callback_json = file_get_contents('php://input');
$callback_data = json_decode($callback_json, true);

$checkout_request_id = $callback_data['Body']['stkCallback']['CheckoutRequestID'];
$result_code = $callback_data['Body']['stkCallback']['ResultCode'];

if ($result_code == 0) {
    // Payment successful
    $metadata = $callback_data['Body']['stkCallback']['CallbackMetadata']['Item'];
    $transaction_id = $metadata[4]['Value']; // M-Pesa receipt number
    $amount = $metadata[0]['Value'];
    $phone_number = $metadata[3]['Value'];
    
    // Update order status to 'paid'
    $stmt = $conn->prepare("UPDATE orders SET status = 'paid', transaction_id = ? WHERE checkout_request_id = ?");
    $stmt->bind_param("ss", $transaction_id, $checkout_request_id);
    $stmt->execute();
} else {
    // Payment failed
    $result_desc = $callback_data['Body']['stkCallback']['ResultDesc'];
    // Update order status to 'failed'
    $stmt = $conn->prepare("UPDATE orders SET status = 'failed' WHERE checkout_request_id = ?");
    $stmt->bind_param("s", $checkout_request_id);
    $stmt->execute();
}

// Log the callback for debugging
error_log($callback_json, 3, 'mpesa_callback.log');

// Respond to M-Pesa with OK
echo json_encode(["ResultCode" => 0, "ResultDesc" => "Accepted"]);
?>