<?php
require __DIR__ . '/config.php';

// 1. Setup Logging
$log_file = __DIR__ . '/webhook_log.txt';
function log_debug($msg) {
    global $log_file;
    file_put_contents($log_file, "[" . date('Y-m-d H:i:s') . "] " . $msg . "\n", FILE_APPEND);
}

// 2. Get Data
$json = file_get_contents('php://input');
if (empty($json)) {
    exit("Webhook endpoint. Do not access directly.");
}

log_debug("Raw Input Received: " . $json);
$data = json_decode($json, true);

// 3. Verify Secret Hash
$secret = "movyra_secret_123"; 
$headers = function_exists('getallheaders') ? getallheaders() : [];
if (empty($headers) && isset($_SERVER['HTTP_VERIF_HASH'])) {
    $headers['verif-hash'] = $_SERVER['HTTP_VERIF_HASH'];
}
$sig = isset($headers['verif-hash']) ? $headers['verif-hash'] : '';

if ($sig !== $secret) {
    log_debug("WARNING: Signature Mismatch! Received: $sig | Expected: $secret");
}

// 4. Process Payment
$event = $data['event'] ?? '';
log_debug("Event Type: " . $event);

if ($event == 'charge.completed' || $event == 'transfer.completed') {
    $amount = $data['data']['amount'];
    $currency = $data['data']['currency'];
    $user = null;

    log_debug("Amount: $amount | Currency: $currency");

    if ($currency == 'NGN' && $amount > 0) {
        $account_number = '';

        // METHOD A: Check meta (Works if "Add meta to webhook" is checked in Flutterwave)
        if (isset($data['data']['meta']['account_number'])) {
            $account_number = $data['data']['meta']['account_number'];
            log_debug("Method A: Found account number in meta: " . $account_number);
        }         // METHOD B: Check direct data
        elseif (isset($data['data']['account_number'])) {
            $account_number = $data['data']['account_number'];
        }
        
        // METHOD C (FALLBACK): Parse the Narration to find the username
        // Example narration: "Movyra Wallet Funding for Muskid"
        if (empty($account_number)) {
            $narration = $data['data']['narration'] ?? '';
            log_debug("Method C: Checking Narration: " . $narration);
            
            if (strpos($narration, 'Movyra Wallet Funding for ') !== false) {
                $username = trim(str_replace('Movyra Wallet Funding for ', '', $narration));
                log_debug("Method C: Extracted username: " . $username);
                
                // Find user directly by username
                $stmt = $pdo->prepare("SELECT id, username, wallet_balance FROM users WHERE username = ?");
                $stmt->execute([$username]);
                $user = $stmt->fetch();
                
                if ($user) {
                    log_debug("Method C SUCCESS: Found user " . $user['username']);
                }
            }
        }

        // If we found the account number (Method A or B), find user by account number
        if (!$user && !empty($account_number)) {
            log_debug("Method A/B: Searching user by account number: " . $account_number);
            $stmt = $pdo->prepare("SELECT id, username, wallet_balance FROM users WHERE virtual_account_number = ?");
            $stmt->execute([$account_number]);
            $user = $stmt->fetch();
        }

        // 5. Credit the User and Update Deposit History
        if ($user) {
            // A. Update Wallet Balance
            $new_balance = $user['wallet_balance'] + $amount;
            $updateStmt = $pdo->prepare("UPDATE users SET wallet_balance = ? WHERE id = ?");
            $updateStmt->execute([$new_balance, $user['id']]);
            
            // B. Check if there is a 'Pending' deposit (from the "I've Made Transfer" button)
            $checkPending = $pdo->prepare("SELECT id FROM deposits WHERE user_id = ? AND amount = ? AND status = 'Pending' ORDER BY id DESC LIMIT 1");
            $checkPending->execute([$user['id'], $amount]);
            $pendingDep = $checkPending->fetch();

            if ($pendingDep) {
                // Update existing pending deposit to Completed
                $updateDep = $pdo->prepare("UPDATE deposits SET status = 'Completed' WHERE id = ?");
                $updateDep->execute([$pendingDep['id']]);                log_debug("Updated pending deposit ID " . $pendingDep['id'] . " to Completed.");
            } else {
                // Insert new deposit record (for permanent account transfers)
                $insertDep = $pdo->prepare("INSERT INTO deposits (user_id, amount, status) VALUES (?, ?, 'Completed')");
                $insertDep->execute([$user['id'], $amount]);
                log_debug("Created new deposit record for ₦" . $amount);
            }
            
            log_debug("FINAL SUCCESS: Credited user " . $user['username'] . " with ₦" . $amount . ". New Balance: ₦" . $new_balance);
            exit("Success");
        } else {
            log_debug("ERROR: Could not find user to credit.");
        }
    }
}

exit("Processed");
?>