<?php
session_start();
header('Content-Type: application/json');

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

include('../../includes/config.php');

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

if (!$id) {
    echo json_encode(['success' => false, 'message' => 'Invalid inventory ID']);
    exit();
}

// Fetch inventory data before deletion for audit logging
$stmt_fetch = $conn->prepare("SELECT * FROM inventory WHERE id = ? AND deleted_at IS NULL");
$stmt_fetch->bind_param("i", $id);
$stmt_fetch->execute();
$result = $stmt_fetch->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Inventory not found or already deleted.']);
    exit();
}

$inventory_before = $result->fetch_assoc();
$stmt_fetch->close();

// Soft delete inventory by setting deleted_at timestamp and modified_by
$stmt = $conn->prepare("UPDATE inventory SET deleted_at = NOW(), modified_by = ? WHERE id = ? AND deleted_at IS NULL");
$stmt->bind_param("ii", $_SESSION['user_id'], $id);

if ($stmt->execute()) {
    if ($stmt->affected_rows > 0) {
        // Log deletion in audit_log
        $action = 'delete_inventory';
        $module = 'Inventory';
        $details = json_encode([
            'deleted_record' => $inventory_before
        ]);
        $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

        $audit_stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info) VALUES (?, ?, ?, NOW(), ?, ?, ?)");
        $audit_stmt->bind_param("isssis", $_SESSION['user_id'], $action, $details, $module, $_SESSION['role_id'], $device_info);
        $audit_stmt->execute();
        $audit_stmt->close();

        echo json_encode(['success' => true, 'message' => 'Inventory deleted successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Inventory not found or already deleted.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $stmt->error]);
}
