<?php
header('Content-Type: application/json');

// Use the correct path to conn.php
$connPath = __DIR__ . '/conn.php';
if (!file_exists($connPath)) {
    die(json_encode(['error' => 'Database connection file not found']));
}
require_once $connPath;

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Log function
function logMessage($message) {
    $logFile = __DIR__ . '/webhook_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

// Log the start of webhook processing
logMessage("Webhook processing started");

try {
    // Get the raw POST data
    $rawData = file_get_contents('php://input');
    
    // Log the raw data
    logMessage("Raw webhook data: " . $rawData);
    
    // Decode the JSON payload
    $payload = json_decode($rawData, true);
    
    if (!$payload) {
        throw new Exception("Invalid JSON payload");
    }
    
    // Verify this is a payment notification
    if ($payload['event'] !== 'PAYMENT_NOTIFICATION') {
        throw new Exception("Invalid event type");
    }
    
    // Extract transaction data
    $transactionData = $payload['data'];
    $amount = $transactionData['amount'];
    $transactionRef = $transactionData['transaction_ref'];
    $createdAt = $transactionData['created_at'];
    $customerEmail = $transactionData['customer']['email'];
    
    // No charge applied, full amount added to wallet
    $profit = 0;
    
    // Log transaction details
    logMessage("Processing transaction for email: " . $customerEmail);
    logMessage("Amount: " . $amount . ", Charge: 0");
    
    // Get user ID and current wallet balance from email
    $stmt = $con->prepare("SELECT sId, sWallet FROM subscribers WHERE sEmail = ?");
    if (!$stmt) {
        throw new Exception("Failed to prepare user query: " . $con->error);
    }
    
    $stmt->bind_param("s", $customerEmail);
    $stmt->execute();
    $result = $stmt->get_result();
    $userData = $result->fetch_assoc();
    
    if (!$userData) {
        throw new Exception("User not found for email: " . $customerEmail);
    }
    
    $userId = $userData['sId'];
    $oldBalance = $userData['sWallet'];
    $newBalance = $oldBalance + $amount; // Add full amount to the wallet
    
    // Begin transaction
    $con->begin_transaction();
    
    try {
        // Insert transaction record
        $insertSql = "INSERT INTO transactions (
            sId, 
            transref,
            servicename,
            servicedesc,
            amount,
            status,
            oldbal,
            newbal,
            profit,
            date,
            api_response
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $insertStmt = $con->prepare($insertSql);
        if (!$insertStmt) {
            throw new Exception("Failed to prepare insert statement: " . $con->error);
        }
        
        $serviceName = "Wallet Funding";
        $serviceDesc = "Billstack Payment (No charge)";
        $status = 0; // Assuming 1 means success
        $apiResponse = json_encode($payload);
        
        $insertStmt->bind_param(
            "issssdssiss",
            $userId,
            $transactionRef,
            $serviceName,
            $serviceDesc,
            $amount,
            $status,
            $oldBalance,
            $newBalance,
            $profit,
            $createdAt,
            $apiResponse
        );
        
        if (!$insertStmt->execute()) {
            throw new Exception("Failed to insert transaction: " . $insertStmt->error);
        }
        
        // Update user's wallet balance
        $updateSql = "UPDATE subscribers SET sWallet = ? WHERE sId = ?";
        $updateStmt = $con->prepare($updateSql);
        if (!$updateStmt) {
            throw new Exception("Failed to prepare update statement: " . $con->error);
        }
        
        $updateStmt->bind_param("di", $newBalance, $userId);
        if (!$updateStmt->execute()) {
            throw new Exception("Failed to update wallet: " . $updateStmt->error);
        }
        
        // Commit transaction
        $con->commit();
        
        logMessage("Transaction processed successfully for user ID: " . $userId);
        
        echo json_encode([
            'success' => true,
            'message' => 'Transaction processed successfully',
            'transaction_ref' => $transactionRef,
            'amount' => $amount,
            'charge_amount' => 0,
            'added_to_wallet' => $amount
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $con->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    logMessage("Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    if (isset($insertStmt)) $insertStmt->close();
    if (isset($updateStmt)) $updateStmt->close();
    if (isset($con)) $con->close();
}
?>

