<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include '../connection.php';

$service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$price = isset($_POST['price']) ? floatval($_POST['price']) : 0;

if ($service_id <= 0 || $product_id <= 0 || $price < 0) {
    echo json_encode(["success" => false, "message" => "Invalid input data"]);
    exit;
}

// Check if combination already exists
$check = $conn->prepare("SELECT id FROM tbl_service_product_prices WHERE service_id=? AND product_id=?");
$check->bind_param("ii", $service_id, $product_id);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "This service-product combination already exists"]);
    exit;
}

$stmt = $conn->prepare("INSERT INTO tbl_service_product_prices (service_id, product_id, price) VALUES (?, ?, ?)");
$stmt->bind_param("iid", $service_id, $product_id, $price);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Price added successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to add price"]);
}

$stmt->close();
$conn->close();
?>