<?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 formulation name first
    $stmtFind = $conn->prepare("SELECT formulation_name FROM drug_formulations WHERE id = ?");
    $stmtFind->bind_param("i", $id);
    $stmtFind->execute();
    $res = $stmtFind->get_result()->fetch_assoc();
    $stmtFind->close();

    if ($res) {
        $name = $res['formulation_name'];
        
        // 2. Enterprise Safety Check: Is this formulation actively used in the Master Formulary?
        $stmtCheck = $conn->prepare("SELECT id FROM service_catalog WHERE drug_formulation = ? LIMIT 1");
        $stmtCheck->bind_param("s", $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 drug_formulations WHERE id = ?");
            $stmtDel->bind_param("i", $id);
            if ($stmtDel->execute()) {
                $_SESSION['success'] = "Formulation '<strong>{$name}</strong>' was successfully deleted.";
            } else {
                $_SESSION['error'] = "A database error occurred while trying to delete the formulation.";
            }
            $stmtDel->close();
        }
    } else {
        $_SESSION['error'] = "Formulation not found in the database.";
    }
} else {
    $_SESSION['error'] = "Invalid request.";
}

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