<?php
require 'config.php';

$data = json_decode(file_get_contents("php://input"), true);
$result = $data['Body']['stkCallback'];

$status = $result['ResultCode'] == 0 ? 'paid' : 'failed';
$receipt = null;

if ($status === 'paid') {
    foreach ($result['CallbackMetadata']['Item'] as $item) {
        if ($item['Name'] === 'MpesaReceiptNumber') {
            $receipt = $item['Value'];
        }
    }
}

$stmt = $pdo->prepare("
    UPDATE mpesa_payments
    SET status=?, mpesa_receipt=?, result_desc=?
    WHERE checkout_request_id=?
");
$stmt->execute([
    $status,
    $receipt,
    $result['ResultDesc'],
    $result['CheckoutRequestID']
]);

echo json_encode(["ResultCode" => 0, "ResultDesc" => "OK"]);
