<?php
// Fix for CORS issues if accessed via AJAX from frontend
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

require_once('../../database/config.php'); // Your main DB config
require_once('config.php'); // RSPay config

// Check if user is logged in (optional, depending on flow)
// session_start();
// if(!isset($_SESSION['username'])){
//     echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
//     exit;
// }

// Check authentication
if (!isset($input['api_key'])) {
    echo json_encode(['status' => 'error', 'message' => 'API Key required']);
    exit;
}

$user_api_key = $input['api_key'];

// Verify API Key and get user
$stmt = $conn->prepare("SELECT * FROM add_merchant WHERE access_token = ? AND merchant_name = 'RSPay'");
$stmt->execute([$user_api_key]);
$merchant_user = $stmt->fetch();

if (!$merchant_user) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid API Key']);
    exit;
}

// User is authenticated
$requesting_user = $merchant_user['user'];

if($amount <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid amount']);
    exit;
}

// Generate unique order ID
$merchantOrderId =  time() . rand(1000, 9999);

// Prepare parameters for signature
$params = [
    'merchantId' => $rspay_merchant_id,
    'merchantOrderId' => $merchantOrderId,
    'amount' => $amount,
    'type' => 2, // Fixed at 2 for UPI/Pay-in as per doc
    'paymentCurrency' => 'INR', // Default INR
    'notifyUrl' => $callback_url,
    'userName' => $userName,
    'ext' => 'test', // Optional pass-through
    'redirectUrl' => $protocol . $domain . '/partner/success.php' // Redirect after payment
];

// Generate Signature
$sign = generateRspaySign($params, $rspay_key);

// Add signature to params
$params['sign'] = $sign;

// Call API
$response = callRspayApi('/apii/in/createOrder', $params);

// Log the request and response for debugging (Optional)
// file_put_contents('rspay_log.txt', date('Y-m-d H:i:s'). " REQ: " . json_encode($params) . "\n", FILE_APPEND);
// file_put_contents('rspay_log.txt', date('Y-m-d H:i:s'). " RES: " . json_encode($response) . "\n", FILE_APPEND);


// Handle Response
if(isset($response['status']) && $response['status'] == '200') {
    
    // Save order to your database (pending status)
    // You should create a table `deposits` or similar if not exists
    /*
    $stmt = $conn->prepare("INSERT INTO deposits (order_id, amount, status, created_at) VALUES (?, ?, 'pending', NOW())");
    $stmt->execute([$merchantOrderId, $amount]);
    */

    echo json_encode([
        'status' => 'success',
        'pay_url' => $response['data']['payUrl'], // The user needs to visit this URL to pay
        'order_id' => $merchantOrderId
    ]);

} else {
    echo json_encode([
        'status' => 'error', 
        'message' => isset($response['message']) ? $response['message'] : 'Unknown error'
    ]);
}
?>
