<?php
session_start();

// Check CSRF token for security
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("CSRF token mismatch");
}

// Include the database connection
require_once('../../database/config.php');  // Adjust the path as needed

// Retrieve form data from the POST request
$encrypted_data = $_POST['encrypted_data'];  // Retrieve the encrypted data from the form

// Decode the base64 encoded data
$decoded_data = base64_decode($encrypted_data);

// Split the decoded data into individual parts
$data_parts = explode(',', $decoded_data);

// Ensure we have all the necessary data
if (count($data_parts) !== 6) {
    die('Error: Missing or incorrect data.');
}

// Extract individual data values
$user = $data_parts[0];
$id = $data_parts[1];
$amount = $data_parts[2];
$plan_name = $data_parts[3];
$txn_limit = $data_parts[4];
$subscription_date = $data_parts[5];

// Generate an order ID based on the current time
$orderid = 'SUB' . date('YmdHis');
$status = "Inactive";  // Default status

// Get the domain dynamically (current server domain)
$domain = $_SERVER['HTTP_HOST'];  // This will give you the current domain

$api_url = "https://$domain/api/create-order.php";  // Construct the full API URL

$redirect_url = "https://$domain/partner/function/subscription-confirmation.php"; 


// Fetch the API key from the loginusers table for the mainadmin user
try {
    $stmt = $conn->prepare("SELECT api_key FROM loginusers WHERE usertype = 'mainadmin' LIMIT 1");
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        $api_key = $result['api_key'];
    } else {
        die("Error: API key not found for mainadmin user.");
    }
} catch (PDOException $e) {
    die('Error: ' . $e->getMessage());
}

// Prepare data for API request
$data = [
    'api_key' => $api_key, // Replace with your actual API key
    'orderid' => $orderid,
    'amount' => $amount,
    'customer_name' => $user,
    'redirect_url' => $redirect_url,  // Replace with actual redirect URL
    'merchant_name' => 'Paytm',
];

// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

// Execute cURL request
$response = curl_exec($ch);
//echo $response;
// Check for cURL errors
if ($response === false) {
    die('Error: ' . curl_error($ch));
}

// Parse the response (assuming it's a JSON response from the API)
$response_data = json_decode($response, true);

// Handle the API response
if ($response_data['status'] === 'SUCCESS') {
    // Save data into the database
    try {
        // Prepare the insert statement using PDO with placeholders
        $stmt = $conn->prepare("INSERT INTO subscriptions (orderid, user, user_id, amount, plans_name, txn_limit, subscription_date, status) 
                                VALUES (:orderid, :user, :id, :amount, :plan_name, :txn_limit, :subscription_date, :status)");

        // Bind parameters using bindParam
        $stmt->bindParam(':orderid', $orderid);
        $stmt->bindParam(':user', $user);
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':amount', $amount);
        $stmt->bindParam(':plan_name', $plan_name);
        $stmt->bindParam(':txn_limit', $txn_limit);
        $stmt->bindParam(':subscription_date', $subscription_date);
        $stmt->bindParam(':status', $status);

        // Execute the query
        if ($stmt->execute()) {
            // Redirect to the payment link
            header("Location: " . $response_data['payment_link']);
            exit;
        } else {
            die("Error: Failed to insert data into the database");
        }
    } catch (PDOException $e) {
        // Handle any database-related errors
        die('Error: ' . $e->getMessage());
    }
} else {
    // Display error if the API response status is not 'SUCCESS'
    $_SESSION['error_message'] = 'Error: ' . $response_data['message'];
    header("Location: https://$domain/portallogin/subscription.php");
    exit;
}

// Close cURL
curl_close($ch);
?>
