<?php
// challenge-payment-callback.php
header('Content-Type: application/json');

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

if ($input['status'] === 'success') {
    $checkout_id = $input['data']['checkout_request_id'] ?? '';
    $reference   = $input['data']['external_reference'] ?? '';
    $amount      = $input['data']['amount'] ?? 0;

    $conn = getDbConnection();

    // Find pending contribution
    $stmt = $conn->prepare("
        SELECT cc.user_id, cc.challenge_id, cc.amount
        FROM challenge_contributions cc
        WHERE cc.checkout_request_id = ? OR cc.reference = ?
        AND cc.status = 'pending'
    ");
    $stmt->bind_param("ss", $checkout_id, $reference);
    $stmt->execute();
    $result = $stmt->get_result();
    $contrib = $result->fetch_assoc();
    $stmt->close();

    if ($contrib) {
        // Update contribution status
        $stmt = $conn->prepare("
            UPDATE challenge_contributions 
            SET status = 'completed', completed_at = NOW()
            WHERE checkout_request_id = ? OR reference = ?
        ");
        $stmt->bind_param("ss", $checkout_id, $reference);
        $stmt->execute();
        $stmt->close();

        // Update main challenge progress
        $update_stmt = $conn->prepare("
            UPDATE user_challenges 
            SET total_saved = total_saved + ?,
                current_week = CASE WHEN challenge_id = '52_week' THEN current_week + 1 ELSE current_week END
            WHERE user_id = ? AND challenge_id = ?
        ");
        $update_stmt->bind_param("dis", $amount, $contrib['user_id'], $contrib['challenge_id']);
        $update_stmt->execute();
        $update_stmt->close();
    }

    $conn->close();
}

echo json_encode(['status' => 'ok']);
?>