<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Only POST requests are allowed.");
}
csrfVerify();

$orderId = $_POST['order_id'] ?? '';

$order = getOrderById($orderId);
$link = getPaymentLinkBySlug($orderId);

if (!$order && !$link) {
    die("Order or Link not found.");
}

if ($order && $order['status'] === 'success') {
    die("Order is already paid.");
}
if ($link && $link['status'] === 'paid') {
    die("Payment Link is already paid.");
}

$userId = $order ? $order['user_id'] : $link['user_id'];
$user = getUserById($userId);

// Simulate a successful payment
if ($order) {
    updateOrder($order['order_id'], [
        'status' => 'success',
        'transaction_id' => 'SIMULATED_' . time(),
        'utr' => 'SIM' . rand(100000000, 999999999),
        'sender_name' => 'Aryan Simulator',
        'payment_time_ist' => date('d-m-Y H:i:s')
    ]);
    // Fire webhook so merchants can test their webhook endpoint
    fireWebhook($order['order_id']);
} else {
    updatePaymentLink($link['slug'], 'paid');
    $newOrderId = generateOrderId();
    saveOrder([
        'order_id' => $newOrderId,
        'type' => 'payment_link',
        'user_id' => $userId,
        'upi_id' => $user['fampay_upi_id'] ?? '',
        'amount' => $link['amount'],
        'payable_amount' => $link['amount'],
        'status' => 'success',
        'transaction_id' => 'SIMULATED_' . time(),
        'utr' => 'SIM' . rand(100000000, 999999999),
        'sender_name' => 'Aryan Simulator Link',
        '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')
    ]);
    // Fire webhook for payment link generated order
    fireWebhook($newOrderId);
}

// Update user stats
if ($user) {
    $user['total_success'] = ($user['total_success'] ?? 0) + 1;
    $amountToAdd = $order ? $order['payable_amount'] : $link['amount'];
    $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $amountToAdd;
    saveUser($user);
}

echo "Success! Order {$orderId} marked as PAID. Check your pay.php tab, it should automatically redirect to success now.";
