<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../../dripend/includes/db.php';

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // 1. Find the exact unit name first
    $stmtFind = $conn->prepare("SELECT unit_name FROM units_of_measure WHERE id = ?");
    $stmtFind->bind_param("i", $id);
    $stmtFind->execute();
    $res = $stmtFind->get_result()->fetch_assoc();
    $stmtFind->close();

    if ($res) {
        $name = $res['unit_name'];
        
        // 2. Enterprise Safety Check: Is this unit actively used in the Master Formulary?
        $stmtCheck = $conn->prepare("SELECT id FROM service_catalog WHERE strength_unit = ? OR unit_of_pricing = ? LIMIT 1");
        $stmtCheck->bind_param("ss", $name, $name);
        $stmtCheck->execute();
        $in_use = $stmtCheck->get_result()->num_rows > 0;
        $stmtCheck->close();

        if ($in_use) {
            // Block deletion to prevent breaking existing drug profiles
            $_SESSION['error'] = "Cannot delete '<strong>{$name}</strong>'. It is currently assigned to one or more medicines in the Master Formulary. Please deactivate it instead.";
        } else {
            // Safe to delete
            $stmtDel = $conn->prepare("DELETE FROM units_of_measure WHERE id = ?");
            $stmtDel->bind_param("i", $id);
            if ($stmtDel->execute()) {
                $_SESSION['success'] = "Unit of measure '<strong>{$name}</strong>' was successfully deleted.";
            } else {
                $_SESSION['error'] = "A database error occurred while trying to delete the unit.";
            }
            $stmtDel->close();
        }
    } else {
        $_SESSION['error'] = "Unit of measure not found.";
    }
} else {
    $_SESSION['error'] = "Invalid request.";
}

// Redirect back to the dictionary dashboard
header("Location: UnitOfMeasure.php");
exit;
?>