<?php
// Paystack Webhook Handler
require_once '../../config.php';
require_once '../../config_paystack.php';

// Validate Paystack signature
$input = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] ?? '';
if (!$signature) {
    http_response_code(400);
    echo 'Missing signature';
    exit;
}

$expected = hash_hmac('sha512', $input, $PAYSTACK_SECRET_KEY);
if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    echo 'Invalid signature';
    exit;
}

$event = json_decode($input, true);
if (!is_array($event)) {
    http_response_code(400);
    echo 'Invalid payload';
    exit;
}

$type = $event['event'] ?? '';
$data = $event['data'] ?? [];
$reference = $data['reference'] ?? '';
$status = $data['status'] ?? '';

if ($type === 'charge.success' && $status === 'success' && $reference !== '') {
    // Verify server-side to be safe
    $verify = paystackVerifyTransaction($reference);
    $ok = $verify['success'] && (($verify['data']['data']['status'] ?? '') === 'success');
    if (!$ok) {
        http_response_code(202);
        echo 'Verification deferred';
        exit;
    }

    // SECURITY: Find order using prepared statement to prevent SQL injection
    $stmt = $conn->prepare("SELECT * FROM pending_databundle_orders WHERE reference = ? LIMIT 1");
    if (!$stmt) {
        error_log("Paystack webhook: Failed to prepare statement - " . $conn->error);
        http_response_code(500);
        echo 'Database error';
        exit;
    }
    $stmt->bind_param("s", $reference);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    
    if ($row) {
        // Move to verified table
        $insertStmt = $conn->prepare("INSERT INTO verified_databundle_orders (original_id, momo_name, momo_number, package, package_mb, amount_paid, reference, megabytes, received, network_type, external_transaction_id, api_response_data, payment_verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        if (!$insertStmt) {
            error_log("Paystack webhook: Failed to prepare insert statement - " . $conn->error);
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $external_id = $data['id'] ?? null;
        $api_data = json_encode($data);
        $original_id = $row['id'];
        $insertStmt->bind_param("issssdssisss", $original_id, $row['momo_name'], $row['momo_number'], $row['package'], $row['package_mb'], $row['amount_paid'], $row['reference'], $row['megabytes'], $row['received'], $row['network_type'], $external_id, $api_data);
        
        if (!$insertStmt->execute()) {
            error_log("Paystack webhook: Failed to insert verified order - " . $insertStmt->error);
            $insertStmt->close();
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $insertStmt->close();

        // Update main orders table status to paid
        $updateMain = $conn->prepare("UPDATE orders SET status = 'paid', status_updated_at = NOW(), external_transaction_id = ? WHERE order_reference = ?");
        if (!$updateMain) {
            error_log("Paystack webhook: Failed to prepare update statement - " . $conn->error);
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $updateMain->bind_param("ss", $external_id, $row['reference']);
        if (!$updateMain->execute()) {
            error_log("Paystack webhook: Failed to update order - " . $updateMain->error);
            $updateMain->close();
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $updateMain->close();

        // SECURITY: Remove from pending using prepared statement
        $deleteStmt = $conn->prepare("DELETE FROM pending_databundle_orders WHERE id = ?");
        if (!$deleteStmt) {
            error_log("Paystack webhook: Failed to prepare delete statement - " . $conn->error);
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $deleteStmt->bind_param("i", $row['id']);
        if (!$deleteStmt->execute()) {
            error_log("Paystack webhook: Failed to delete pending order - " . $deleteStmt->error);
            $deleteStmt->close();
            http_response_code(500);
            echo 'Database error';
            exit;
        }
        $deleteStmt->close();

        http_response_code(200);
        echo 'ok';
        exit;
    }
}

http_response_code(200);
echo 'ignored';




