<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

require_once '../layouts/dbconn.php';

$checkout_request_id = $_GET['checkout_request_id'] ?? '';
$transaction_id = $_GET['transaction_id'] ?? '';

if (empty($checkout_request_id) && empty($transaction_id)) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit();
}

// Get transaction status
$sql = "SELECT * FROM mpesa_transactions WHERE ";
if (!empty($checkout_request_id)) {
    $sql .= "checkout_request_id = ?";
    $param = $checkout_request_id;
    $type = 's';
} else {
    $sql .= "id = ?";
    $param = $transaction_id;
    $type = 'i';
}

$stmt = $conn->prepare($sql);
$stmt->bind_param($type, $param);
$stmt->execute();
$result = $stmt->get_result();
$transaction = $result->fetch_assoc();

if (!$transaction) {
    echo json_encode(['success' => false, 'message' => 'Transaction not found']);
    exit();
}

echo json_encode([
    'success' => true,
    'status' => $transaction['status'],
    'mpesa_receipt' => $transaction['mpesa_receipt_number'] ?? null,
    'message' => $transaction['status'] == 'COMPLETED' 
        ? 'Payment completed successfully!' 
        : ($transaction['status'] == 'FAILED' 
            ? 'Payment failed: ' . ($transaction['error_message'] ?? 'Unknown error')
            : 'Payment is being processed. Please wait...')
]);
?>
