<?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']) &&
    isset($_POST['utr_number']) && !empty($_POST['utr_number'])) {

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

    // 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) {
        $txn_status = strtolower(trim($order_data['txn_status']));
        $order_amount = $order_data['amount'];
        $user_id = $order_data['user'];

        if ($txn_status == 'success') {
            // If already success, return success response
            echo json_encode([
                'status' => 'SUCCESS',
                'message' => 'Transaction already 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') {
            // For pending transactions, check with BharatPe API
            
            // Get merchant credentials
            $sql = "SELECT merchant_id, access_token FROM add_merchant WHERE user = ? AND merchant_name = 'Bharatpe'";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$user_id]);
            $merchantData = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$merchantData) {
                echo json_encode([
                    'status' => 'Error',
                    'message' => 'Merchant credentials not found'
                ]);
                exit;
            }

            $merchant_id = $merchantData['merchant_id'];
            $access_token = $merchantData['access_token'];

            // Call BharatPe API
            $apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/payment-status.php?merchant_id=$merchant_id&access_token=$access_token&bank_reference_no=$post_utr_number";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                echo json_encode([
                    'status' => 'Error', 
                    'message' => 'cURL Error: ' . curl_error($ch)
                ]);
                exit;
            }
            curl_close($ch);

            $apiResponse = json_decode($response, true);

            // Check API response
            if (!$apiResponse || !isset($apiResponse['status'])) {
                echo json_encode([
                    'status' => 'Pending',
                    'message' => 'Payment status could not be verified',
                    'data' => $order_data
                ]);
                exit;
            }

            if ($apiResponse['status'] == 'success') {
                // Verify UTR number matches with API response
                $api_utr_number = $apiResponse['bank_reference_no'] ?? '';
                if ($api_utr_number != $post_utr_number) {
                    echo json_encode([
                        'status' => 'Error',
                        'message' => 'UTR number mismatch with API response',
                        'api_utr' => $api_utr_number,
                        'post_utr' => $post_utr_number
                    ]);
                    exit;
                }

                // Verify amount matches
                $api_amount = $apiResponse['amount'] ?? 0;
                if ($api_amount != $order_amount) {
                    echo json_encode([
                        'status' => 'Error',
                        'message' => 'Amount mismatch',
                        'order_amount' => $order_amount,
                        'api_amount' => $api_amount
                    ]);
                    exit;
                }

                // Update transaction details
                $txn_id = $apiResponse['transaction_id'] ?? '';
                $received_from = $apiResponse['payer_handle'] ?? '';
                $payer_handle = $apiResponse['payer_handle'] ?? '';
                $payment_timestamp = $apiResponse['payment_timestamp'] ?? date('Y-m-d H:i:s');

                $updateQuery = "UPDATE create_orders SET 
                    transactions_id = ?, 
                    txn_status = 'SUCCESS', 
                    received_from = ?,
                    amount = ?,
                    utr_number = ?,
                    created_at = ?
                    WHERE orderid = ?";
                
                $stmt = $conn->prepare($updateQuery);
                $stmt->execute([
                    $txn_id,
                    $received_from,
                    $api_amount,
                    $api_utr_number,
                    $payment_timestamp,
                    $orderid
                ]);

                // Send Callback
                $callbackFile = __DIR__ . '/../partner/send_callback.php';
                if (file_exists($callbackFile)) {
                    require_once($callbackFile);
                    if (function_exists('sendCallback')) {
                        sendCallback($conn, $orderid, 'SUCCESS');
                    }
                }

                echo json_encode([
                    'status' => 'Success',
                    'message' => 'Transaction successfully processed',
                    'data' => [
                        'txn_id' => $txn_id,
                        'orderid' => $orderid,
                        'txn_status' => 'SUCCESS',
                        'utr_number' => $api_utr_number,
                        'amount' => $api_amount,
                        'received_from' => $received_from,
                        'payer_handle' => $payer_handle
                    ]
                ]);
            } else {
                // API returned non-success status
                echo json_encode([
                    'status' => 'Pending',
                    'message' => 'Transaction still pending',
                    'api_response' => $apiResponse
                ]);
            }
        } elseif ($txn_status == 'failed') {
            echo json_encode([
                'status' => 'Failed',
                'message' => 'Transaction Failed',
                'data' => $order_data
            ]);
        } else {
            echo json_encode([
                'status' => 'Error',
                'message' => 'Unknown transaction status'
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'Error',
            'message' => 'Order not found'
        ]);
    }
} else {
    $missing = [];
    if (empty($_POST['api_key'])) $missing[] = 'api_key';
    if (empty($_POST['orderid'])) $missing[] = 'orderid';
    if (empty($_POST['utr_number'])) $missing[] = 'utr_number';
    
    echo json_encode([
        'status' => 'FAILED',
        'message' => 'Missing parameters: ' . implode(', ', $missing)
    ]);
}
?>