<?php
require_once __DIR__ . '/../includes/functions.php';

// Security: only allow requests with the correct secret
if (($_POST['secret'] ?? '') !== CRON_SECRET) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

$userId = $_POST['merchant_id'] ?? '';
$foundAmount = floatval($_POST['amount'] ?? 0);
$txnId = $_POST['transaction_id'] ?? '';
$utr = $_POST['utr'] ?? '';
$senderName = $_POST['sender_name'] ?? '';
$paymentTimestamp = intval($_POST['payment_timestamp'] ?? time());
$now = time();

if (!$userId || $foundAmount <= 0) {
    http_response_code(400);
    echo 'Invalid payload';
    exit;
}

$user = getUserById($userId);
if (!$user) {
    http_response_code(404);
    echo 'User not found';
    exit;
}

// -----------------------------------------------
// 1. Check pending ORDERS
// -----------------------------------------------
$incomingOrderId = $_POST['order_id'] ?? '';

if ($incomingOrderId) {
    if (strpos($incomingOrderId, 'LINK_') === 0) {
        // Handle Payment Link
        $slug = substr($incomingOrderId, 5);
        $cleanSlug = str_replace(['_', '-'], '', $slug);
        $stmt = getDB()->prepare("SELECT * FROM payment_links WHERE user_id = ? AND REPLACE(REPLACE(slug, '_', ''), '-', '') = ? AND status = 'pending' AND expires_at > ?");
        $stmt->execute([$userId, $cleanSlug, $now]);
        $link = $stmt->fetch();
        
        if ($link) {
            $expectedAmount = $link['amount'];
            if ($foundAmount >= $expectedAmount - 0.01) {
                if (!empty($txnId)) {
                    $dsStmt = getDB()->prepare("SELECT order_id FROM orders WHERE transaction_id = ? AND status = 'success'");
                    $dsStmt->execute([$txnId]);
                    if ($dsStmt->fetch()) {
                        echo json_encode(['status' => 'pending', 'message' => 'Double spend prevented.']);
                        exit;
                    }
                }
                
                updatePaymentLink($link['slug'], 'paid');
                $dummyOrderId = generateOrderId();
                saveOrder([
                    'order_id' => $dummyOrderId,
                    'type' => 'link_' . $link['slug'],
                    'user_id' => $userId,
                    'upi_id' => $user['fampay_upi_id'],
                    'amount' => $link['amount'],
                    'payable_amount' => $foundAmount,
                    'status' => 'success',
                    'transaction_id' => $txnId,
                    'utr' => $utr,
                    'sender_name' => $senderName,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_at_timestamp' => time(),
                    'expires_at_timestamp' => 2147483647,
                    'payment_time_ist' => date('d-m-Y H:i:s', $paymentTimestamp ?: time())
                ]);
                fireWebhook($dummyOrderId);
                $user['total_success'] = ($user['total_success'] ?? 0) + 1;
                $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $link['amount'];
                saveUser($user);
                addSystemLog('API', "Payment Link {$link['slug']} fulfilled via Purpose ID for {$userId} (₹{$foundAmount}).");
                
                echo json_encode(['status' => 'success', 'type' => 'payment_link', 'order_id' => $dummyOrderId]);
                exit;
            }
        }
    } else {
        // Handle API Order
        $cleanIncomingOrderId = str_replace(['_', '-'], '', $incomingOrderId);
        $stmt = getDB()->prepare("SELECT * FROM orders WHERE user_id = ? AND REPLACE(REPLACE(order_id, '_', ''), '-', '') = ? AND status = 'pending' AND expires_at_timestamp > ?");
        $stmt->execute([$userId, $cleanIncomingOrderId, $now]);
        $order = $stmt->fetch();
        
        if ($order) {
            $expectedAmount = $order['amount'];
            if ($foundAmount >= $expectedAmount - 0.01) {
                if (!empty($txnId)) {
                    $dsStmt = getDB()->prepare("SELECT order_id FROM orders WHERE transaction_id = ? AND status = 'success' AND order_id != ?");
                    $dsStmt->execute([$txnId, $order['order_id']]);
                    if ($dsStmt->fetch()) {
                        echo json_encode(['status' => 'pending', 'message' => 'Double spend prevented.']);
                        exit;
                    }
                }
                
                updateOrder($order['order_id'], [
                    'status' => 'success',
                    'transaction_id' => $txnId,
                    'utr' => $utr,
                    'sender_name' => $senderName,
                    'payment_time_ist' => date('d-m-Y H:i:s', $paymentTimestamp ?: time())
                ]);
                fireWebhook($order['order_id']);
                $user['total_success'] = ($user['total_success'] ?? 0) + 1;
                $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $order['amount'];
                saveUser($user);
                addSystemLog('API', "Order {$order['order_id']} fulfilled via Purpose ID for {$userId} (₹{$foundAmount}).");
                
                echo json_encode(['status' => 'success', 'type' => 'order', 'order_id' => $order['order_id']]);
                exit;
            }
        }
    }
}

// -----------------------------------------------
// Fallback: If no order_id was found in the Purpose note (e.g. manual payment),
// fallback to the old amount-matching logic.
// -----------------------------------------------
$stmt = getDB()->prepare("SELECT * FROM orders WHERE user_id = ? AND status = 'pending' AND expires_at_timestamp > ? ORDER BY created_at_timestamp ASC");
$stmt->execute([$userId, $now]);
$pendingOrders = $stmt->fetchAll();

foreach ($pendingOrders as $order) {
    $expectedAmount = $order['payable_amount'] ?? $order['amount'];
    if (abs($foundAmount - $expectedAmount) < 0.01) {
        if (!empty($txnId)) {
            $dsStmt = getDB()->prepare("SELECT order_id FROM orders WHERE transaction_id = ? AND status = 'success' AND order_id != ?");
            $dsStmt->execute([$txnId, $order['order_id']]);
            if ($dsStmt->fetch()) continue; // Double spend protection
        }
        
        updateOrder($order['order_id'], [
            'status' => 'success',
            'transaction_id' => $txnId,
            'utr' => $utr,
            'sender_name' => $senderName,
            'payment_time_ist' => date('d-m-Y H:i:s', $paymentTimestamp ?: time())
        ]);
        fireWebhook($order['order_id']);
        $user['total_success'] = ($user['total_success'] ?? 0) + 1;
        $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $order['amount'];
        saveUser($user);
        addSystemLog('API', "Order {$order['order_id']} fulfilled via fallback amount for {$userId} (₹{$foundAmount}).");
        
        echo json_encode(['status' => 'success', 'type' => 'order', 'order_id' => $order['order_id']]);
        exit;
    }
}

$stmt = getDB()->prepare("SELECT * FROM payment_links WHERE user_id = ? AND status = 'pending' AND expires_at > ? ORDER BY created_at ASC");
$stmt->execute([$userId, $now]);
$pendingLinks = $stmt->fetchAll();

foreach ($pendingLinks as $link) {
    $expectedAmount = !empty((float)($link['payable_amount'] ?? 0)) ? $link['payable_amount'] : $link['amount'];
    if (abs($foundAmount - $expectedAmount) < 0.01) {
        if (!empty($txnId)) {
            $dsStmt = getDB()->prepare("SELECT order_id FROM orders WHERE transaction_id = ? AND status = 'success'");
            $dsStmt->execute([$txnId]);
            if ($dsStmt->fetch()) continue;
        }
        
        updatePaymentLink($link['slug'], 'paid');
                $dummyOrderId = generateOrderId();
        saveOrder([
            'order_id' => $dummyOrderId,
            'type' => 'link_' . $link['slug'],
            'user_id' => $userId,
            'upi_id' => $user['fampay_upi_id'],
            'amount' => $link['amount'],
            'payable_amount' => $foundAmount,
            'status' => 'success',
            'transaction_id' => $txnId,
            'utr' => $utr,
            'sender_name' => $senderName,
            'created_at' => date('Y-m-d H:i:s'),
            'created_at_timestamp' => time(),
            'expires_at_timestamp' => 2147483647,
            'payment_time_ist' => date('d-m-Y H:i:s', $paymentTimestamp ?: time())
        ]);
        fireWebhook($dummyOrderId);
        $user['total_success'] = ($user['total_success'] ?? 0) + 1;
        $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $link['amount'];
        saveUser($user);
        addSystemLog('API', "Payment Link {$link['slug']} fulfilled via fallback amount for {$userId} (₹{$foundAmount}).");
        
        echo json_encode(['status' => 'success', 'type' => 'payment_link', 'order_id' => $dummyOrderId]);
        exit;
    }
}

echo json_encode(['status' => 'pending', 'message' => 'No matching order found for amount ' . $foundAmount]);
