<?php
include('include/session.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('connection.php'); 
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

if(isset($_POST['variation'])) { // Check for POST data
    $selectedVariation = $_POST['variation'];

    // Use prepared statement to prevent SQL injection
    $sql = "SELECT product_id, price FROM procurement WHERE variation = ?";
    $stmt = $connection->prepare($sql);

    if ($stmt) {
        $stmt->bind_param("s", $selectedVariation); // Assuming variation is a string
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result) {
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc(); // Fetch only one row
                $price = $row['price'];
                $product_id = $row['product_id'];
                echo json_encode(array('success' => true, 'price' => $price, 'product_id' => $product_id));
            } else {
                echo json_encode(array('success' => false, 'error' => 'Variation not found'));
            }
            $result->close();
        } else {
            echo json_encode(array('success' => false, 'error' => $connection->error)); // Error handling for query execution
        }

        $stmt->close();
    } else {
        echo json_encode(array('success' => false, 'error' => 'Database error'));
    }
} else {
    echo json_encode(array('success' => false, 'error' => 'Variation ID not received'));
}

$connection->close();
?>
