<?php
include '../db.php';
include '../auth.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['role_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

// Check if user has the "Edit Sale Price in POS" right
$role_id = $_SESSION['role_id'];
$right_name = 'Edit Sale Price in POS';
$query = $conn->prepare("
    SELECT 1 FROM role_rights 
    JOIN rights ON role_rights.right_id = rights.id 
    WHERE role_rights.role_id = ? AND LOWER(rights.name) = LOWER(?)
    LIMIT 1
");
$query->bind_param("is", $role_id, $right_name);
$query->execute();
$query->store_result();

if ($query->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to edit prices']);
    exit;
}

// Get POST data
$item_code = $_POST['item_code'] ?? '';
$new_price = $_POST['new_price'] ?? '';

// Validate input
if (empty($item_code) || empty($new_price)) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

// Validate price is a positive number
$new_price = floatval($new_price);
if ($new_price <= 0) {
    echo json_encode(['success' => false, 'message' => 'Price must be greater than 0']);
    exit;
}

// No price limits - user can set any price above 0

header('Content-Type: application/json');
echo json_encode([
    'success' => true, 
    'message' => 'Price updated successfully',
    'new_price' => number_format($new_price, 2)
]);
?>
