<?php
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit;
}

$inventory_id = isset($_POST['inventory_id']) ? (int)$_POST['inventory_id'] : 0;
$item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
$category_id = isset($_POST['category_id']) ? (int)$_POST['category_id'] : 0;
$current_stock = isset($_POST['current_stock']) ? (int)$_POST['current_stock'] : 0;
$unit_cost = isset($_POST['unit_cost']) ? (float)$_POST['unit_cost'] : 0;
$selling_price = isset($_POST['selling_price']) ? (float)$_POST['selling_price'] : 0;

if ($inventory_id <= 0 || $item_name === '') {
    echo json_encode(['success' => false, 'message' => 'Invalid inventory id or item name']);
    exit;
}

if ($current_stock < 0) {
    echo json_encode(['success' => false, 'message' => 'Stock cannot be negative']);
    exit;
}

if ($category_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid category']);
    exit;
}

$markup_percentage = ($unit_cost > 0) ? (($selling_price - $unit_cost) / $unit_cost) * 100 : 0;

$stmt = $conn->prepare("UPDATE pharmacy_inventory SET item_name = ?, category_id = ?, current_stock = ?, unit_cost = ?, selling_price = ?, markup_percentage = ?, updated_at = NOW() WHERE inventory_id = ?");
$stmt->bind_param('siidddi', $item_name, $category_id, $current_stock, $unit_cost, $selling_price, $markup_percentage, $inventory_id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Row updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Update failed: ' . $conn->error]);
}
$stmt->close();
?>
