<?php
/**
 * Midtrans Callback Handler
 *
 * This script handles payment notifications from Midtrans
 */

// Include required files
require_once __DIR__ . '/midtrans_config.php';
require_once __DIR__ . '/config/db_config.php';
require_once __DIR__ . '/models/Order.php';

// Set response header
header('Content-Type: application/json');

// Function for logging
function logCallback($message, $data = []) {
    $log = date('Y-m-d H:i:s') . ' - ' . $message;
    if (!empty($data)) {
        $log .= ' - ' . json_encode($data);
    }
    $log .= "\n";
    file_put_contents('midtrans_callback.log', $log, FILE_APPEND);
}

// Start logging
logCallback('Callback received');

// Get notification data
$notification = json_decode(file_get_contents('php://input'), true);
logCallback('Notification data', $notification);

$transaction = $notification['transaction_status'] ?? null;
$order_id = $notification['order_id'] ?? null;
$fraud = $notification['fraud_status'] ?? null;
$signing_key = MIDTRANS_SERVER_KEY;

// Verify the received data
if (empty($notification) || empty($transaction) || empty($order_id)) {
    logCallback('Invalid notification data');
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid notification data']);
    exit;
}

// Handle based on transaction status
try {
    // Load the order
    $order = new Order();
    $order_found = $order->getOrderByMidtransOrderId($order_id);
    
    if (!$order_found) {
        logCallback('Order not found', ['midtrans_order_id' => $order_id]);
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Order not found']);
        exit;
    }
    
    logCallback('Order found', ['order_id' => $order->order_id, 'order_code' => $order->order_code]);
    
    // Prepare transaction data
    $transaction_data = [
        'payment_type' => $notification['payment_type'] ?? 'unknown',
        'transaction_time' => $notification['transaction_time'] ?? date('Y-m-d H:i:s'),
        'amount' => $notification['gross_amount'] ?? $order->total_amount,
        'midtrans_transaction_id' => $notification['transaction_id'] ?? null,
        'midtrans_transaction_status' => $transaction,
        'midtrans_payment_type' => $notification['payment_type'] ?? null,
        'additional_info' => $notification
    ];
    
    // Record transaction
    $transaction_id = $order->recordTransaction($transaction_data);
    logCallback('Transaction recorded', ['transaction_id' => $transaction_id]);
    
    $success_url = null;
    
    if ($transaction == 'capture') {
        // For credit card transactions, check the fraud status
        if ($fraud == 'challenge') {
            // Mark order as pending/challenge
            $order->updateStatus('pending');
            $response = ['status' => 'success', 'message' => 'Transaction is challenged', 'order_id' => $order_id];
        } else if ($fraud == 'accept') {
            // Mark order as success
            $order->updateStatus('paid');
            $success_url = 'public/payment_success.php?order_id=' . $order_id;
            $response = ['status' => 'success', 'message' => 'Transaction is successful', 'order_id' => $order_id];
        }
    } else if ($transaction == 'settlement') {
        // Mark order as paid
        $order->updateStatus('paid');
        $success_url = 'public/payment_success.php?order_id=' . $order_id;
        $response = ['status' => 'success', 'message' => 'Transaction is settled', 'order_id' => $order_id];
    } else if ($transaction == 'pending') {
        // Mark order as pending
        $order->updateStatus('pending');
        $response = ['status' => 'pending', 'message' => 'Transaction is pending', 'order_id' => $order_id];
    } else if ($transaction == 'deny') {
        // Mark order as failed
        $order->updateStatus('cancelled');
        $response = ['status' => 'failed', 'message' => 'Transaction is denied', 'order_id' => $order_id];
    } else if ($transaction == 'expire') {
        // Mark order as expired
        $order->updateStatus('cancelled');
        $response = ['status' => 'failed', 'message' => 'Transaction is expired', 'order_id' => $order_id];
    } else if ($transaction == 'cancel') {
        // Mark order as failed
        $order->updateStatus('cancelled');
        $response = ['status' => 'failed', 'message' => 'Transaction is canceled', 'order_id' => $order_id];
    } else {
        $response = ['status' => 'error', 'message' => 'Unknown transaction status', 'order_id' => $order_id];
    }
    
    // If we have a success URL, store it in the response
    if ($success_url) {
        $response['success_url'] = $success_url;
    }
    
    // Return a success response to Midtrans
    logCallback('Response', $response);
    http_response_code(200);
    echo json_encode($response);
    
} catch (Exception $e) {
    // Log the error
    logCallback('Error', ['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
    
    // Return an error response
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Server error']);
} 