<?php
// webhook_listener.php
$db = new PDO('sqlite:app_feed.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 1. Get the payload
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);

// 2. Test Override (Allows you to bypass the key for testing via browser)
$is_test = isset($_GET['test']) && $_GET['test'] === 'true';

if (!$is_test) {
    $provided_key = $_SERVER['HTTP_X_API_KEY'] ?? '';
    $settings = $db->query("SELECT setting_value FROM app_feed_settings WHERE setting_key = 'secret_key'")->fetchColumn();

    if ($provided_key !== $settings) {
        http_response_code(403);
        exit("Invalid API Key");
    }
}

// 3. Simulated Data (If no JSON payload is sent, use this for a quick browser test)
if (!$data && $is_test) {
    $data = [
        'status' => 'finished',
        'payment_id' => 'TEST-' . uniqid(),
        'pay_amount' => 10.00,
        'order_id' => '+123456789'
    ];
}

// 4. Process the payment
if ($data && $data['status'] === 'finished') {
    $amount = floatval($data['pay_amount']);
    $user_phone = $data['order_id'];

    // Update transactions
    $stmt = $db->prepare("UPDATE momo_transactions SET status = 'Completed (Verified)' WHERE phone = :phone AND amount = :amount");
    $stmt->execute([':phone' => $user_phone, ':amount' => $amount]);

    // Update user balance
    $updateUser = $db->prepare("UPDATE users SET balance = balance + :amount WHERE phone = :phone");
    $updateUser->execute([':amount' => $amount, ':phone' => $user_phone]);
    
    http_response_code(200);
    echo "Webhook Processed Successfully for " . htmlspecialchars($user_phone);
} else {
    http_response_code(400);
    echo "Payment not finished or data missing";
}
?>