<?php
// create_order.php - Initializes a "Pending" transaction
require_once 'config.php';

$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
    file_put_contents(__DIR__ . '/debug.log', "[" . date('Y-m-d H:i:s') . "] CREATE ORDER FAILED: No JSON data\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'No data']);
    exit;
}

$customer_id = $data['user_id'] ?? null;
$amount = (float)($data['amount'] ?? 0);
$api_key = $_SERVER['HTTP_X_API_KEY'] ?? ($data['api_key'] ?? null);
$return_url = $data['return_url'] ?? null;

if ($amount <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid amount']);
    exit;
}

$merchant_id = null;
if ($api_key) {
    // Validate Merchant Key
    $m_res = supabase_request('GET', 'merchants?api_key=eq.' . $api_key);
    if (!empty($m_res['data'])) {
        $merchant_id = $m_res['data'][0]['id'];
    }
}

$order_id = "ORD_" . time() . "_" . rand(1000, 9999);

// Create a pending record in Supabase
$response = supabase_request('POST', 'transactions', [
    'customer_id' => $customer_id,
    'merchant_id' => $merchant_id,
    'amount' => $amount,
    'status' => 'pending',
    'order_id' => $order_id,
    'return_url' => $return_url
]);

if ($response['status'] == 201 || $response['status'] == 200) {
    file_put_contents('debug.log', "[" . date('Y-m-d H:i:s') . "] ORDER CREATED: $order_id for Amount: $amount (Merchant: " . ($merchant_id ?? 'None') . ")\n", FILE_APPEND);
    echo json_encode(['status' => 'success', 'order_id' => $order_id, 'amount' => $amount]);
} else {
    file_put_contents('debug.log', "[" . date('Y-m-d H:i:s') . "] DB ERROR: " . json_encode($response) . "\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'Failed to create order']);
}
?>
