<?php
/**
 * pay2inr Branded Order Creation
 * This creates orders that redirect to pay2inr hosted payment page
 * Instead of external RSPay page
 */

date_default_timezone_set('Asia/Kolkata');

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $res = [
        "status" => "FAILED",
        "message" => "Please use POST method to send x-www-form-urlencoded data."
    ];
    header('Content-Type: application/json');
    echo json_encode($res);
    exit;
}

require_once('../database/config.php');

// Check if required parameters are set
if (isset($_POST['api_key'], $_POST['orderid'], $_POST['amount'], $_POST['customer_name'], $_POST['redirect_url'])) {
    
    $api_key = $_POST['api_key'];
    $orderid = $_POST['orderid'];
    $amount = $_POST['amount'];
    $customer_name = $_POST['customer_name'];
    $redirect_url = $_POST['redirect_url'];
    $merchant_name = isset($_POST['merchant_name']) ? $_POST['merchant_name'] : 'RSPAY';
    
    // Check if orderid already exists
    $check_orderid_query = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
    $check_orderid_query->execute([$orderid]);
    
    if ($check_orderid_query->rowCount() > 0) {
        $res = [
            "status" => "FAILED",
            "message" => "Order ID already exists. Please use a different order ID."
        ];
        echo json_encode($res);
        exit;
    }
    
    // Fetch user data from loginusers table using api_key
    $api_key_data_query = $conn->prepare("SELECT * FROM loginusers WHERE api_key = ?");
    $api_key_data_query->execute([$api_key]);
    $api_key_data = $api_key_data_query->fetch();
    
    if ($api_key_data) {
        $user_id = $api_key_data['id'];
        $user = $api_key_data['username'];
        $subscription_date = $api_key_data['subscription_date'];
        $transactions_limit = $api_key_data['transactions_limit'];
        
        // Check if the plan has expired
        if (strtotime($subscription_date) < time()) {
            $res = [
                "status" => "FAILED",
                "message" => "Your plan has expired. Please renew your plan."
            ];
        }
        // Check if the transaction limit is available
        elseif ($transactions_limit <= 0) {
            $res = [
                "status" => "FAILED",
                "message" => "Your transaction limit has been exhausted."
            ];
        } else {
            // Decrease the transaction limit by 1
            $new_transactions_limit = $transactions_limit - 1;
            $update_transactions_limit_query = $conn->prepare("UPDATE loginusers SET transactions_limit = ? WHERE api_key = ?");
            $update_transactions_limit_query->execute([$new_transactions_limit, $api_key]);
            
            // Generate token for payment page
            $token = bin2hex(random_bytes(32));
            $expiration_time = time() + (15 * 60); // 15 minutes
            
            // Insert order into create_orders table
            $status = 'SUCCESS';
            $txn_status = 'PENDING';
            $date = date('Y-m-d H:i:s');
            
            $insert_order_query = $conn->prepare("
                INSERT INTO create_orders 
                (orderid, amount, customer_name, merchant_name, upi_id, status, txn_status, redirect_url, user_id, user, date, token, expiration_time, callback_sent, api_txn_id) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)
            ");
            
            $insert_order_query->execute([
                $orderid,
                $amount,
                $customer_name,
                $merchant_name,
                'N/A', // UPI ID not needed for RSPay
                $status,
                $txn_status,
                $redirect_url,
                $user_id,
                $user,
                $date,
                $token,
                $expiration_time,
                '' // api_txn_id
            ]);
            
            // Check if the order was successfully inserted
            if ($insert_order_query->rowCount() > 0) {
                // Get the current domain
                $domain = $_SERVER['HTTP_HOST'];
                
                // Generate pay2inr hosted payment link
                $payment_link = "https://$domain/api/payment.php?token=" . $token;
                
                $res = [
                    "status" => "SUCCESS",
                    "message" => "Transaction processed successfully",
                    "orderid" => $orderid,
                    "amount" => $amount,
                    "customer_name" => $customer_name,
                    "txn_status" => 'PENDING',
                    "payment_link" => $payment_link,
                    "token" => $token
                ];
            } else {
                $res = [
                    "status" => "FAILED",
                    "message" => "Failed to save the order"
                ];
            }
        }
    } else {
        $res = [
            "status" => "FAILED",
            "message" => "Invalid API Key"
        ];
    }
} else {
    $res = [
        "status" => "FAILED",
        "message" => "Missing or Invalid Parameters"
    ];
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($res);
?>
