<?php
// webhook_listener.php
$db = new PDO('sqlite:app_feed.db');

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

// 2. Security: Verify that the request is authentic
// Fetch the secret key dynamically from the database
$settings_query = $db->query("SELECT setting_value FROM app_feed_settings WHERE setting_key = 'secret_key'");
$settings = $settings_query->fetchColumn();

$provided_key = $_SERVER['HTTP_X_NOWPAYMENTS_SIG'] ?? '';

// Use the database value for verification
if ($provided_key !== hash_hmac('sha512', $payload, $settings)) {
    http_response_code(403);
    exit("Invalid API Key");
}

// 3. Process the payment confirmation
if (isset($data['payment_status']) && $data['payment_status'] === 'finished') {
    $amount = floatval($data['pay_amount']);
    $user_phone = $data['order_id']; 

    // Update the transaction log
    // We explicitly set payment_method to 'Crypto/Card' to keep your ledger organized
    $stmt = $db->prepare("UPDATE momo_transactions 
                          SET status = 'Completed (Verified)', payment_method = 'Crypto/Card' 
                          WHERE phone = :phone AND amount = :amount");
    $stmt->execute([':phone' => $user_phone, ':amount' => $amount]);

    // Update the user's account balance in your main MySQL database
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=imperial_credit_bank;charset=utf8", "root", "");
        
        // Fetch current user details
        $stmt = $pdo->prepare("SELECT balance_usd FROM users WHERE phone_number = ? LIMIT 1");
        $stmt->execute([$user_phone]);
        $user_row = $stmt->fetch();

        // Calculate new balance
        $old_balance = $user_row ? floatval($user_row['balance_usd']) : 0;
        $new_balance = $old_balance + $amount;
        
        // Level calculation logic
        $level = ($new_balance > 500) ? 4 : (($new_balance > 150) ? 3 : (($new_balance > 25) ? 2 : 1));

        // Perform Update
        $update_stmt = $pdo->prepare("UPDATE users SET balance_usd = ?, current_level = ? WHERE phone_number = ?");
        $update_stmt->execute([$new_balance, $level, $user_phone]);
            
        http_response_code(200);
        echo "Webhook Processed and Balance Updated Successfully";
        
    } catch (PDOException $e) {
        http_response_code(500);
        echo "Database error during balance update: " . $e->getMessage();
    }
} else {
    http_response_code(400);
    echo "Payment not finished";
}
?>