<?php
date_default_timezone_set('Asia/Kolkata');

// ini_set('display_errors', 1);
// error_reporting(E_ALL);

// 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'])) {

// Get the required parameters
$api_key = $_POST['api_key'];
$orderid = $_POST['orderid'];
$amount = $_POST['amount'];
$customer_name = $_POST['customer_name'];
$redirect_url = $_POST['redirect_url'];

// Get optional parameters (merchant_name)
$merchant_name = isset($_POST['merchant_name']) ? $_POST['merchant_name'] : null;

// Validate orderid format: should start with TXN followed by numbers
// if (!preg_match('/^TXN\d+$/', $orderid)) {
// $res = [
// "status" => "FAILED",
// "message" => "Invalid orderid format. It should start with 'TXN' followed by numbers. TXN20250111175941"
// ];
// echo json_encode($res);
// exit;
// }

// Check if the orderid already exists in the create_orders table
$check_orderid_query = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
$check_orderid_query->bindParam(1, $orderid, PDO::PARAM_STR);
$check_orderid_query->execute();

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->bindParam(1, $api_key, PDO::PARAM_STR);
$api_key_data_query->execute();
$api_key_data = $api_key_data_query->fetch();

if ($api_key_data) {
// Get user_id and other subscription details
$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->bindParam(1, $new_transactions_limit, PDO::PARAM_INT);
$update_transactions_limit_query->bindParam(2, $api_key, PDO::PARAM_STR);
$update_transactions_limit_query->execute();

// Handle merchant logic
if ($merchant_name) {
// Fetch merchant data from the add_merchant table based on the merchant name and user
$merchant_data_query = $conn->prepare("SELECT * FROM add_merchant WHERE merchant_name = ? AND user = ?");
$merchant_data_query->bindParam(1, $merchant_name, PDO::PARAM_STR);
$merchant_data_query->bindParam(2, $user, PDO::PARAM_STR); // Using the username to filter the merchant
$merchant_data_query->execute();
$merchant_data = $merchant_data_query->fetch();

if ($merchant_data) {
// Fetch both merchant_name and upi_id
$merchant_name = $merchant_data['merchant_name'];
$upi_id = $merchant_data['upi_id'];

if ($merchant_data['status'] == 'Active') {
// Generate transaction reference number
$transaction_ref_no = 'REF' . rand(100000, 999999);

// Prepare the data for the token
$data = [
'status' => 'PENDING',  // Initial transaction status
'orderid' => $orderid,  // Order ID
'amount' => $amount,  // Payment amount
'customer_name' => $customer_name,  // Customer name
'merchant_name' => $merchant_name,  // Merchant name
'upi_id' => $upi_id,  // UPI ID
'txn_status' => 'PENDING',  // Transaction status (pending at first)
'csrf' => bin2hex(random_bytes(16)),  // CSRF token for security (random)
'timestamp' => time(),  // Current timestamp
'expiration_time' => time() + 10 * 60 // Token expiration time (5 minutes from now)
];

// JSON encode the data
$json_data = json_encode($data);

// Generate a short 32-bit token by using a hash (SHA256 truncated)
$short_token = substr(hash('sha256', $json_data), 0, 32); // Truncate the hash to 32 characters

// Get the current domain
$domain = $_SERVER['HTTP_HOST']; // Dynamically fetch the domain name

// Generate the payment link with the short token
$payment_link = "https://$domain/api/payment.php?token=" . $short_token;

// Insert the order into the create_orders table, including the token and expiration time
$status = 'SUCCESS';
$txn_status = 'PENDING';  // Pending transaction status
$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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insert_order_query->bindParam(1, $orderid, PDO::PARAM_STR);
$insert_order_query->bindParam(2, $amount, PDO::PARAM_STR);
$insert_order_query->bindParam(3, $customer_name, PDO::PARAM_STR);
$insert_order_query->bindParam(4, $merchant_name, PDO::PARAM_STR);
$insert_order_query->bindParam(5, $upi_id, PDO::PARAM_STR);
$insert_order_query->bindParam(6, $status, PDO::PARAM_STR);
$insert_order_query->bindParam(7, $txn_status, PDO::PARAM_STR);
$insert_order_query->bindParam(8, $redirect_url, PDO::PARAM_STR);
$insert_order_query->bindParam(9, $user_id, PDO::PARAM_INT);
$insert_order_query->bindParam(10, $user, PDO::PARAM_STR);
$insert_order_query->bindParam(11, $date, PDO::PARAM_STR);
$insert_order_query->bindParam(12, $short_token, PDO::PARAM_STR);  // Saving the token
$insert_order_query->bindParam(13, $data['expiration_time'], PDO::PARAM_INT); // Saving the expiration time
$insert_order_query->execute();

// Check if the order was successfully inserted
if ($insert_order_query->rowCount() > 0) {
$res = [
"status" => "SUCCESS",
"message" => "Transaction Processed successfully",
"orderid" => $orderid,
"amount" => $amount,
"customer_name" => $customer_name,
"txn_status" => 'PENDING',
"qr_code" => 'https://qr-generator.developer-dhanyainfotech.workers.dev/?upi_id='.$upi_id.'&customer_name=UPI&amount='.$amount.'&orderid='.$orderid.'',
"payment_link" => $payment_link,
];
} else {
$res = [
"status" => "FAILED",
"message" => "Failed to Save the Order"
];
}
} else {
$res = [
"status" => "FAILED",
"message" => "Merchant is Not Active"
];
}
} else {
$res = [
"status" => "FAILED",
"message" => "Merchant Not Found"
];
}
} else {
// No merchant provided, use an active merchant from the add_merchant table based on the user
$active_merchant_query = $conn->prepare("SELECT * FROM add_merchant WHERE status = 'Active' AND user = ? LIMIT 1");
$active_merchant_query->bindParam(1, $user, PDO::PARAM_STR); // Using the username to filter the active merchant
$active_merchant_query->execute();
$active_merchant_data = $active_merchant_query->fetch();

if ($active_merchant_data) {
// Fetch both merchant_name and upi_id for the active merchant
$merchant_name = $active_merchant_data['merchant_name'];
$upi_id = $active_merchant_data['upi_id'];


// Generate transaction reference number
$transaction_ref_no = 'REF' . rand(100000, 999999);

// Prepare the data for the token
$data = [
'status' => 'PENDING',  // Initial transaction status
'orderid' => $orderid,  // Order ID
'amount' => $amount,  // Payment amount
'customer_name' => $customer_name,  // Customer name
'merchant_name' => $merchant_name,  // Merchant name
'upi_id' => $upi_id,  // UPI ID
'txn_status' => 'PENDING',  // Transaction status (pending at first)
'csrf' => bin2hex(random_bytes(16)),  // CSRF token for security (random)
'timestamp' => time(),  // Current timestamp
'expiration_time' => time() + 10 * 60 // Token expiration time (5 minutes from now)
];

// JSON encode the data
$json_data = json_encode($data);

// Generate a short 32-bit token by using a hash (SHA256 truncated)
$short_token = substr(hash('sha256', $json_data), 0, 32); // Truncate the hash to 32 characters

// Get the current domain
$domain = $_SERVER['HTTP_HOST']; // Dynamically fetch the domain name

// Generate the payment link with the short token
$payment_link = "https://$domain/api/payment.php?token=" . $short_token;


// Insert the order with the active merchant's details
$status = 'SUCCESS';
$txn_status = 'PENDING'; // Pending transaction status
$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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insert_order_query->bindParam(1, $orderid, PDO::PARAM_STR);
$insert_order_query->bindParam(2, $amount, PDO::PARAM_STR);
$insert_order_query->bindParam(3, $customer_name, PDO::PARAM_STR);
$insert_order_query->bindParam(4, $merchant_name, PDO::PARAM_STR);
$insert_order_query->bindParam(5, $upi_id, PDO::PARAM_STR);
$insert_order_query->bindParam(6, $status, PDO::PARAM_STR);
$insert_order_query->bindParam(7, $txn_status, PDO::PARAM_STR);
$insert_order_query->bindParam(8, $redirect_url, PDO::PARAM_STR);
$insert_order_query->bindParam(9, $user_id, PDO::PARAM_INT);
$insert_order_query->bindParam(10, $user, PDO::PARAM_STR);
$insert_order_query->bindParam(11, $date, PDO::PARAM_STR);
$insert_order_query->bindParam(12, $short_token, PDO::PARAM_STR);  // Saving the token
$insert_order_query->bindParam(13, $data['expiration_time'], PDO::PARAM_INT); // Saving the expiration time
$insert_order_query->execute();

// Check if the order was successfully inserted
if ($insert_order_query->rowCount() > 0) {
$res = [
"status" => "SUCCESS",
"message" => "Transaction processed successfully",
"orderid" => $orderid,
"amount" => $amount,
"customer_name" => $customer_name,
"txn_status" => 'PENDING',
"qr_code" => 'https://qr-generator.developer-dhanyainfotech.workers.dev/?upi_id='.$upi_id.'&customer_name=UPI&amount='.$amount.'&orderid='.$orderid.'',
"payment_link" => $payment_link,
];
} else {
$res = [
"status" => "FAILED",
"message" => "Failed To save The Order"
];
}
} else {
$res = [
"status" => "FAILED",
"message" => "No Active Merchant Found"
];
}
}
}
} 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);
?>
