<?php
// api/check_status.php — Kindamba Pay Order Status Check

// Always return JSON — catch fatal errors before they output HTML
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (!headers_sent()) header('Content-Type: application/json');
        echo json_encode(['status' => 'pending', 'error' => 'Server error: ' . $err['message']]);
    }
});

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

$baseDir = dirname(__DIR__);
require_once $baseDir . '/config.php';
require_once $baseDir . '/includes/kindamba.php';

$tranId = trim($_GET['tran_id'] ?? $_GET['id'] ?? '');
if (empty($tranId)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing transaction ID (tran_id or id)']);
    exit;
}

// Logic for Public Key:
// 1. Check if token is passed in GET
// 2. Otherwise use global KINDAMBA_PUBLIC_KEY
$publicKey = !empty($_GET['token']) ? $_GET['token'] : (defined('KINDAMBA_PUBLIC_KEY') ? KINDAMBA_PUBLIC_KEY : null);

// 1. First check if we already have a finalized status in our local database
// This is critical because webhooks might have already updated the status.
require_once $baseDir . '/includes/db.php';
$localStatus = 'pending';
try {
    $stmt = $pdo->prepare("SELECT status FROM transactions WHERE tran_id = ? LIMIT 1");
    $stmt->execute([$tranId]);
    $localStatus = $stmt->fetchColumn() ?: 'pending';
} catch (Exception $e) {}

// If database already knows it's completed or failed, return that immediately.
if (in_array($localStatus, ['completed', 'failed', 'cancelled', 'user_cancelled', 'rejected', 'expired'])) {
    echo json_encode([
        'status'         => $localStatus,
        'raw_status'     => $localStatus,
        'message'        => 'Status retrieved from local database.',
        'transaction_id' => $tranId,
        'source'         => 'db'
    ]);
    exit;
}

// 2. Call Kindamba status endpoint for real-time verification
$result = kindamba_verify_status($tranId, $publicKey);
$data = $result['data'];

if ($result['code'] < 200 || $result['code'] >= 300) {
    if ($result['code'] === 401) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid or inactive API key', 'code' => 401]);
    } else {
        echo json_encode(['status' => 'error', 'message' => $data['message'] ?? 'Kindamba API error (HTTP ' . $result['code'] . ')']);
    }
    exit;
}

/**
 * Kindamba Pay Status Mapping
 * Expected status from API: pending, completed, failed, cancelled, expired
 */
// Handle API response inconsistency: Status can be in root or nested under 'data'
$rawStatus = strtolower(
    $data['data']['status'] 
    ?? $data['data']['payment_status']
    ?? $data['status'] 
    ?? $data['payment_status'] 
    ?? 'pending'
);

$statusMap = [
    'success'        => 'completed',
    'completed'      => 'completed',
    'paid'           => 'completed',
    'successful'     => 'completed',
    'failed'         => 'failed',
    'error'          => 'failed',
    'user_cancelled' => 'cancelled',
    'cancelled'      => 'cancelled',
    'canceled'       => 'cancelled',
    'rejected'       => 'failed',
    'expired'        => 'expired',
    'pending'        => 'pending',
    'inprogress'     => 'pending',
    'processing'     => 'pending',
    'initiated'      => 'pending',
];

$finalStatus = $statusMap[$rawStatus] ?? 'pending';

// Update database as fallback to webhook
if ($finalStatus !== 'pending') {
    require_once $baseDir . '/includes/db.php';
    try {
        $dbStatus = ($finalStatus === 'completed') ? 'completed' : $finalStatus;
        $stmt = $pdo->prepare("UPDATE transactions SET status = ? WHERE tran_id = ? AND status = 'pending'");
        $stmt->execute([$dbStatus, $tranId]);
    } catch (Exception $e) {
        error_log('[KindambaPay] DB Update Error in check_status: ' . $e->getMessage());
    }
}

echo json_encode([
    'status'     => $finalStatus,
    'raw_status' => $rawStatus,
    'message'    => $data['message'] ?? ($data['data']['message'] ?? ''),
    'transaction_id' => $tranId
]);
