<?php
session_start();
require_once '../config/db.php';

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

try {
    if (!isset($_SESSION['username'])) {
        throw new Exception('User not logged in');
    }

    if (empty($_POST['id'])) {
        throw new Exception('Category ID is required');
    }

    $id = $_POST['id'];

    // Check if category is in use
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM drugs WHERE category IN (SELECT category_name FROM categories WHERE id = ?)");
    $stmt->execute([$id]);
    if ($stmt->fetchColumn() > 0) {
        throw new Exception('Cannot delete category that is in use');
    }

    // Delete category
    $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
    $stmt->execute([$id]);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}