<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require('razorpay-php/Razorpay.php');
use Razorpay\Api\Api;

include "db.php";

/* CHECK SESSION ORDER */
if (!isset($_SESSION['current_order_id']) || !isset($_SESSION['order_amount'])) {
    die("Order session missing!");
}

$order_id = $_SESSION['current_order_id'];
$amount = $_SESSION['order_amount']; // rupees

/* RAZORPAY KEYS */
$keyId = "rzp_test_RpUMYUDg3gBSOb";
$keySecret = "1239XYUaUCuHKUfDwdiU14Sr";

/* CREATE API OBJECT */
$api = new Api($keyId, $keySecret);

/* CREATE RAZORPAY ORDER */
$razorpayOrder = $api->order->create([
    "receipt" => "order_rcptid_" . $order_id,
    "amount" => $amount * 100,  // in paise
    "currency" => "INR",
    "payment_capture" => 1
]);

$razorpay_order_id = $razorpayOrder['id'];

/* SAVE razorpay order id in DATABASE */
$update = $pdo->prepare("UPDATE orders SET razorpay_order_id=? WHERE id=?");
$update->execute([$razorpay_order_id, $order_id]);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Processing Payment...</title>
</head>
<body>

<h2 style="text-align:center;">Redirecting to Secure Payment...</h2>

<form action="verify_payment.php" method="POST" name="razorpay-form">
    <script src="https://checkout.razorpay.com/v1/checkout.js"
        data-key="<?php echo $keyId; ?>"
        data-amount="<?php echo $amount * 100; ?>"
        data-currency="INR"
        data-order_id="<?php echo $razorpay_order_id; ?>"
        data-buttontext="Pay Now"
        data-name="Lalita Varahi Foods"
        data-description="Order #<?php echo $order_id; ?>"
        data-theme.color="#002344">
    </script>
    <input type="hidden" name="hidden">
</form>

<script>
// Auto trigger Razorpay popup
document.querySelector(".razorpay-payment-button").click();
</script>

</body>
</html>
