<?php
// Secure Backend IPN Endpoint for automated payment processing
require_once __DIR__ . '/../../../config/config.php';

// Retrieve raw POST data from NOWPayments IPN
$raw_data = file_get_contents('php://input');
$json = json_decode($raw_data, true);

if (!$json) {
    http_response_code(400);
    exit("No JSON data received.");
}

// Fetch IPN secret from database for verification security
$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'nowpayments_ipn_secret'");
$local_ipn_secret = $stmt->fetchColumn();

// Validate payload authentication header
$received_hmac = $_SERVER['HTTP_X_NOWPAYMENTS_SIG'] ?? '';
$calculated_hmac = hash_hmac('sha512', $raw_data, $local_ipn_secret);

if (!hash_equals($calculated_hmac, $received_hmac)) {
    http_response_code(400);
    exit("HMAC Signature verification failed.");
}

// Check payment status
$payment_status = $json['payment_status'] ?? '';
$order_id = $json['order_id'] ?? '';
$pay_amount = $json['pay_amount'] ?? 0;

if ($payment_status === 'finished' || $payment_status === 'confirmed') {
    // Extract User ID and Plan ID from custom Order ID string logic (e.g., INV_{user_id}_{timestamp})
    preg_match('/INV_(\d+)_(\d+)/', $order_id, $matches);
    
    if ($matches) {
        $user_id = $matches[1];
        
        // Retrieve transaction/plan identification or fetch active temporary invoice logs
        $ledger_stmt = $pdo->prepare("SELECT plan_id, duration_days FROM subscription_plans WHERE price = ? ORDER BY id ASC LIMIT 1");
        $ledger_stmt->execute([$json['price_amount']]);
        $plan_data = $ledger_stmt->fetch(PDO::FETCH_ASSOC);

        if ($plan_data) {
            $plan_id = $plan_data['plan_id'];
            $expiry_date = date('Y-m-d H:i:s', strtotime("+" . $plan_data['duration_days'] . " days"));

            // Activate subscription securely
            $sub_stmt = $pdo->prepare("INSERT INTO user_subscriptions (user_id, plan_id, expires_at, is_active) 
                                       VALUES (?, ?, ?, 1) 
                                       ON DUPLICATE KEY UPDATE plan_id = ?, expires_at = ?, is_active = 1");
            $sub_stmt->execute([$user_id, $plan_id, $expiry_date, $plan_id, $expiry_date]);

            // Save transaction entry inside the platform ledger
            $trans_stmt = $pdo->prepare("INSERT INTO transactions (user_id, plan_id, amount_paid, payment_method, status) 
                                         VALUES (?, ?, ?, 'NOWPayments (Crypto)', 'success')");
            $trans_stmt->execute([$user_id, $plan_id, $json['price_amount']]);
        }
    }
    http_response_code(200);
    exit("Payment processed and ledger updated.");
} else {
    http_response_code(200);
    exit("Event status ignored (not finished).");
}
?>