<?php

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

// Log file path
$logFile = __DIR__ . '/ref_requests.log';

// Get parameters (GET or POST)
$order_ref = $_REQUEST['order_ref'] ?? null;
$ref_type  = $_REQUEST['ref_type'] ?? null;

// --------------------
// Validation
// --------------------
if (empty($order_ref) || !is_numeric($order_ref)) {
    echo json_encode([
        'status'  => 'error',
        'message' => 'Invalid order_ref'
    ]);
    exit;
}

$allowedTypes = ['refund', 'void'];

if (empty($ref_type) || !in_array($ref_type, $allowedTypes, true)) {
    echo json_encode([
        'status'  => 'error',
        'message' => 'Invalid ref_type'
    ]);
    exit;
}

// --------------------
// Log request
// --------------------
$logData = [
    'time'      => date('Y-m-d H:i:s'),
    'order_ref' => $order_ref,
    'ref_type'  => $ref_type,
    'ip'        => $_SERVER['REMOTE_ADDR'] ?? 'CLI'
];

file_put_contents(
    $logFile,
    json_encode($logData) . PHP_EOL,
    FILE_APPEND | LOCK_EX
);

// --------------------
// Generate response
// --------------------
$response = [
    'status'     => 'success',
    'order_ref'  => $order_ref,
    'ref_type'   => $ref_type,
    'ref_no'     => 'REF-' . rand(100000, 999999)
];

echo json_encode($response);
