<?php
/**
 * API - Payment Webhook Receiver
 * Receives payment notifications and auto-credits wallet
 * Uses settings from Admin Panel
 */

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

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

// Get UPI settings from database
$upiId = getSetting('upi_id', 'merchant@upi');

// Log all incoming requests for debugging
$logDir = ROOT_PATH . '/logs';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);

$logData = [
    'time' => date('Y-m-d H:i:s'),
    'method' => $_SERVER['REQUEST_METHOD'],
    'headers' => getallheaders(),
    'get' => $_GET,
    'post' => $_POST,
    'raw' => file_get_contents('php://input')
];
file_put_contents($logDir . '/payment_webhook.log', json_encode($logData) . "\n", FILE_APPEND);

// Get input
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = array_merge($_GET, $_POST);
}

// Verify webhook secret (if provided)
$webhookSecret = getSetting('upi_webhook_secret', '');
$secret = $input['secret'] ?? $_SERVER['HTTP_X_WEBHOOK_SECRET'] ?? '';
if ($webhookSecret && $secret !== $webhookSecret) {
    error_log("Payment webhook called without valid secret");
}

// Expected parameters
$amount = (float)($input['amount'] ?? 0);
$utr = $input['utr'] ?? $input['transaction_id'] ?? $input['txn_id'] ?? '';
$senderUpi = $input['sender_upi'] ?? $input['payer_vpa'] ?? '';
$senderName = $input['sender_name'] ?? $input['payer_name'] ?? '';
$receiverUpi = $input['receiver_upi'] ?? $input['payee_vpa'] ?? $upiId;
$timestamp = $input['timestamp'] ?? $input['txn_time'] ?? date('Y-m-d H:i:s');
$paymentRef = $input['ref'] ?? $input['payment_ref'] ?? $input['note'] ?? '';

// Validate required fields
if ($amount <= 0) {
    jsonError('Invalid amount');
}

// Try to find matching pending payment
$payment = null;

// Method 1: Match by payment reference (if sender included it in note)
if (!empty($paymentRef)) {
    $payment = dbFetch(
        "SELECT * FROM upi_payments WHERE payment_ref = :ref AND status = 'pending' AND amount = :amt",
        ['ref' => $paymentRef, 'amt' => $amount]
    );
}

// Method 2: Match by exact amount and recent pending payment
if (!$payment) {
    $payment = dbFetch(
        "SELECT * FROM upi_payments 
         WHERE status = 'pending' 
         AND amount = :amt 
         AND expires_at > NOW() 
         ORDER BY created_at DESC 
         LIMIT 1",
        ['amt' => $amount]
    );
}

// Method 3: Check if UTR already processed (prevent duplicate)
if ($utr) {
    $existingTxn = dbFetch(
        "SELECT id FROM upi_payments WHERE utr_number = :utr AND status = 'completed'",
        ['utr' => $utr]
    );
    if ($existingTxn) {
        jsonSuccess('Payment already processed', ['duplicate' => true]);
    }
}

if (!$payment) {
    // No matching pending payment found
    // Log for manual review
    dbInsert('upi_payments', [
        'payment_ref' => 'UNMATCHED_' . time(),
        'user_id' => 0,
        'amount' => $amount,
        'upi_id' => $receiverUpi,
        'sender_upi' => $senderUpi,
        'sender_name' => $senderName,
        'utr_number' => $utr,
        'status' => 'unmatched',
        'raw_data' => json_encode($input)
    ]);
    
    jsonError('No matching pending payment found', 404, ['logged' => true]);
}

// Found matching payment - process it
try {
    dbBeginTransaction();
    
    $userId = $payment['user_id'];
    
    // Update payment status
    dbUpdate('upi_payments', [
        'status' => 'completed',
        'utr_number' => $utr,
        'sender_upi' => $senderUpi,
        'sender_name' => $senderName,
        'completed_at' => date('Y-m-d H:i:s'),
        'raw_data' => json_encode($input)
    ], 'id = :id', ['id' => $payment['id']]);
    
    // Credit user wallet
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);
    $currentBalance = $wallet['balance'] ?? 0;
    $newBalance = $currentBalance + $amount;
    
    if ($wallet) {
        dbUpdate('user_wallets', [
            'balance' => $newBalance,
            'total_deposited' => db()->query("SELECT total_deposited FROM user_wallets WHERE user_id = {$userId}")->fetchColumn() + $amount
        ], 'user_id = :uid', ['uid' => $userId]);
    } else {
        dbInsert('user_wallets', [
            'user_id' => $userId,
            'balance' => $amount,
            'total_deposited' => $amount
        ]);
    }
    
    // Create deposit record
    dbInsert('deposits', [
        'deposit_id' => 'DEP' . strtoupper(substr(md5(uniqid()), 0, 10)),
        'user_id' => $userId,
        'amount' => $amount,
        'payment_method' => 'upi',
        'transaction_id' => $utr,
        'status' => 'approved',
        'processed_at' => date('Y-m-d H:i:s'),
        'payment_details' => json_encode([
            'upi_id' => $senderUpi,
            'sender_name' => $senderName,
            'utr' => $utr
        ])
    ]);
    
    // Create transaction record
    dbInsert('transactions', [
        'user_id' => $userId,
        'type' => 'deposit',
        'amount' => $amount,
        'balance_after' => $newBalance,
        'description' => 'UPI Deposit - UTR: ' . ($utr ?: 'N/A'),
        'reference_id' => $payment['payment_ref'],
        'status' => 'completed'
    ]);
    
    // Apply deposit bonus if enabled
    $bonusEnabled = getSetting('deposit_bonus_enabled', '0') === '1';
    $bonusMinAmount = (float)getSetting('deposit_bonus_min_amount', 0);
    $bonusMaxBonus = (float)getSetting('deposit_bonus_max_bonus', 0);
    $turnoverMultiplier = (float)getSetting('bonus_turnover_multiplier', 30);
    
    if ($bonusEnabled && $amount >= $bonusMinAmount) {
        // Find applicable bonus tier
        $bonusTier = dbFetch(
            "SELECT * FROM deposit_bonus_tiers WHERE min_amount <= :amt AND status = 'active' ORDER BY min_amount DESC LIMIT 1",
            ['amt' => $amount]
        );
        
        $bonusPercent = 0;
        if ($bonusTier) {
            $bonusPercent = (float)$bonusTier['bonus_percent'];
        } else {
            // Use default bonus percent if no tier matches
            $bonusPercent = (float)getSetting('deposit_bonus_percent', 0);
        }
        
        if ($bonusPercent > 0) {
            $bonusAmount = $amount * ($bonusPercent / 100);
            
            // Apply max bonus cap
            if ($bonusMaxBonus > 0 && $bonusAmount > $bonusMaxBonus) {
                $bonusAmount = $bonusMaxBonus;
            }
            
            dbQuery(
                "UPDATE user_wallets SET bonus_balance = bonus_balance + :bonus WHERE user_id = :uid",
                ['bonus' => $bonusAmount, 'uid' => $userId]
            );
            
            // Set turnover requirement based on (deposit + bonus)
            $turnoverRequired = ($amount + $bonusAmount) * $turnoverMultiplier;
            dbQuery(
                "UPDATE users SET turnover_required = COALESCE(turnover_required, 0) + :tr WHERE id = :uid",
                ['tr' => $turnoverRequired, 'uid' => $userId]
            );
            
            // Set CFD withdrawal threshold
            $cfdMultiplier = (float)getSetting('cfd_balance_multiplier', 3);
            $cfdThreshold = ($amount + $bonusAmount) * $cfdMultiplier;
            dbQuery(
                "UPDATE users SET cfd_withdraw_threshold = COALESCE(cfd_withdraw_threshold, 0) + :ct WHERE id = :uid",
                ['ct' => $cfdThreshold, 'uid' => $userId]
            );
            
            dbInsert('transactions', [
                'transaction_id' => 'BNS' . strtoupper(substr(md5(uniqid()), 0, 10)),
                'user_id' => $userId,
                'type' => 'bonus',
                'amount' => $bonusAmount,
                'balance_before' => $newBalance,
                'balance_after' => $newBalance + $bonusAmount,
                'description' => 'Deposit Bonus ' . $bonusPercent . '% (Tier: ' . ($bonusTier['tier_type'] ?? 'Default') . ')',
                'status' => 'completed'
            ]);
        }
    }
    
    dbCommit();
    
    // Log success
    logActivity('user', $userId, 'deposit_completed', "UPI deposit of ₹{$amount} credited. UTR: {$utr}");
    
    jsonSuccess('Payment processed successfully', [
        'payment_ref' => $payment['payment_ref'],
        'amount' => $amount,
        'new_balance' => $newBalance,
        'user_id' => $userId
    ]);
    
} catch (Exception $e) {
    dbRollback();
    error_log("Payment webhook error: " . $e->getMessage());
    jsonError('Failed to process payment: ' . $e->getMessage(), 500);
}
