<?php
require '../includes/db.php';
header('Content-Type: application/json');

// Read incoming raw JSON
$data = json_decode(file_get_contents('php://input'), true);

// Validate required fields
if (!isset($data['merchant_key'], $data['secret_key'], $data['amount'], $data['callback_url'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

// Sanitize input
$merchant_key = $data['merchant_key'];
$secret_key = $data['secret_key'];
$amount = floatval($data['amount']);
$callback_url = $data['callback_url'];

// Find the user
$stmt = $pdo->prepare("SELECT * FROM users WHERE merchant_key = ? AND secret_key = ?");
$stmt->execute([$merchant_key, $secret_key]);
$user = $stmt->fetch();

if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid merchant credentials']);
    exit;
}

// Create a transaction (status = pending)
$reference = 'TXN' . time() . rand(1000,9999);
$insert = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, status, payment_gateway, reference) VALUES (?, 'payin', ?, 'pending', 'custom', ?)");
$insert->execute([$user['id'], $amount, $reference]);

// Simulate real payment gateway here later
$response = [
    'status' => 'success',
    'message' => 'Transaction initialized',
    'reference' => $reference,
    'redirect_url' => 'https://yourdomain.com/simulate-gateway.php?ref=' . $reference . '&callback=' . urlencode($callback_url)
];

echo json_encode($response);
