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

// Include your database configuration file
require_once('../../database/config.php'); // Make sure this path is correct

// Check if $_POST contains 'order_id'
if (isset($_POST['order_id'])) {
    // Get the order_id from the POST request
    $order_id = $_POST['order_id'];
} else {
    echo "Order ID not received!";
    exit;
}

// Step 2: Check the subscriptions table to find the order status
$subscriptionQuery = $conn->prepare("SELECT * FROM subscriptions WHERE orderid = :orderid LIMIT 1");
$subscriptionQuery->bindParam(':orderid', $order_id, PDO::PARAM_STR);
$subscriptionQuery->execute();

// Fetch subscription data
$subscription = $subscriptionQuery->fetch(PDO::FETCH_ASSOC);

// Step 3: If the order exists and status is 'Inactive', proceed with API call
if ($subscription) {
    if ($subscription['status'] === 'Inactive') {

        $api_key = "76f732-3a9aa9-78578d-6c3a1f-8df507";

        $domain = $_SERVER['SERVER_NAME'];
        // Step 4: Set the API URL using the domain name
        $apiUrl = 'https://'.$domain.'/api/order-status.php'; // Dynamic domain URL

        // Prepare the data to send in the POST request (application/x-www-form-urlencoded)
        $data = [
            'api_key' => $api_key,
            'orderid' => $order_id, // Use the received orderid directly here
        ];

        // Initialize cURL session
        $ch = curl_init();

        // Set the URL for the API call
        curl_setopt($ch, CURLOPT_URL, $apiUrl);

        // Set cURL options for the POST request
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
        curl_setopt($ch, CURLOPT_POST, true);  // Indicate that it's a POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  // Attach data as a query string

        // Set the Content-Type to application/x-www-form-urlencoded
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded'
        ]);

        // Execute the cURL request and capture the response
        $response = curl_exec($ch);
        
        // Debugging step: Echo cURL response and check if it's valid
        if (curl_errno($ch)) {
            echo 'cURL Error: ' . curl_error($ch);
        } else {
            // Decode the API response
            $apiResponse = json_decode($response, true);

            // Check if txn_status is Success and api_txn_id is available
            if (isset($apiResponse['status']) && $apiResponse['status'] === 'SUCCESS') {
                $api_txn_id = $apiResponse['data']['txn_id'];
                $txn_status = $apiResponse['data']['txn_status'];
                $utr_number = $apiResponse['data']['utr_number']; // UTR number is available here
                $amount = $apiResponse['data']['amount'];

                // Step 5: Update subscriptions table with Active status
                // If api_txn_id is not available, we don't need to update it, but we can still mark the subscription as Active.
                $updateSubscription = $conn->prepare("UPDATE subscriptions SET status = 'Active' WHERE orderid = :orderid");
                $updateSubscription->bindParam(':orderid', $order_id, PDO::PARAM_STR);
                $updateSubscription->execute();

                // Optionally log the utr_number and amount
                //echo "Transaction Success: UTR Number: $utr_number, Amount: $amount<br>";

                // Step 6: Get user, txn_limit, and subscription_date from subscriptions table
                $userQuery = $conn->prepare("SELECT user, plans_name, amount, txn_limit, subscription_date FROM subscriptions WHERE orderid = :orderid LIMIT 1");
                $userQuery->bindParam(':orderid', $order_id, PDO::PARAM_STR);
                $userQuery->execute();
                $userData = $userQuery->fetch(PDO::FETCH_ASSOC);

                // Store the data for later display in HTML
                if ($userData) {
                    $user = $userData['user'];
                    $plans_name = $userData['plans_name'];
                    $txn_limit = $userData['txn_limit'];
                    $subscription_date = $userData['subscription_date'];

                    // Step 7: Update the loginusers table with subscription details
                    $updateLoginUser = $conn->prepare("UPDATE loginusers SET subscription_date = :subscription_date, transactions_limit = :transactions_limit WHERE username = :username");
                    $updateLoginUser->bindParam(':subscription_date', $subscription_date);
                    $updateLoginUser->bindParam(':transactions_limit', $txn_limit);
                    $updateLoginUser->bindParam(':username', $user);
                    $updateLoginUser->execute();

                    // Show subscription details in an invoice format
                    echo "<!DOCTYPE html>
                    <html lang='en'>
                    <head>
                        <meta charset='UTF-8'>
                        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                        <title>Subscription Invoice</title>
                        <style>
                            body {
                                font-family: Arial, sans-serif;
                                background-color: #f4f4f4;
                                margin: 0;
                                padding: 0;
                            }
                            .invoice-container {
                                width: 80%;
                                margin: 50px auto;
                                background: #fff;
                                padding: 20px;
                                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                            }
                            .invoice-header {
                                text-align: center;
                                border-bottom: 1px solid #ddd;
                                padding-bottom: 10px;
                            }
                            .invoice-header h1 {
                                margin: 0;
                                font-size: 24px;
                                color: #333;
                            }
                            .invoice-details {
                                margin-top: 20px;
                            }
                            .invoice-details table {
                                width: 100%;
                                border-collapse: collapse;
                            }
                            .invoice-details table td {
                                padding: 10px;
                                border: 1px solid #ddd;
                            }
                            .invoice-details table td:first-child {
                                font-weight: bold;
                                width: 30%;
                            }
                            .invoice-footer {
                                text-align: center;
                                margin-top: 20px;
                                padding-top: 10px;
                                border-top: 1px solid #ddd;
                            }
                            .invoice-footer button {
                                padding: 10px 20px;
                                margin: 0 10px;
                                font-size: 16px;
                                cursor: pointer;
                            }
                            .countdown {
                                font-size: 18px;
                                color: #333;
                                margin-top: 20px;
                            }
                        </style>
                    </head>
                    <body>
                        <div class='invoice-container'>
                            <div class='invoice-header'>
                                <h1>Subscription Invoice</h1>
                            </div>
                            <div class='invoice-details'>
                                <table>
                                    <tr>
                                        <td>Order ID</td>
                                        <td>$order_id</td>
                                    </tr>
                                    <tr>
                                        <td>Subscription Date</td>
                                        <td>$subscription_date</td>
                                    </tr>
                                    <tr>
                                        <td>Plan Name</td>
                                        <td>$plans_name</td>
                                    </tr>
                                    <tr>
                                        <td>Transaction Limit</td>
                                        <td>$txn_limit</td>
                                    </tr>
                                    <tr>
                                        <td>Transaction Status</td>
                                        <td>$txn_status</td>
                                    </tr>
                                    <tr>
                                        <td>UTR Number</td>
                                        <td>$utr_number</td>
                                    </tr>
                                    <tr>
                                        <td>Amount</td>
                                        <td>$amount</td>
                                    </tr>
                                </table>
                            </div>
                            <div class='invoice-footer'>
                                <button onclick='window.print()'>Print Invoice</button>
                                <button onclick='downloadInvoice()'>Download Invoice</button>
                                <div class='countdown'>Redirecting in <span id='countdown'>60</span> seconds...</div>
                            </div>
                        </div>
                        <script>
                            function downloadInvoice() {
                                // Implement download functionality here
                                alert('Download functionality to be implemented.');
                            }

                            // Countdown timer for redirection
                            let timeLeft = 60;
                            const countdownElement = document.getElementById('countdown');
                            const countdownInterval = setInterval(() => {
                                timeLeft--;
                                countdownElement.textContent = timeLeft;
                                if (timeLeft <= 0) {
                                    clearInterval(countdownInterval);
                                    window.location.href = 'https://fastpay.us.cc/partner/index.php';
                                }
                            }, 1000);
                        </script>
                    </body>
                    </html>";
                }
            } else {
                //echo "API response error: " . json_encode($apiResponse); // Debug API failure
            }
        }

        // Close the cURL session
        curl_close($ch);
    } else {
        // If the order status is already Active, just show a message and do nothing further.
        echo "<!DOCTYPE html>
        <html lang='en'>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Subscription Invoice</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                }
                .invoice-container {
                    width: 80%;
                    margin: 50px auto;
                    background: #fff;
                    padding: 20px;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                }
                .invoice-header {
                    text-align: center;
                    border-bottom: 1px solid #ddd;
                    padding-bottom: 10px;
                }
                .invoice-header h1 {
                    margin: 0;
                    font-size: 24px;
                    color: #333;
                }
                .invoice-details {
                    margin-top: 20px;
                }
                .invoice-details table {
                    width: 100%;
                    border-collapse: collapse;
                }
                .invoice-details table td {
                    padding: 10px;
                    border: 1px solid #ddd;
                }
                .invoice-details table td:first-child {
                    font-weight: bold;
                    width: 30%;
                }
                .invoice-footer {
                    text-align: center;
                    margin-top: 20px;
                    padding-top: 10px;
                    border-top: 1px solid #ddd;
                }
                .invoice-footer button {
                    padding: 10px 20px;
                    margin: 0 10px;
                    font-size: 16px;
                    cursor: pointer;
                }
                .countdown {
                    font-size: 18px;
                    color: #333;
                    margin-top: 20px;
                }
            </style>
        </head>
        <body>
            <div class='invoice-container'>
                <div class='invoice-header'>
                    <h1>Subscription Invoice</h1>
                </div>
                <div class='invoice-details'>
                    <p>Subscription is already Active.</p>
                </div>
                <div class='invoice-footer'>
                    <div class='countdown'>Redirecting in <span id='countdown'>60</span> seconds...</div>
                </div>
            </div>
            <script>
                // Countdown timer for redirection
                let timeLeft = 60;
                const countdownElement = document.getElementById('countdown');
                const countdownInterval = setInterval(() => {
                    timeLeft--;
                    countdownElement.textContent = timeLeft;
                    if (timeLeft <= 0) {
                        clearInterval(countdownInterval);
                        window.location.href = 'https://justpay.in.net/partner/index.php';
                    }
                }, 1000);
            </script>
            
        </body>
        </html>";
    }
} else {
    echo "Order not found.";
}
?>
