<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

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

try {
    if (!isset($_POST['icd10_id'])) {
        echo json_encode(['success' => false, 'message' => 'Missing ICD-10 ID']);
        exit();
    }

    $icd10_id = intval($_POST['icd10_id']);

    // Check if code is being used in consultations (optional - you can enable this if needed)
    
    $check_sql = "SELECT COUNT(*) as count FROM consultations 
                  WHERE diagnosis_primary LIKE CONCAT('%', (SELECT code FROM icd10_codes WHERE icd10_id = ?), '%')
                  OR diagnosis_secondary LIKE CONCAT('%', (SELECT code FROM icd10_codes WHERE icd10_id = ?), '%')";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("ii", $icd10_id, $icd10_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result()->fetch_assoc();
    
    if ($check_result['count'] > 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Cannot delete: This ICD-10 code is used in ' . $check_result['count'] . ' consultation(s). Consider deactivating it instead.'
        ]);
        exit();
    }
    

    // Delete the code
    $sql = "DELETE FROM icd10_codes WHERE icd10_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $icd10_id);

    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'ICD-10 code deleted successfully'
        ]);
    } else {
        throw new Exception($stmt->error);
    }

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

$conn->close();
?>