<?php
/**
 * Midtrans Utility Functions
 * 
 * This file contains helper functions for Midtrans integration.
 */

// Include the Midtrans configuration with absolute path
require_once __DIR__ . '/../midtrans_config.php';

// Function to log Midtrans API calls
function logMidtransApi($message, $data = null) {
    $log = date('Y-m-d H:i:s') . ' - ' . $message;
    if ($data !== null) {
        $log .= ' - ' . json_encode($data);
    }
    $log .= "\n";
    file_put_contents(__DIR__ . '/midtrans_api.log', $log, FILE_APPEND);
}

/**
 * Creates a Snap token for Midtrans payment
 * 
 * @param array $orderData Order data including items, customer details, etc.
 * @return string|null The Snap token if successful, null otherwise
 */
function createMidtransSnapToken($orderData) {
    logMidtransApi("Creating Snap token - Order ID: {$orderData['order_id']}");
    
    try {
        $curl = curl_init();
        
        // Prepare minimalistic transaction data for Midtrans
        $data = array(
            'transaction_details' => array(
                'order_id' => $orderData['order_id'],
                'gross_amount' => (int)$orderData['gross_amount']
            ),
            'callbacks' => array(
                'finish' => 'https://1v7xfrw5-443.asse.devtunnels.ms/web-baso/public/payment_success.php?order_id=' . $orderData['order_id'],
                'unfinish' => 'https://1v7xfrw5-443.asse.devtunnels.ms/web-baso/dashboard.php?order_id=' . $orderData['order_id'],
                'error' => 'https://1v7xfrw5-443.asse.devtunnels.ms/web-baso/dashboard.php?order_id=' . $orderData['order_id']
            )
        );
        
        // Add customer details if available
        if (isset($orderData['customer_name']) || isset($orderData['customer_email']) || isset($orderData['customer_phone'])) {
            $data['customer_details'] = array();
            
            if (isset($orderData['customer_name']))
                $data['customer_details']['first_name'] = $orderData['customer_name'];
                
            if (isset($orderData['customer_email']))
                $data['customer_details']['email'] = $orderData['customer_email'];
                
            if (isset($orderData['customer_phone']))
                $data['customer_details']['phone'] = $orderData['customer_phone'];
                
            if (isset($orderData['customer_address']))
                $data['customer_details']['billing_address']['address'] = $orderData['customer_address'];
        }
        
        // Add item_details if available
        if (isset($orderData['items']) && is_array($orderData['items'])) {
            $data['item_details'] = $orderData['items'];
        }
        
        $encoded_data = json_encode($data);
        logMidtransApi("Request data", $data);
        
        // FIXED: Set correct URL for Snap API
        $url = MIDTRANS_IS_SANDBOX 
            ? 'https://app.sandbox.midtrans.com/snap/v1/transactions'
            : 'https://app.midtrans.com/snap/v1/transactions';
        
        // Encode server key for auth
        $server_key = MIDTRANS_SERVER_KEY;
        $auth = base64_encode($server_key . ':');
        
        logMidtransApi("Using URL", $url);
        logMidtransApi("Auth header", "Basic " . substr($auth, 0, 10) . '...');
        
        // Set cURL options
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $encoded_data,
            CURLOPT_HTTPHEADER => array(
                "accept: application/json",
                "authorization: Basic " . $auth,
                "content-type: application/json"
            ),
            CURLOPT_VERBOSE => true,
            CURLOPT_STDERR => fopen(__DIR__ . '/curl_errors.log', 'a+')
        ));
        
        $response = curl_exec($curl);
        $err = curl_error($curl);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        
        curl_close($curl);
        
        if ($err) {
            logMidtransApi("cURL Error", $err);
            return null;
        } else {
            logMidtransApi("Response (HTTP $http_code)", $response);
            $response_array = json_decode($response, true);
            
            // Dump raw response for debugging
            file_put_contents(__DIR__ . '/midtrans_response_raw.txt', $response);
            
            if (isset($response_array['token'])) {
                logMidtransApi("Snap token created successfully", $response_array['token']);
                return $response_array['token'];
            } else {
                logMidtransApi("Failed to create Snap token", $response_array);
                return null;
            }
        }
    } catch (Exception $e) {
        logMidtransApi("Exception", $e->getMessage());
        logMidtransApi("Exception trace", $e->getTraceAsString());
        return null;
    }
}

/**
 * Check transaction status
 * 
 * @param string $order_id The order ID
 * @return array|null The transaction status if successful, null otherwise
 */
function checkMidtransTransaction($order_id) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => MIDTRANS_BASE_URL . "/v2/" . $order_id . "/status",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "accept: application/json",
            "authorization: Basic " . base64_encode(MIDTRANS_SERVER_KEY . ':'),
            "content-type: application/json"
        )
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return null;
    } else {
        return json_decode($response, true);
    }
} 