<?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();
}

$user_id = $_SESSION['user_id'];

try {
    // Validate required fields
    if (!isset($_POST['icd10_id']) || !isset($_POST['code']) || !isset($_POST['short_description'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }

    $icd10_id = intval($_POST['icd10_id']);
    $code = trim($_POST['code']);
    $short_description = trim($_POST['short_description']);
    $full_description = isset($_POST['full_description']) ? trim($_POST['full_description']) : null;
    $category = isset($_POST['category']) ? trim($_POST['category']) : null;
    $chapter = isset($_POST['chapter']) ? trim($_POST['chapter']) : null;
    $chapter_code = isset($_POST['chapter_code']) ? trim($_POST['chapter_code']) : null;
    $synonyms = isset($_POST['synonyms']) ? trim($_POST['synonyms']) : null;
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : null;
    $is_billable = isset($_POST['is_billable']) ? 1 : 0;
    $is_ent_related = isset($_POST['is_ent_related']) ? 1 : 0;
    $commonly_used = isset($_POST['commonly_used']) ? 1 : 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    // Validate code format
    if (!preg_match('/^[A-Z][0-9]{2}(\.[0-9]{1,4})?$/', $code)) {
        echo json_encode(['success' => false, 'message' => 'Invalid ICD-10 code format. Use format like H65.0']);
        exit();
    }

    // Check if code already exists (excluding current record)
    $check_sql = "SELECT icd10_id FROM icd10_codes WHERE code = ? AND icd10_id != ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("si", $code, $icd10_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'This ICD-10 code already exists']);
        exit();
    }

    // Update the ICD-10 code
    $sql = "UPDATE icd10_codes SET 
            code = ?,
            short_description = ?,
            full_description = ?,
            category = ?,
            chapter = ?,
            chapter_code = ?,
            synonyms = ?,
            notes = ?,
            is_billable = ?,
            is_ent_related = ?,
            commonly_used = ?,
            is_active = ?,
            updated_at = NOW()
            WHERE icd10_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        "sssssssiiiii",
        $code,
        $short_description,
        $full_description,
        $category,
        $chapter,
        $chapter_code,
        $synonyms,
        $notes,
        $is_billable,
        $is_ent_related,
        $commonly_used,
        $is_active,
        $icd10_id
    );

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

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

$conn->close();
?>