<?php
/**
 * API - Submit UTR Number for UPI Payment (Enhanced with Auto-Verification)
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';
require_once '../../includes/UpiVerifier.php';
require_once '../../includes/ApiAuth.php';

// Authenticate (session or token)
$user = ApiAuth::authenticate();
$userId = $user['id'];

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

$paymentRef = trim($input['payment_ref'] ?? '');
$utrNumber = trim($input['utr_number'] ?? '');

if (!$paymentRef || !$utrNumber) {
    jsonError('Payment reference and UTR number are required');
}

// Rate limit: max 5 UTR submissions per minute
if (!ApiAuth::rateLimit($userId, 'utr_submit', 5, 60)) {
    jsonError('Too many attempts. Please wait a minute before trying again.', 429);
}

// Log the attempt
ApiAuth::logApiActivity($userId, 'utr_submit', "UTR: {$utrNumber}, Ref: {$paymentRef}");

// Find the payment
$payment = dbFetch(
    "SELECT * FROM upi_payments WHERE payment_ref = :ref AND user_id = :uid AND status = 'pending'",
    ['ref' => $paymentRef, 'uid' => $userId]
);

if (!$payment) {
    jsonError('Payment not found or already processed');
}

// Auto-verify the deposit
$ipAddress = ApiAuth::getClientIp();
$deviceInfo = ApiAuth::getDeviceInfo();

$result = UpiVerifier::autoVerifyDeposit(
    $payment['id'],
    $utrNumber,
    $ipAddress,
    $deviceInfo
);

if ($result['success']) {
    // Get updated balance
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);
    $newBalance = ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0);
    
    jsonSuccess($result['message'], [
        'payment_ref' => $paymentRef,
        'utr_number' => $utrNumber,
        'amount' => $result['amount'],
        'bonus' => $result['bonus'],
        'new_balance' => $newBalance,
        'auto_verified' => true,
        'status' => 'approved'
    ]);
} else {
    jsonError($result['error']);
}
