<?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';

/**
 * Check M-Pesa Transaction Status
 * Polls the database for transaction status updates
 */

try {
    $checkout_request_id = $_POST['checkout_request_id'] ?? '';
    
    if (empty($checkout_request_id)) {
        throw new Exception('Checkout Request ID is required');
    }
    
    // Query transaction status
    $sql = "SELECT mt.*, p.payment_id 
            FROM mpesa_transactions mt
            LEFT JOIN payments p ON mt.transaction_id = p.mpesa_transaction_id
            WHERE mt.checkout_request_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $checkout_request_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    if (!$result) {
        echo json_encode([
            'status' => 'PENDING',
            'message' => 'Transaction not found'
        ]);
        exit();
    }
    
    $status = $result['status'];
    
    if ($status === 'COMPLETED') {
        echo json_encode([
            'status' => 'COMPLETED',
            'message' => 'Payment completed successfully',
            'payment_id' => $result['payment_id'],
            'mpesa_receipt' => $result['mpesa_receipt_number'],
            'amount' => $result['amount']
        ]);
    } elseif ($status === 'FAILED') {
        echo json_encode([
            'status' => 'FAILED',
            'message' => $result['result_description'] ?? 'Payment failed'
        ]);
    } elseif ($status === 'CANCELLED') {
        echo json_encode([
            'status' => 'CANCELLED',
            'message' => 'Payment was cancelled'
        ]);
    } else {
        echo json_encode([
            'status' => 'PENDING',
            'message' => 'Waiting for customer to complete payment'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'ERROR',
        'message' => $e->getMessage()
    ]);
}
?>