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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Only admins can delete documents
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Permission denied']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$document_id = isset($input['document_id']) ? intval($input['document_id']) : 0;

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

try {
    $conn->begin_transaction();

    // Get document details before deletion
    $get_doc_sql = "SELECT file_path FROM medical_documents WHERE document_id = ?";
    $stmt = $conn->prepare($get_doc_sql);
    $stmt->bind_param('i', $document_id);
    $stmt->execute();
    $result = $stmt->get_result();

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

    $document = $result->fetch_assoc();
    $file_path = $document['file_path'];

    // Log the deletion before deleting
    $log_sql = "INSERT INTO document_access_log (
        document_id, accessed_by, access_type, access_ip
    ) VALUES (?, ?, 'DELETE', ?)";
    
    $log_stmt = $conn->prepare($log_sql);
    $access_ip = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param('iis', $document_id, $_SESSION['user_id'], $access_ip);
    $log_stmt->execute();

    // Soft delete - update status to DELETED instead of actually deleting
    $delete_sql = "UPDATE medical_documents SET status = 'DELETED' WHERE document_id = ?";
    $stmt = $conn->prepare($delete_sql);
    $stmt->bind_param('i', $document_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete document');
    }

    $conn->commit();

    // Optionally, you can physically delete the file or keep it for audit purposes
    // Uncomment the line below to physically delete the file:
    // if (file_exists($file_path)) { unlink($file_path); }

    echo json_encode([
        'success' => true,
        'message' => 'Document deleted successfully'
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to delete document: ' . $e->getMessage()
    ]);
}
?>