<?php

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

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

// POST request check
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'FAILED',
        'message' => 'Please use POST method.'
    ]);
    exit;
}

// Check for required parameters
if (isset($_POST['api_key']) && !empty($_POST['api_key']) && isset($_POST['orderid']) && !empty($_POST['orderid'])) {

    $api_key = $_POST['api_key'];
    $orderid = $_POST['orderid'];

    // Validate API Key
    $api_key_check = $conn->prepare("SELECT count(*) FROM loginusers WHERE api_key = ?");
    $api_key_check->execute([$api_key]);
    $api_key_valid = $api_key_check->fetchColumn();

    if (!$api_key_valid) {
        echo json_encode([
            'status' => 'FAILED',
            'message' => 'Invalid API Key'
        ]);
        exit;
    }

    // Check if order exists in create_orders table
    $stmt = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
    $stmt->execute([$orderid]);
    $order_data = $stmt->fetch();

    if ($order_data) {
        // Check txn_status and return appropriate response
        $txn_status = strtolower(trim($order_data['txn_status']));

        if ($txn_status == 'success') {
            // If txn_status is success, return Success response
            echo json_encode([
                'status' => 'SUCCESS',
                'message' => 'Transaction successfully processed',
                'data' => [
                    'txn_id' => $order_data['transactions_id'],
                    'orderid' => $order_data['orderid'],
                    'txn_status' => $order_data['txn_status'],
                    'utr_number' => $order_data['utr_number'],
                    'amount' => $order_data['amount'],
                    'received_from' => $order_data['received_from']
                ]
            ]);
        } elseif ($txn_status == 'pending') {
            // If txn_status is pending, return Pending response
            echo json_encode([
                'status' => 'Pending',
                'message' => 'Transaction Waiting For Payment',
                'data' => [
                    'api_key' => $api_key,  // Retaining api_key
                    'orderid' => $order_data['orderid'],
                    'order_status' => $order_data['status'],
                    'txn_status' => $order_data['txn_status'],
                    'utr_number' => $order_data['utr_number'],
                    'amount' => $order_data['amount'],
                    'received_from' => $order_data['received_from']
                ]
            ]);
        } elseif ($txn_status == 'failed') {
            // If txn_status is failed, return Failed response
            echo json_encode([
                'status' => 'Failed',
                'message' => 'Transaction Failed',
                'data' => [
                    'orderid' => $order_data['orderid'],
                    'txn_status' => $order_data['txn_status'],
                    'utr_number' => $order_data['utr_number'],
                    'amount' => $order_data['amount'],
                    'received_from' => $order_data['received_from']
                ]
            ]);
        } else {
            // If txn_status is neither success, pending, nor failed, return an error or other message
            echo json_encode([
                'status' => 'Error',
                'message' => 'Transaction status is not recognized'
            ]);
        }
    } else {
        // Order not found
        echo json_encode([
            'status' => 'Error',
            'message' => 'Order not found'
        ]);
    }

} else {
    if (empty($_POST['api_key'])) {
        echo json_encode([
            'status' => 'FAILED',
            'message' => 'Missing api_key parameter'
        ]);
    } elseif (empty($_POST['orderid'])) {
        echo json_encode([
            'status' => 'FAILED',
            'message' => 'Missing orderid parameter'
        ]);
    } else {
        echo json_encode([
            'status' => 'FAILED',
            'message' => 'Missing api_key or orderid parameter'
        ]);
    }
}
?>