<?php
header("Content-Type: application/json; charset=UTF-8");

// Debug mode (disable in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
    exit;
}

$targetUrl = "http://84.241.41.22:9002/yadakshop-app/lastPrice.php";

// Get "code" from POST or JSON body
$code = null;

if (!empty($_POST['code'])) {
    // Standard form POST
    $code = $_POST['code'];
} else {
    // Check for JSON body
    $raw = file_get_contents("php://input");
    $json = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE && isset($json['code'])) {
        $code = $json['code'];
    }
}

if ($code === null || $code === '') {
    http_response_code(400);
    echo json_encode(["error" => "Missing 'code' parameter"]);
    exit;
}

// Build POST data for remote server
$postData = http_build_query(['code' => $code]);

// Send request to remote server
$ch = curl_init($targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    http_response_code(500);
    echo json_encode([
        "error" => "cURL error: " . curl_error($ch)
    ]);
    curl_close($ch);
    exit;
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

http_response_code($httpCode);
echo $response;
