<?php
/**
 * ajax/update_consultation.php
 * Handles POST from edit_consultation.php.
 * Updates narrative / examination / diagnosis / plan fields only.
 * Does NOT touch status, fees, medications, queue, or visit status —
 * those are managed exclusively by save_consultation.php.
 */

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

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

/* ── Auth ──────────────────────────────────────────────────────────────────── */
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorised.']);
    exit;
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'RESIDENT_DOCTOR'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Permission denied.']);
    exit;
}

/* ── Helpers ───────────────────────────────────────────────────────────────── */
function p(string $key, string $default = ''): string
{
    return trim($_POST[$key] ?? $default);
}

function pnull(string $key): ?string
{
    $v = trim($_POST[$key] ?? '');
    return $v !== '' ? $v : null;
}

function safe_json($value): ?string
{
    if ($value === null || $value === '') return null;
    if (is_string($value)) {
        $d = json_decode($value, true);
        return (json_last_error() === JSON_ERROR_NONE) ? json_encode($d) : null;
    }
    if (is_array($value)) return json_encode($value);
    return null;
}

/* ── Validate consultation_id ──────────────────────────────────────────────── */
$consultation_id = (int)($_POST['consultation_id'] ?? 0);
if ($consultation_id < 1) {
    echo json_encode(['success' => false, 'message' => 'Invalid consultation ID.']);
    exit;
}

/* ── Verify the record exists and the current user has rights to edit it ───── */
$chk = $conn->prepare("
    SELECT c.consultation_id, c.status, d.user_id AS doctor_user_id
    FROM   consultations c
    JOIN   doctors d ON c.doctor_id = d.doctor_id
    WHERE  c.consultation_id = ?
    LIMIT  1
");
if (!$chk) {
    echo json_encode(['success' => false, 'message' => 'DB error: ' . $conn->error]);
    exit;
}
$chk->bind_param('i', $consultation_id);
$chk->execute();
$row = $chk->get_result()->fetch_assoc();
$chk->close();

if (!$row) {
    echo json_encode(['success' => false, 'message' => 'Consultation not found.']);
    exit;
}

// Only SUPER_ADMIN / HOSPITAL_ADMIN can edit another doctor's completed consultation
$is_admin       = in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN']);
$is_own_consult = ((int)$_SESSION['user_id'] === (int)$row['doctor_user_id']);

if (!$is_admin && !$is_own_consult) {
    echo json_encode(['success' => false, 'message' => 'You can only edit your own consultations.']);
    exit;
}

/* ── Collect fields ─────────────────────────────────────────────────────────── */
$chief_complaint           = pnull('chief_complaint');
$history_present_illness   = pnull('history_present_illness');
$past_medical_history      = pnull('past_medical_history');
$family_history            = pnull('family_history');
$social_history            = pnull('social_history');
$general_examination       = pnull('general_examination');
$diagnosis_primary         = pnull('diagnosis_primary');
$diagnosis_primary_icd11   = pnull('diagnosis_primary_icd11');
$diagnosis_secondary       = pnull('diagnosis_secondary');
$diagnosis_secondary_icd11 = pnull('diagnosis_secondary_icd11');
$differential_diagnosis    = pnull('differential_diagnosis');
$treatment_plan            = pnull('treatment_plan');
$follow_up_instructions    = pnull('follow_up_instructions');
$next_appointment          = pnull('next_appointment');
$doctor_notes              = pnull('doctor_notes');

$ear_examination    = safe_json($_POST['ear_examination']    ?? null);
$nose_examination   = safe_json($_POST['nose_examination']   ?? null);
$throat_examination = safe_json($_POST['throat_examination'] ?? null);
$neck_examination   = safe_json($_POST['neck_examination']   ?? null);
$cranial_nerves     = safe_json($_POST['cranial_nerves']     ?? null);

/* ── Require primary diagnosis ─────────────────────────────────────────────── */
if (empty($diagnosis_primary)) {
    echo json_encode(['success' => false, 'message' => 'Primary diagnosis is required.']);
    exit;
}

/* ── Update ─────────────────────────────────────────────────────────────────── */
$stmt = $conn->prepare("
    UPDATE consultations SET
        chief_complaint           = ?,
        history_present_illness   = ?,
        past_medical_history      = ?,
        family_history            = ?,
        social_history            = ?,
        general_examination       = ?,
        ear_examination           = ?,
        nose_examination          = ?,
        throat_examination        = ?,
        neck_examination          = ?,
        cranial_nerves            = ?,
        diagnosis_primary         = ?,
        diagnosis_primary_icd11   = ?,
        diagnosis_secondary       = ?,
        diagnosis_secondary_icd11 = ?,
        differential_diagnosis    = ?,
        treatment_plan            = ?,
        follow_up_instructions    = ?,
        next_appointment          = ?,
        doctor_notes              = ?,
        updated_at                = NOW()
    WHERE consultation_id = ?
");

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Prepare error: ' . $conn->error]);
    exit;
}

$stmt->bind_param(
    'ssssssssssssssssssssi',
    $chief_complaint,
    $history_present_illness,
    $past_medical_history,
    $family_history,
    $social_history,
    $general_examination,
    $ear_examination,
    $nose_examination,
    $throat_examination,
    $neck_examination,
    $cranial_nerves,
    $diagnosis_primary,
    $diagnosis_primary_icd11,
    $diagnosis_secondary,
    $diagnosis_secondary_icd11,
    $differential_diagnosis,
    $treatment_plan,
    $follow_up_instructions,
    $next_appointment,
    $doctor_notes,
    $consultation_id
);

if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Execute error: ' . $stmt->error]);
    exit;
}

$stmt->close();

echo json_encode([
    'success'         => true,
    'consultation_id' => $consultation_id,
    'message'         => 'Consultation updated successfully.',
]);