<?php
// Check if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: ../../../views/auth/403.php");
    exit;
}

require_once '../../../config/constants.php';
require_once '../../../database/db_connect.php';

if (isset($_POST['price_ask'])) {
    sendAjaxRequest();
}

function sendAjaxRequest()
{
    // Prepare data for POST request
    $postData = array(
        "sendMessage" => "price_ask",
        "id" => $_SESSION['id'],
        "username" => $_SESSION['username'],
        "time" => date("Y-m-d h:i:sa"),
        "host" => $_SERVER['HTTP_HOST'],
        "ip" => $_SERVER['REMOTE_ADDR'],
        "code" => $_POST['code'],
    );

    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, "http://auto.yadak.center/");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL request
    curl_exec($ch);

    // Close cURL session
    curl_close($ch);
}

if (isset($_POST['getPrices'])) {

    echo getPrices($_POST['code']);
}

function getPrices($data)
{
    // Set the URL for the external HTTP API
    $apiUrl = 'http://84.241.41.22:9002/yadakshop-app/lastPrice.php';

    // Initialize cURL session
    $ch = curl_init();

    // Prepare the data to send (wrap it in an associative array)
    $data = [
        'code' => $data // Assuming you want to send the 'code' value
    ];

    // Set cURL options for POST request
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true); // Set method to POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // Send data as a query string

    // Execute the request
    $response = curl_exec($ch);

    // Check for errors
    if ($response === false) {
        $error = curl_error($ch);
        echo json_encode(['error' => 'Error fetching data: ' . $error]);
        exit;
    }

    // Close cURL session
    curl_close($ch);

    // Send the response back to the client
    header('Content-Type: application/json');
    echo $response;
}

if (isset($_POST['record_request'])) {
    $user_id = $_POST['id'];
    recordRequest($user_id);
}

function recordRequest($user_id)
{
    $stmt = PDO_CONNECTION->prepare("INSERT INTO requests (user_id) VALUES (:user_id);");
    $stmt->bindParam(":user_id", $user_id);
    $stmt->execute();
}
