Lokasi:
/
home
/
u847703118
/
domains
/
alphamed.cloud
/
public_html
/
Ubah: consultation.php
<?php ob_start(); require('includes/auth_session.php'); if (function_exists('isClinicManagementEnabled') && !isClinicManagementEnabled($pdo)) { header("Location: dashboard.php"); exit(); } $__ensureSchema = function() use ($pdo) { try { $pdo->exec("CREATE TABLE IF NOT EXISTS consultation_records ( id INT AUTO_INCREMENT PRIMARY KEY, patient_id INT NOT NULL, doctor_id INT NOT NULL, invoice_id INT NULL, consultation_date DATETIME DEFAULT CURRENT_TIMESTAMP, chief_complaint TEXT NULL, history TEXT NULL, findings TEXT NULL, diagnosis TEXT NULL, plan TEXT NULL, created_by INT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NULL DEFAULT NULL, FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE, FOREIGN KEY (doctor_id) REFERENCES doctors(id) ON DELETE SET NULL, FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE SET NULL )"); if (function_exists('tableHasColumn')) { if (!tableHasColumn($pdo, 'consultation_records', 'follow_up_days')) { $pdo->exec("ALTER TABLE consultation_records ADD COLUMN follow_up_days INT NULL AFTER plan"); } if (!tableHasColumn($pdo, 'consultation_records', 'follow_up_notes')) { $pdo->exec("ALTER TABLE consultation_records ADD COLUMN follow_up_notes TEXT NULL AFTER follow_up_days"); } if (!tableHasColumn($pdo, 'consultation_records', 'follow_up_completed')) { $pdo->exec("ALTER TABLE consultation_records ADD COLUMN follow_up_completed TINYINT(1) NOT NULL DEFAULT 0 AFTER follow_up_notes"); } } $pdo->exec("CREATE TABLE IF NOT EXISTS consultation_prescriptions ( id INT AUTO_INCREMENT PRIMARY KEY, patient_id INT NOT NULL, doctor_id INT NOT NULL, consultation_id INT NULL, invoice_id INT NULL, notes TEXT NULL, created_by INT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE, FOREIGN KEY (doctor_id) REFERENCES doctors(id) ON DELETE SET NULL, FOREIGN KEY (consultation_id) REFERENCES consultation_records(id) ON DELETE SET NULL, FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE SET NULL )"); $pdo->exec("CREATE TABLE IF NOT EXISTS consultation_prescription_items ( id INT AUTO_INCREMENT PRIMARY KEY, prescription_id INT NOT NULL, medicine_name VARCHAR(255) NOT NULL, dosage VARCHAR(255) NULL, frequency VARCHAR(255) NULL, duration VARCHAR(255) NULL, instructions TEXT NULL, FOREIGN KEY (prescription_id) REFERENCES consultation_prescriptions(id) ON DELETE CASCADE )"); } catch (\Throwable $e) {} }; $__ensureSchema(); // AJAX: Get Doctor Fee if (isset($_GET['action']) && $_GET['action'] == 'get_doctor_fee' && isset($_GET['doctor_id'])) { header('Content-Type: application/json'); $docId = intval($_GET['doctor_id']); $fee = 0; try { $stmt = $pdo->prepare("SELECT consultation_fee FROM doctors WHERE id = ?"); $stmt->execute([$docId]); $fee = floatval($stmt->fetchColumn() ?: 0); } catch (Exception $e) {} echo json_encode(['fee' => $fee]); exit; } $use_custom_modules = ($_SESSION['use_custom_modules'] ?? false); $can_consult_menu = userCanAccess('consultation', ['admin', 'doctor', 'staff']); if ($use_custom_modules) { $can_records = userHasModule('consultation_records'); $can_prescriptions = userHasModule('consultation_prescriptions'); $can_followups = userHasModule('consultation_followups'); $can_create_rx_from_consult = userHasModule('consultation_create_prescription') && userHasModule('consultation_prescriptions'); } else { $can_records = $can_consult_menu; $can_prescriptions = $can_consult_menu; $can_followups = $can_consult_menu; $can_create_rx_from_consult = $can_consult_menu; } $is_admin = (($_SESSION['role'] ?? '') === 'admin'); $is_doctor = (($_SESSION['role'] ?? '') === 'doctor'); if (!$can_records && !$can_prescriptions && !$can_followups) { header("Location: dashboard.php"); exit(); } $tab = $_GET['tab'] ?? 'records'; if (!in_array($tab, ['records', 'prescriptions', 'followups'], true)) { $tab = 'records'; } $msg = $_GET['msg'] ?? ''; $error = $_GET['error'] ?? ''; $current_doctor_id = null; try { $stmtDoc = $pdo->prepare("SELECT id FROM doctors WHERE user_id = ?"); $stmtDoc->execute([$_SESSION['user_id']]); $current_doctor_id = $stmtDoc->fetchColumn() ?: null; } catch (Exception $e) { $current_doctor_id = null; } // Fetch Today's Consultations Log $today = date('Y-m-d'); $today_consults = []; // Fetch Active Discounts $active_discounts = []; if (tableExists($pdo, 'discount_definitions')) { $stmtDisc = $pdo->query("SELECT * FROM discount_definitions WHERE active = 1 ORDER BY name ASC"); $active_discounts = $stmtDisc->fetchAll(PDO::FETCH_ASSOC); } // Fetch Lab Tests for Request Modal $req_categories = []; try { $stmt = $pdo->query("SELECT id, test_name, category FROM lab_tests ORDER BY category, test_name"); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $cat = $row['category'] ?: 'Uncategorized'; $req_categories[$cat][] = ['id' => $row['id'], 'name' => $row['test_name']]; } } catch (Exception $e) { } try { // 1. Existing consultation records for today - SKIPPED to show only pending in "Today's Consultations Log" // The user requested that completed consultations move to "Recent Consultation Records" immediately. $today_consults = []; /* Original code preserved for reference: $sql = "SELECT cr.*, p.first_name, p.last_name, d.name as doctor_name FROM consultation_records cr JOIN patients p ON cr.patient_id = p.id JOIN doctors d ON cr.doctor_id = d.id WHERE DATE(cr.created_at) = ?"; $params = [$today]; if ($is_doctor && $current_doctor_id) { $sql .= " AND cr.doctor_id = ?"; $params[] = $current_doctor_id; } $sql .= " ORDER BY cr.created_at DESC"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $today_consults = $stmt->fetchAll(PDO::FETCH_ASSOC); */ // 2. Served patients (Pending Consultation) // Fetch served patients who do not have a consultation record yet today $sqlServed = "SELECT r.id AS reservation_id, r.patient_id, r.reservation_date, r.served_at as created_at, p.first_name, p.last_name, d.name as doctor_name, r.doctor_id, NULL as id, NULL as diagnosis, NULL as follow_up_days FROM clinic_reservations r JOIN patients p ON r.patient_id = p.id JOIN doctors d ON r.doctor_id = d.id WHERE r.reservation_date = ? AND r.is_served = 1 AND r.is_confirmed = 1 AND NOT EXISTS ( SELECT 1 FROM consultation_records cr WHERE cr.patient_id = r.patient_id AND DATE(cr.created_at) = r.reservation_date AND cr.doctor_id = r.doctor_id )"; // Filter out cancelled consultations if table exists if (function_exists('tableExists') && tableExists($pdo, 'clinic_patient_list')) { $sqlServed .= " AND NOT EXISTS ( SELECT 1 FROM clinic_patient_list l WHERE l.reservation_id = r.id AND l.status = 'consult_cancelled' )"; } $paramsServed = [$today]; if ($is_doctor && $current_doctor_id) { $sqlServed .= " AND r.doctor_id = ?"; $paramsServed[] = $current_doctor_id; } $stmtServed = $pdo->prepare($sqlServed); $stmtServed->execute($paramsServed); $pending_served = $stmtServed->fetchAll(PDO::FETCH_ASSOC); // Merge and sort if (!empty($pending_served)) { $today_consults = array_merge($today_consults, $pending_served); usort($today_consults, function($a, $b) { return strtotime($b['created_at']) - strtotime($a['created_at']); }); } } catch (Exception $e) { $today_consults = []; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($tab === 'records' && $can_records) { $patient_id = intval($_POST['patient_id'] ?? 0); $doctor_id = intval($_POST['doctor_id'] ?? 0); $chief_complaint = trim($_POST['chief_complaint'] ?? ''); $history = trim($_POST['history'] ?? ''); $findings = trim($_POST['findings'] ?? ''); $diagnosis = trim($_POST['diagnosis'] ?? ''); $plan = trim($_POST['plan'] ?? ''); $invoice_id = !empty($_POST['invoice_id']) ? intval($_POST['invoice_id']) : null; $has_follow_up = !empty($_POST['has_follow_up']) ? 1 : 0; $follow_up_days = null; $follow_up_notes = null; if ($has_follow_up) { $preset = $_POST['follow_up_preset'] ?? ''; $custom_days = isset($_POST['follow_up_days']) ? intval($_POST['follow_up_days']) : null; if ($preset !== '' && $preset !== 'custom') { $follow_up_days = intval($preset); } elseif ($custom_days) { $follow_up_days = $custom_days; } $follow_up_notes = trim($_POST['follow_up_notes'] ?? ''); } if ($patient_id <= 0) { $error = "Select a patient."; } elseif ($doctor_id <= 0 && !$current_doctor_id) { $error = "Select a doctor."; } else { if ($doctor_id <= 0) $doctor_id = $current_doctor_id; $edit_id = !empty($_POST['edit_id']) ? intval($_POST['edit_id']) : null; if ($edit_id) { if (!$is_admin) { $error = "Only admins can edit consultation records."; } else { $sql = "UPDATE consultation_records SET patient_id=?, doctor_id=?, invoice_id=?, chief_complaint=?, history=?, findings=?, diagnosis=?, plan=?, follow_up_days=?, follow_up_notes=?, updated_at=NOW() WHERE id=?"; $stmt = $pdo->prepare($sql); if ($stmt->execute([$patient_id, $doctor_id, $invoice_id, $chief_complaint, $history, $findings, $diagnosis, $plan, $follow_up_days, $follow_up_notes, $edit_id])) { if (function_exists('logAction')) { logAction($pdo, $_SESSION['user_id'], 'Edit Consultation', "Updated consultation record #$edit_id for Patient ID: $patient_id"); } $msg = "Consultation record updated."; header("Location: consultation.php?tab=records&msg=" . urlencode($msg)); exit(); } else { $error = "Failed to update."; } } } else { // Auto-billing: DISABLED per user request (Bill button in queue should handle billing) /* if (empty($invoice_id)) { $docFee = isset($_POST['consultation_fee']) ? floatval($_POST['consultation_fee']) : 0; // Fallback if not set via UI if ($docFee <= 0) { try { $stmtF = $pdo->prepare("SELECT consultation_fee FROM doctors WHERE id = ?"); $stmtF->execute([$doctor_id]); $docFee = floatval($stmtF->fetchColumn() ?: 0); } catch(Exception $e){} } if ($docFee > 0) { try { // ... (auto-invoice creation logic removed to prevent 'Pending' status) ... } catch(Exception $e) { } } } */ // Check duplication $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM consultation_records WHERE patient_id = ? AND doctor_id = ? AND DATE(created_at) = CURDATE()"); $stmtCheck->execute([$patient_id, $doctor_id]); if ($stmtCheck->fetchColumn() > 0) { $error = "A consultation record for this patient and doctor already exists today."; } else { $sql = "INSERT INTO consultation_records (patient_id, doctor_id, invoice_id, chief_complaint, history, findings, diagnosis, plan, follow_up_days, follow_up_notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); if ($stmt->execute([$patient_id, $doctor_id, $invoice_id, $chief_complaint, $history, $findings, $diagnosis, $plan, $follow_up_days, $follow_up_notes, $_SESSION['user_id']])) { $new_consult_id = $pdo->lastInsertId(); // Ensure patient is marked as served so they appear in billing list with Bill button enabled try { $stmtServed = $pdo->prepare("UPDATE clinic_reservations SET is_served = 1 WHERE patient_id = ? AND reservation_date = CURDATE()"); $stmtServed->execute([$patient_id]); } catch (Exception $e) {} if (function_exists('logAction')) { logAction($pdo, $_SESSION['user_id'], 'Create Consultation', "Created consultation record #$new_consult_id for Patient ID: $patient_id"); } $msg = "Consultation record saved."; header("Location: consultation.php?tab=records&msg=" . urlencode($msg)); exit(); } else { $error = "Failed to save."; } } } } } elseif ($tab === 'prescriptions' && $can_prescriptions) { $patient_id = intval($_POST['patient_id'] ?? 0); $doctor_id = intval($_POST['doctor_id'] ?? 0); $consultation_id = !empty($_POST['consultation_id']) ? intval($_POST['consultation_id']) : null; $invoice_id = !empty($_POST['invoice_id']) ? intval($_POST['invoice_id']) : null; $notes = trim($_POST['notes'] ?? ''); $items = $_POST['items'] ?? []; $edit_id = !empty($_POST['edit_id']) ? intval($_POST['edit_id']) : null; if ($patient_id <= 0) { $error = "Select a patient."; } elseif ($doctor_id <= 0 && !$current_doctor_id) { $error = "Select a doctor."; } else { if ($doctor_id <= 0) $doctor_id = $current_doctor_id; if ($edit_id) { $stmt = $pdo->prepare("UPDATE consultation_prescriptions SET patient_id=?, doctor_id=?, consultation_id=?, invoice_id=?, notes=? WHERE id=?"); if ($stmt->execute([$patient_id, $doctor_id, $consultation_id, $invoice_id, $notes, $edit_id])) { $prescription_id = $edit_id; $pdo->prepare("DELETE FROM consultation_prescription_items WHERE prescription_id=?")->execute([$prescription_id]); if (function_exists('logAction')) { logAction($pdo, $_SESSION['user_id'], 'Edit Prescription', "Updated prescription #$prescription_id for Patient ID: $patient_id"); } $msg = "Prescription updated."; } else { $error = "Failed to update."; } } else { $stmt = $pdo->prepare("INSERT INTO consultation_prescriptions (patient_id, doctor_id, consultation_id, invoice_id, notes, created_by) VALUES (?, ?, ?, ?, ?, ?)"); if ($stmt->execute([$patient_id, $doctor_id, $consultation_id, $invoice_id, $notes, $_SESSION['user_id']])) { $prescription_id = $pdo->lastInsertId(); if (function_exists('logAction')) { logAction($pdo, $_SESSION['user_id'], 'Create Prescription', "Created prescription #$prescription_id for Patient ID: $patient_id"); } $msg = "Prescription saved."; } else { $error = "Failed to save."; } } if (!$error && is_array($items)) { $ins = $pdo->prepare("INSERT INTO consultation_prescription_items (prescription_id, medicine_name, dosage, frequency, duration, instructions) VALUES (?, ?, ?, ?, ?, ?)"); foreach ($items as $it) { $name = trim($it['medicine_name'] ?? ''); if ($name === '') continue; $dosage = trim($it['dosage'] ?? ''); $freq = trim($it['frequency'] ?? ''); $dur = trim($it['duration'] ?? ''); $instr = trim($it['instructions'] ?? ''); $ins->execute([$prescription_id, $name, $dosage, $freq, $dur, $instr]); } } if (!$error) { $autoViewId = isset($prescription_id) ? intval($prescription_id) : 0; $location = "consultation.php?tab=prescriptions"; if ($autoViewId > 0) { $location .= "&auto_view=" . $autoViewId; } header("Location: " . $location); exit(); } } } } $search = trim($_GET['search'] ?? ''); $patients = []; try { $stmt = $pdo->prepare("SELECT id, patient_code, first_name, last_name FROM patients WHERE first_name LIKE ? OR last_name LIKE ? OR patient_code LIKE ? ORDER BY first_name"); $stmt->execute(["%$search%", "%$search%", "%$search%"]); $patients = $stmt->fetchAll(); } catch (Exception $e) { $patients = []; } $doctors = []; try { $stmt = $pdo->query("SELECT id, name FROM doctors ORDER BY name"); $doctors = $stmt->fetchAll(); } catch (Exception $e) { $doctors = []; } $recent_records = []; if ($can_records) { try { $stmt = $pdo->query("SELECT cr.*, p.first_name, p.last_name, d.name as doctor_name FROM consultation_records cr JOIN patients p ON cr.patient_id = p.id JOIN doctors d ON cr.doctor_id = d.id ORDER BY cr.created_at DESC LIMIT 20"); $recent_records = $stmt->fetchAll(); } catch (Exception $e) { $recent_records = []; } } $followup_records = []; $doctor_due_followups = []; if ($can_followups) { try { $sql = "SELECT cr.*, p.first_name, p.last_name, d.name as doctor_name FROM consultation_records cr JOIN patients p ON cr.patient_id = p.id JOIN doctors d ON cr.doctor_id = d.id WHERE cr.follow_up_days IS NOT NULL AND cr.follow_up_days > 0 AND (cr.follow_up_completed IS NULL OR cr.follow_up_completed = 0)"; $params = []; if (!$is_admin && $current_doctor_id) { $sql .= " AND cr.doctor_id = ?"; $params[] = $current_doctor_id; } $sql .= " ORDER BY cr.created_at DESC"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $followup_records = $stmt->fetchAll(); if ($is_doctor && $current_doctor_id) { $todayEnd = strtotime('today 23:59:59'); foreach ($followup_records as $fr) { if (empty($fr['follow_up_days'])) { continue; } $base = !empty($fr['consultation_date']) ? $fr['consultation_date'] : $fr['created_at']; $followTs = strtotime($base . ' +' . intval($fr['follow_up_days']) . ' days'); if ($followTs && $followTs <= $todayEnd) { $doctor_due_followups[] = [ 'id' => $fr['id'], 'patient_name' => ($fr['first_name'] ?? '') . ' ' . ($fr['last_name'] ?? ''), 'doctor_name' => $fr['doctor_name'] ?? '', 'follow_up_date' => date('M d, Y', $followTs), 'follow_up_notes' => $fr['follow_up_notes'] ?? '', 'diagnosis' => $fr['diagnosis'] ?? '', ]; } } } } catch (Exception $e) { $followup_records = []; $doctor_due_followups = []; } } // Common chief complaint options (can still type manually) $chief_complaint_options = [ 'Fever', 'Cough', 'Cough and colds', 'Headache', 'Abdominal pain', 'Chest pain', 'Shortness of breath', 'Dizziness', 'Back pain', 'Sore throat', 'Diarrhea', 'Vomiting', 'Generalized body weakness', 'Dysuria', 'Follow-up consultation' ]; $recent_prescriptions = []; if ($can_prescriptions) { try { $stmt = $pdo->query("SELECT cp.*, p.first_name, p.last_name, d.name as doctor_name FROM consultation_prescriptions cp JOIN patients p ON cp.patient_id = p.id JOIN doctors d ON cp.doctor_id = d.id ORDER BY cp.created_at DESC LIMIT 20"); $recent_prescriptions = $stmt->fetchAll(); } catch (Exception $e) { $recent_prescriptions = []; } } $pharmacy_items = []; try { $stmt = $pdo->query("SELECT id, item_name, unit, stock_qty FROM pharmacy_items ORDER BY item_name"); $pharmacy_items = $stmt->fetchAll(); } catch (Exception $e) { $pharmacy_items = []; } $edit_rx = null; $edit_items = []; if (isset($_GET['edit_prescription_id']) && $can_prescriptions && $can_create_rx_from_consult) { $edit_id = intval($_GET['edit_prescription_id']); try { $stmt = $pdo->prepare("SELECT * FROM consultation_prescriptions WHERE id = ?"); $stmt->execute([$edit_id]); $edit_rx = $stmt->fetch(); if ($edit_rx) { $stmt = $pdo->prepare("SELECT * FROM consultation_prescription_items WHERE prescription_id = ?"); $stmt->execute([$edit_id]); $edit_items = $stmt->fetchAll(); } } catch (Exception $e) {} } $prefill_consult = null; $prefill_patient_id = null; $prefill_doctor_id = null; if ($tab === 'prescriptions' && isset($_GET['from_consultation_id']) && $can_prescriptions) { $from_id = intval($_GET['from_consultation_id']); try { $stmt = $pdo->prepare("SELECT cr.*, p.first_name, p.last_name, d.name as doctor_name FROM consultation_records cr JOIN patients p ON cr.patient_id = p.id JOIN doctors d ON cr.doctor_id = d.id WHERE cr.id = ?"); $stmt->execute([$from_id]); $prefill_consult = $stmt->fetch(); if ($prefill_consult) { $prefill_patient_id = $prefill_consult['patient_id'] ?? null; $prefill_doctor_id = $prefill_consult['doctor_id'] ?? null; } } catch (Exception $e) {} } include('includes/header.php'); ?> <div class="d-flex justify-content-between align-items-center mb-3"> <h2>Consultation</h2> </div> <?php if($msg): ?> <div class="alert alert-success"><?php echo $msg; ?></div> <?php endif; ?> <?php if($error): ?> <div class="alert alert-danger"><?php echo $error; ?></div> <?php endif; ?> <form method="GET" class="row g-2 mb-3"> <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab); ?>"> <div class="col-md-4 col-sm-6"> <input type="text" name="search" class="form-control" placeholder="Search patient by name or code" value="<?php echo htmlspecialchars($search); ?>"> </div> <div class="col-auto"> <button type="submit" class="btn btn-outline-secondary">Search Patient</button> </div> </form> <?php if ($tab === 'records' && $can_records): ?> <div class="d-flex justify-content-between align-items-center mb-3"> <h5 class="mb-0">Consultation Records</h5> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#consultationModal"> Add Consultation </button> </div> <div class="card mb-4"> <div class="card-header bg-white"> <h5 class="mb-0 text-primary">Today's Consultations Log</h5> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hover mb-0"> <thead> <tr> <th>Time</th> <th>Patient</th> <th>Doctor</th> <th>Diagnosis</th> <th>Action</th> </tr> </thead> <tbody> <?php if (!empty($today_consults)): ?> <?php foreach ($today_consults as $c): ?> <?php $is_pending = empty($c['id']); ?> <tr> <td><?php echo date('h:i A', strtotime($c['created_at'])); ?></td> <td><?php echo htmlspecialchars(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? '')); ?></td> <td><?php echo htmlspecialchars($c['doctor_name'] ?? ''); ?></td> <td> <?php if ($is_pending) { echo '<span class="badge bg-warning text-dark">Waiting for consultation</span>'; } else { echo nl2br(htmlspecialchars($c['diagnosis'] ?? '')); } ?> </td> <td> <?php if ($is_pending): ?> <a href="consultation.php?tab=records&patient_id=<?php echo $c['patient_id']; ?>&create_new=1&doctor_id=<?php echo isset($c['doctor_id']) ? $c['doctor_id'] : ''; ?>" class="btn btn-sm btn-success">Create Consultation</a> <?php if (userCanAccess('consultation', ['admin', 'doctor']) && !empty($c['reservation_id'])): ?> <form method="post" action="save_room_reservation.php" class="d-inline ms-1"> <input type="hidden" name="cancel_consult_id" value="<?php echo (int)$c['reservation_id']; ?>"> <input type="hidden" name="reservation_date" value="<?php echo date('Y-m-d'); ?>"> <input type="hidden" name="redirect_page" value="consultation.php?tab=records"> <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Cancel this consultation?');"> Cancel </button> </form> <?php endif; ?> <?php else: ?> <a href="print_consultation.php?id=<?php echo $c['id']; ?>" target="_blank" class="btn btn-sm btn-danger text-white">Print</a> <?php if (userCanAccess('consultation', ['admin', 'doctor'])): ?> <a href="consultation.php?tab=records&auto_view=<?php echo $c['id']; ?>" class="btn btn-sm btn-outline-secondary ms-1">Open</a> <?php endif; ?> <?php endif; ?> </td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td colspan="5" class="text-center text-muted">No consultations recorded today.</td> </tr> <?php endif; ?> </tbody> </table> </div> </div> </div> <div class="card"> <div class="card-header"> <div class="d-flex justify-content-between align-items-center"> <span>Recent Consultation Records</span> <div class="ms-auto" style="max-width:260px;"> <input type="text" id="consultationSearch" class="form-control form-control-sm" placeholder="Search records..."> </div> </div> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="consultationTable"> <thead> <tr> <th>Date</th> <th>Patient</th> <th>Doctor</th> <th>Diagnosis</th> <th>Plan</th> <th>Follow-up</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($recent_records as $r): ?> <?php $followUpDisplay = ''; if (!empty($r['follow_up_days'])) { $baseDate = !empty($r['consultation_date']) ? $r['consultation_date'] : $r['created_at']; $followTs = strtotime($baseDate . ' +' . intval($r['follow_up_days']) . ' days'); if ($followTs) { $followUpDisplay = date('M d, Y', $followTs); if (!empty($r['follow_up_notes'])) { $followUpDisplay .= ' - ' . htmlspecialchars($r['follow_up_notes']); } } } ?> <tr> <td><?php echo date('M d, Y h:i A', strtotime($r['created_at'])); ?></td> <td><?php echo htmlspecialchars($r['first_name'].' '.$r['last_name']); ?></td> <td><?php echo htmlspecialchars($r['doctor_name']); ?></td> <td><?php echo nl2br(htmlspecialchars($r['diagnosis'])); ?></td> <td><?php echo nl2br(htmlspecialchars($r['plan'])); ?></td> <td><?php echo $followUpDisplay ? htmlspecialchars($followUpDisplay) : ''; ?></td> <td> <button type="button" class="btn btn-sm btn-info text-white view-consult-btn" data-id="<?php echo $r['id']; ?>">View</button> <a href="print_consultation.php?id=<?php echo $r['id']; ?>" class="btn btn-sm btn-primary ms-1" target="_blank">Print</a> <button type="button" class="btn btn-sm btn-outline-primary ms-1" onclick="openRequestModal(<?php echo $r['patient_id']; ?>, '<?php echo htmlspecialchars(addslashes($r['first_name'].' '.$r['last_name'])); ?>', <?php echo $r['doctor_id']; ?>)">Request Lab</button> <?php if ($can_create_rx_from_consult): ?> <a href="consultation.php?tab=prescriptions&from_consultation_id=<?php echo $r['id']; ?>" class="btn btn-sm btn-success ms-1">Create Prescription</a> <?php endif; ?> <?php if ($is_admin): ?> <button type="button" class="btn btn-sm btn-warning edit-consult-btn ms-1" data-id="<?php echo $r['id']; ?>">Edit</button> <a href="delete_consultation.php?tab=records&id=<?php echo $r['id']; ?>" class="btn btn-sm btn-danger ms-1" onclick="return confirm('Delete this consultation record?');">Delete</a> <?php endif; ?> </td> </tr> <?php endforeach; ?> <?php if(empty($recent_records)): ?> <tr><td colspan="7" class="text-center text-muted">No records yet.</td></tr> <?php endif; ?> </tbody> </table> </div> </div> </div> <?php endif; ?> <!-- Add Consultation Modal --> <div class="modal fade" id="consultationModal" tabindex="-1"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <form method="POST"> <input type="hidden" name="edit_id" id="edit_consultation_id"> <div class="modal-header"> <h5 class="modal-title">Add Consultation Record</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div id="consultationModalError" class="alert alert-danger d-none mb-3"></div> <div class="row"> <div class="col-md-6 mb-3"> <label class="form-label">Patient</label> <select name="patient_id" class="form-select select2-modal" required> <option value="">Select Patient</option> <?php foreach($patients as $p): ?> <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['first_name'].' '.$p['last_name'].' ('.$p['patient_code'].')'); ?></option> <?php endforeach; ?> </select> <small class="text-muted">Use the search bar above to narrow the patient list.</small> </div> <div class="col-md-6 mb-3"> <label class="form-label">Doctor</label> <?php $preselected_doctor_id = $current_doctor_id; if (!$preselected_doctor_id && isset($_GET['doctor_id'])) { $preselected_doctor_id = (int)$_GET['doctor_id']; } ?> <select name="doctor_id" class="form-select select2-modal" <?php echo $current_doctor_id ? 'disabled' : 'required'; ?>> <option value="">Select Doctor</option> <?php foreach($doctors as $d): ?> <option value="<?php echo $d['id']; ?>" <?php echo ($preselected_doctor_id && $preselected_doctor_id == $d['id']) ? 'selected' : ''; ?>> <?php echo htmlspecialchars($d['name']); ?> </option> <?php endforeach; ?> </select> <?php if($current_doctor_id): ?> <input type="hidden" name="doctor_id" value="<?php echo $current_doctor_id; ?>"> <?php endif; ?> </div> </div> <!-- Patient Clinical History Section --> <div id="patient-history-container" class="mt-4" style="display: none;"> <h5 class="mb-3 text-secondary">Patient Clinical History</h5> <div id="history-loader" class="text-center py-4"> <div class="spinner-border text-primary" role="status"></div> <p class="mt-2">Loading history...</p> </div> <div id="history-content" style="display: none;"> <ul class="nav nav-tabs" id="history-tabs" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="lab-history-tab" data-bs-toggle="tab" data-bs-target="#lab-history" type="button" role="tab">Lab/Imaging Results</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="consult-history-tab" data-bs-toggle="tab" data-bs-target="#consult-history" type="button" role="tab">Consultation History</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="rx-history-tab" data-bs-toggle="tab" data-bs-target="#rx-history" type="button" role="tab">Prescription History</button> </li> </ul> <div class="tab-content border border-top-0 p-3" id="history-tabs-content"> <div class="tab-pane fade show active" id="lab-history" role="tabpanel"> <!-- Lab results will be populated here --> </div> <div class="tab-pane fade" id="consult-history" role="tabpanel"> <!-- Consultation history will be populated here --> </div> <div class="tab-pane fade" id="rx-history" role="tabpanel"> <!-- Prescription history will be populated here --> </div> </div> </div> <div id="history-error" class="alert alert-warning" style="display: none;"></div> </div> <div class="row"> <div class="col-md-6 mb-3"> <label class="form-label">Chief Complaint</label> <select id="chief_complaint_select" class="form-select mb-2"> <option value="">Select common complaint</option> <?php foreach($chief_complaint_options as $opt): ?> <option value="<?php echo htmlspecialchars($opt); ?>"><?php echo htmlspecialchars($opt); ?></option> <?php endforeach; ?> <option value="_other">Other (specify)</option> </select> <textarea name="chief_complaint" id="chief_complaint_input" class="form-control" rows="2" placeholder="Enter chief complaint"></textarea> </div> <div class="col-md-6 mb-3"> <label class="form-label">History</label> <div id="history-picker" class="mb-2" style="display:none;"> <select id="history_template_select" class="form-select form-select-sm"> <option value="">Use recent history (optional)...</option> </select> <div id="history-picker-empty" class="form-text text-muted" style="display:none;">No previous history found. Type manually.</div> </div> <textarea name="history" class="form-control" rows="2"></textarea> </div> </div> <div class="row"> <div class="col-md-6 mb-3"> <label class="form-label">Findings</label> <textarea name="findings" class="form-control" rows="3"></textarea> </div> <div class="col-md-6 mb-3"> <label class="form-label">Diagnosis</label> <textarea name="diagnosis" class="form-control" rows="3"></textarea> </div> </div> <div class="mb-3"> <label class="form-label">Plan</label> <textarea name="plan" class="form-control" rows="3"></textarea> </div> <div class="row"> <div class="col-md-4 mb-3"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="follow_up_check" name="has_follow_up" value="1"> <label class="form-check-label" for="follow_up_check">Follow-up?</label> </div> </div> </div> <div class="row" id="follow_up_section" style="display:none;"> <div class="col-md-4 mb-3"> <label class="form-label">Follow-up schedule</label> <select name="follow_up_preset" id="follow_up_preset" class="form-select"> <option value="">Select schedule</option> <option value="1">After 1 day</option> <option value="3">After 3 days</option> <option value="5">After 5 days</option> <option value="7">After 7 days</option> <option value="14">After 2 weeks (14 days)</option> <option value="30">After 1 month (30 days)</option> </select> </div> <div class="col-md-4 mb-3"> <label class="form-label">Or enter days</label> <input type="number" name="follow_up_days" id="follow_up_days" class="form-control" min="1" placeholder="Number of days"> </div> <div class="col-md-4 mb-3"> <label class="form-label">Follow-up notes</label> <input type="text" name="follow_up_notes" class="form-control" placeholder="Optional details"> </div> </div> <div class="row"> <div class="col-md-4 mb-3"> <label class="form-label">Invoice #</label> <input type="number" name="invoice_id" class="form-control" placeholder="Optional"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-success">Save Record</button> </div> </form> </div> </div> </div> <div class="modal fade" id="viewConsultModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Consultation Details</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="viewConsultModalBody"> <div class="text-center py-3"><div class="spinner-border text-primary" role="status"></div></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="resultOverviewModal" tabindex="-1"> <div class="modal-dialog modal-lg modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <div> <h5 class="modal-title" id="resultOverviewTitle">Result Overview</h5> <div class="small text-muted" id="resultOverviewMeta"></div> </div> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="resultOverviewBody"></div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <style> #lab-history .result-badge { max-width: 320px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.75rem; padding: 0.35rem 0.6rem; } #lab-history .lab-history-table th, #lab-history .lab-history-table td { vertical-align: middle; } #lab-history .result-lines { max-width: 320px; display: inline-block; text-align: left; font-size: 0.8rem; line-height: 1.25; } #lab-history .result-lines .result-line { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #lab-history .result-box { max-width: 320px; display: inline-block; background: #198754; color: #fff; border-radius: 12px; padding: 0.35rem 0.6rem; font-size: 0.78rem; line-height: 1.25; text-align: left; } #lab-history .result-box .result-line { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #lab-history .result-box .result-more { color: rgba(255, 255, 255, 0.85); } #resultOverviewModal .table td, #resultOverviewModal .table th { vertical-align: top; } #resultOverviewModal .ref-range div { line-height: 1.25; margin-bottom: 2px; } #resultOverviewModal .ref-range div:last-child { margin-bottom: 0; } </style> <?php if (!empty($doctor_due_followups)): ?> <div class="modal fade" id="followupAlertModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Today's Follow-up Schedule</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="table-responsive"> <table class="table table-bordered table-hover mb-0"> <thead> <tr> <th>Follow-up Date</th> <th>Patient</th> <th>Diagnosis</th> <th>Follow-up Notes</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($doctor_due_followups as $fu): ?> <tr> <td><?php echo htmlspecialchars($fu['follow_up_date']); ?></td> <td><?php echo htmlspecialchars($fu['patient_name']); ?></td> <td><?php echo nl2br(htmlspecialchars($fu['diagnosis'])); ?></td> <td><?php echo htmlspecialchars($fu['follow_up_notes']); ?></td> <td> <button type="button" class="btn btn-sm btn-info text-white view-consult-btn" data-id="<?php echo $fu['id']; ?>">Open Consultation</button> <a href="mark_followup_done.php?id=<?php echo $fu['id']; ?>&redirect=consultation_followups" class="btn btn-sm btn-success ms-1" onclick="return confirm('Mark this follow-up as done?');">Mark Done</a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <?php endif; ?> <?php if ($tab === 'followups' && $can_followups): ?> <div class="d-flex justify-content-between align-items-center mb-3"> <h5 class="mb-0">Patients for Follow-up</h5> </div> <div class="card"> <div class="card-header"> <div class="d-flex justify-content-between align-items-center"> <span>Follow-up Schedule</span> <div class="ms-auto" style="max-width:260px;"> <input type="text" id="followupSearch" class="form-control form-control-sm" placeholder="Search follow-ups..."> </div> </div> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="followupTable"> <thead> <tr> <th>Follow-up Date</th> <th>Patient</th> <th>Doctor</th> <th>Diagnosis</th> <th>Follow-up Notes</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($followup_records as $fr): ?> <?php if (empty($fr['follow_up_days'])) { continue; } $baseDate = !empty($fr['consultation_date']) ? $fr['consultation_date'] : $fr['created_at']; $followTs = strtotime($baseDate . ' +' . intval($fr['follow_up_days']) . ' days'); if (!$followTs) { continue; } $followDateStr = date('M d, Y', $followTs); ?> <tr> <td><?php echo $followDateStr; ?></td> <td><?php echo htmlspecialchars(($fr['first_name'] ?? '') . ' ' . ($fr['last_name'] ?? '')); ?></td> <td><?php echo htmlspecialchars($fr['doctor_name'] ?? ''); ?></td> <td><?php echo nl2br(htmlspecialchars($fr['diagnosis'] ?? '')); ?></td> <td><?php echo htmlspecialchars($fr['follow_up_notes'] ?? ''); ?></td> <td> <button type="button" class="btn btn-sm btn-info text-white view-consult-btn" data-id="<?php echo $fr['id']; ?>">Open Consultation</button> <a href="mark_followup_done.php?id=<?php echo $fr['id']; ?>&redirect=consultation_followups" class="btn btn-sm btn-success ms-1" onclick="return confirm('Mark this follow-up as done?');">Mark Done</a> </td> </tr> <?php endforeach; ?> <?php if(empty($followup_records)): ?> <tr><td colspan="6" class="text-center text-muted">No follow-ups scheduled.</td></tr> <?php endif; ?> </tbody> </table> </div> </div> </div> <?php endif; ?> <?php if ($tab === 'prescriptions' && $can_prescriptions): ?> <?php $company = []; try { $cs = $pdo->query("SELECT * FROM company_settings LIMIT 1"); $company = $cs->fetch() ?: []; } catch (Exception $e) { $company = []; } $company_name = $company['company_name'] ?? 'Diagnostic Center'; $company_address = $company['company_address'] ?? ''; $company_logo = $company['company_logo'] ?? ''; $doctor_sig = ''; if (isset($_SESSION['user_id'])) { try { if (tableHasColumn($pdo, 'users', 'signature')) { $stmtU = $pdo->prepare("SELECT signature FROM users WHERE id = ?"); $stmtU->execute([$_SESSION['user_id']]); $doctor_sig = $stmtU->fetchColumn() ?: ''; } elseif (tableHasColumn($pdo, 'users', 'signature_path')) { $stmtU = $pdo->prepare("SELECT signature_path FROM users WHERE id = ?"); $stmtU->execute([$_SESSION['user_id']]); $doctor_sig = $stmtU->fetchColumn() ?: ''; } } catch (Exception $e) {} } ?> <div class="d-flex justify-content-between align-items-center mb-3"> <h5 class="mb-0">Prescriptions</h5> <?php if ($can_create_rx_from_consult): ?> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#rxModal"> Add Prescription </button> <?php endif; ?> </div> <div class="card"> <div class="card-header">Recent Prescriptions</div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead> <tr> <th>RX No</th> <th>Date</th> <th>Patient</th> <th>Doctor</th> <th>Prescription Overview</th> <th>Notes</th> <th>Action</th> </tr> </thead> <tbody> <?php $rx_items_stmt = $pdo->prepare("SELECT medicine_name, frequency FROM consultation_prescription_items WHERE prescription_id = ?"); ?> <?php foreach($recent_prescriptions as $rx): ?> <tr> <td><?php echo str_pad($rx['id'], 6, '0', STR_PAD_LEFT); ?></td> <td><?php echo date('M d, Y h:i A', strtotime($rx['created_at'])); ?></td> <td><?php echo htmlspecialchars($rx['first_name'].' '.$rx['last_name']); ?></td> <td><?php echo htmlspecialchars($rx['doctor_name']); ?></td> <td> <?php $rx_items_stmt->execute([$rx['id']]); $rx_items = $rx_items_stmt->fetchAll(); $overview = []; foreach ($rx_items as $item) { $name = $item['medicine_name'] ?? ''; if ($name === '') continue; $freq = $item['frequency'] ?? ''; if ($freq !== '') { $overview[] = htmlspecialchars($name) . ' - ' . htmlspecialchars($freq); } else { $overview[] = htmlspecialchars($name); } } echo implode('<br>', $overview); ?> </td> <td><?php echo htmlspecialchars($rx['notes']); ?></td> <td> <button type="button" class="btn btn-sm btn-info text-white view-rx-btn" data-id="<?php echo $rx['id']; ?>">View</button> <a href="print_prescription.php?id=<?php echo $rx['id']; ?>" class="btn btn-sm btn-primary" target="_blank">Print</a> <?php if ($can_create_rx_from_consult): ?> <a href="consultation.php?tab=prescriptions&edit_prescription_id=<?php echo $rx['id']; ?>" class="btn btn-sm btn-warning">Edit</a> <?php endif; ?> <?php if ($is_admin): ?> <a href="delete_consultation.php?tab=prescriptions&id=<?php echo $rx['id']; ?>" class="btn btn-sm btn-danger ms-1" onclick="return confirm('Delete this prescription?');">Delete</a> <?php endif; ?> </td> </tr> <?php endforeach; ?> <?php if(empty($recent_prescriptions)): ?> <tr><td colspan="7" class="text-center text-muted">No prescriptions yet.</td></tr> <?php endif; ?> </tbody> </table> </div> </div> <!-- Add/Edit Prescription Modal --> <div class="modal fade" id="rxModal" tabindex="-1"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <form method="POST" id="rxForm"> <div class="modal-header"> <h5 class="modal-title"><?php echo $edit_rx ? 'Edit Prescription' : 'Add Prescription'; ?></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <?php if($edit_rx): ?> <input type="hidden" name="edit_id" value="<?php echo $edit_rx['id']; ?>"> <?php endif; ?> <datalist id="medList"> <?php foreach($pharmacy_items as $pi): ?> <option value="<?php echo htmlspecialchars($pi['item_name']); ?>"> <?php endforeach; ?> </datalist> <datalist id="dosageList"> <option value="5mg"> <option value="10mg"> <option value="20mg"> <option value="250mg"> <option value="500mg"> <option value="1g"> <option value="5ml"> <option value="10ml"> <option value="1 tab"> <option value="1 cap"> </datalist> <datalist id="freqList"> <option value="OD (Once a day)"> <option value="BID (Twice a day)"> <option value="TID (Thrice a day)"> <option value="QID (Four times a day)"> <option value="HS (At bedtime)"> <option value="PRN (As needed)"> <option value="STAT (Immediately)"> <option value="Every 4 hours"> <option value="Every 6 hours"> <option value="Every 8 hours"> </datalist> <datalist id="durList"> <option value="3 days"> <option value="5 days"> <option value="7 days"> <option value="10 days"> <option value="14 days"> <option value="1 month"> </datalist> <div class="row"> <div class="col-md-6 mb-3"> <label class="form-label">Patient</label> <select name="patient_id" class="form-select select2" required> <option value="">Select Patient</option> <?php foreach($patients as $p): ?> <?php $sel = false; if ($edit_rx && $edit_rx['patient_id'] == $p['id']) { $sel = true; } elseif (!$edit_rx && $prefill_patient_id && $prefill_patient_id == $p['id']) { $sel = true; } ?> <option value="<?php echo $p['id']; ?>" <?php echo $sel ? 'selected' : ''; ?>> <?php echo htmlspecialchars($p['first_name'].' '.$p['last_name'].' ('.$p['patient_code'].')'); ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-6 mb-3"> <label class="form-label">Doctor</label> <select name="doctor_id" class="form-select select2" <?php echo $current_doctor_id ? 'disabled' : ''; ?>> <option value="">Select Doctor</option> <?php foreach($doctors as $d): ?> <?php $sel = false; if (($current_doctor_id && $current_doctor_id == $d['id']) || ($edit_rx && $edit_rx['doctor_id'] == $d['id'])) { $sel = true; } elseif (!$edit_rx && !$current_doctor_id && $prefill_doctor_id && $prefill_doctor_id == $d['id']) { $sel = true; } ?> <option value="<?php echo $d['id']; ?>" <?php echo $sel ? 'selected' : ''; ?>> <?php echo htmlspecialchars($d['name']); ?> </option> <?php endforeach; ?> </select> <?php if($current_doctor_id): ?> <input type="hidden" name="doctor_id" value="<?php echo $current_doctor_id; ?>"> <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-4 mb-3"> <label class="form-label">Consultation Record</label> <select name="consultation_id" class="form-select select2"> <option value="">None</option> <?php foreach($recent_records as $r): ?> <?php $sel = false; if ($edit_rx && $edit_rx['consultation_id'] == $r['id']) { $sel = true; } elseif (!$edit_rx && $prefill_consult && $prefill_consult['id'] == $r['id']) { $sel = true; } ?> <option value="<?php echo $r['id']; ?>" data-patient-id="<?php echo $r['patient_id']; ?>" data-patient-name="<?php echo htmlspecialchars($r['first_name'].' '.$r['last_name']); ?>" data-doctor-id="<?php echo $r['doctor_id']; ?>" data-doctor-name="<?php echo htmlspecialchars($r['doctor_name']); ?>" <?php echo $sel ? 'selected' : ''; ?> > <?php echo date('M d, Y', strtotime($r['created_at'])).' - '.htmlspecialchars($r['first_name'].' '.$r['last_name']); ?> </option> <?php endforeach; ?> </select> </div> <div class="col-md-4 mb-3"> <label class="form-label">Invoice #</label> <input type="number" name="invoice_id" class="form-control" placeholder="Optional" value="<?php echo $edit_rx['invoice_id'] ?? ''; ?>"> </div> <div class="col-md-4 mb-3"> <label class="form-label">Notes</label> <input type="text" name="notes" class="form-control" placeholder="" value="<?php echo htmlspecialchars($edit_rx['notes'] ?? ''); ?>"> </div> </div> <div class="mb-3"> <div class="d-flex justify-content-between align-items-center"> <label class="form-label">Medicines</label> <button type="button" class="btn btn-sm btn-secondary" onclick="addItemRow()">Add Item</button> </div> <div class="table-responsive"> <table class="table table-bordered align-middle" id="itemsTable"> <thead> <tr> <th>Medicine</th> <th>Dosage</th> <th>Frequency</th> <th>Duration</th> <th>Instructions</th> <th>Action</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> <div class="modal-footer"> <?php if($edit_rx): ?> <a href="consultation.php?tab=prescriptions" class="btn btn-outline-secondary">Cancel Edit</a> <?php endif; ?> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-success">Save Prescription</button> </div> </form> </div> </div> </div> <!-- View Prescription Modal --> <div class="modal fade" id="viewRxModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Prescription Details</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="viewRxModalBody"> <div class="text-center py-3"><div class="spinner-border text-primary" role="status"></div></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <?php endif; ?> <script> function addItemRow(data = null) { const tbody = document.querySelector('#itemsTable tbody'); if (!tbody) return; const tr = document.createElement('tr'); const idx = Date.now() + Math.floor(Math.random() * 1000); tr.innerHTML = ` <td><input type="text" name="items[${idx}][medicine_name]" class="form-control" list="medList" required></td> <td><input type="text" name="items[${idx}][dosage]" class="form-control" list="dosageList"></td> <td><input type="text" name="items[${idx}][frequency]" class="form-control" list="freqList"></td> <td><input type="text" name="items[${idx}][duration]" class="form-control" list="durList"></td> <td><input type="text" name="items[${idx}][instructions]" class="form-control"></td> <td><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()">Remove</button></td> `; if (data) { tr.querySelector('input[name*="[medicine_name]"]').value = data.medicine_name || ''; tr.querySelector('input[name*="[dosage]"]').value = data.dosage || ''; tr.querySelector('input[name*="[frequency]"]').value = data.frequency || ''; tr.querySelector('input[name*="[duration]"]').value = data.duration || ''; tr.querySelector('input[name*="[instructions]"]').value = data.instructions || ''; } tbody.appendChild(tr); } document.addEventListener('DOMContentLoaded', function() { const consultServerError = <?php echo json_encode(($tab === 'records') ? ($error ?: '') : ''); ?>; const consultWasPost = <?php echo json_encode($_SERVER['REQUEST_METHOD'] === 'POST' && $tab === 'records'); ?>; const consultPost = <?php echo json_encode(($_SERVER['REQUEST_METHOD'] === 'POST' && $tab === 'records') ? [ 'patient_id' => $_POST['patient_id'] ?? '', 'doctor_id' => $_POST['doctor_id'] ?? '', 'chief_complaint' => $_POST['chief_complaint'] ?? '', 'history' => $_POST['history'] ?? '', 'findings' => $_POST['findings'] ?? '', 'diagnosis' => $_POST['diagnosis'] ?? '', 'plan' => $_POST['plan'] ?? '', 'invoice_id' => $_POST['invoice_id'] ?? '', 'has_follow_up' => !empty($_POST['has_follow_up']), 'follow_up_preset' => $_POST['follow_up_preset'] ?? '', 'follow_up_days' => $_POST['follow_up_days'] ?? '', 'follow_up_notes' => $_POST['follow_up_notes'] ?? '' ] : null); ?>; <?php if(!empty($edit_items)): ?> const items = <?php echo json_encode($edit_items); ?>; if (items.length > 0) { items.forEach(item => addItemRow(item)); } else { addItemRow(); } <?php else: ?> addItemRow(); <?php endif; ?> // --- Patient History Loader --- let patientHistoryCache = null; function loadPatientHistory(patientId) { const container = $('#patient-history-container'); const loader = $('#history-loader'); const content = $('#history-content'); const errorDiv = $('#history-error'); container.show(); loader.show(); content.hide(); errorDiv.hide(); $.ajax({ url: 'api_get_patient_history.php', data: { patient_id: patientId }, dataType: 'json', success: function(data) { loader.hide(); if (data.status === 'success') { patientHistoryCache = data; renderHistory(data); setUpHistoryPicker(data.consultations); content.show(); } else { errorDiv.text(data.message || 'Could not load patient history.').show(); } }, error: function() { loader.hide(); errorDiv.text('An error occurred while fetching patient history.').show(); } }); } function renderHistory(data) { // 1. Lab Results const labTab = $('#lab-history'); let labHtml = ''; if (data.lab_results && data.lab_results.length > 0) { labHtml += ` <div class="table-responsive"> <table class="table table-sm table-hover align-middle mb-0 lab-history-table"> <thead class="table-light"> <tr> <th>Test</th> <th style="width: 140px;">Date</th> <th class="text-end" style="width: 280px;">Result</th> <th style="width: 90px;">Action</th> </tr> </thead> <tbody> `; data.lab_results.forEach(r => { const dt = new Date(r.result_date); const dateStr = isNaN(dt.getTime()) ? '' : dt.toLocaleDateString(); const displayFull = (r.result_display || r.result_value || 'View'); const decodedInline = tryParseJson(r.result_value); let resultCell = ''; const lines = []; if (Array.isArray(decodedInline) && decodedInline.length > 0) { for (let i = 0; i < decodedInline.length && i < 3; i++) { const comp = decodedInline[i]; const name = String(comp?.name ?? '').trim(); const val = String(comp?.result ?? '').trim(); if (!name && !val) continue; lines.push(`${name ? name + ': ' : ''}${val}`); } } if (lines.length === 0) { lines.push(clampText(displayFull, 42)); } const hasMore = Array.isArray(decodedInline) && decodedInline.length > 3; const title = escapeHtml( (Array.isArray(decodedInline) && decodedInline.length > 0) ? decodedInline .map(comp => { const name = String(comp?.name ?? '').trim(); const val = String(comp?.result ?? '').trim(); if (!name && !val) return ''; return `${name ? name + ': ' : ''}${val}`; }) .filter(Boolean) .join('\n') : String(displayFull ?? '') ); resultCell = ` <div class="d-flex justify-content-end"> <div class="result-box" title="${title}"> ${lines.map(l => `<div class="result-line">${escapeHtml(l)}</div>`).join('')} ${hasMore ? `<div class="result-line result-more">…</div>` : ''} </div> </div> `; labHtml += ` <tr> <td> <div class="fw-bold text-danger">${r.test_name || ''} <span class="fw-normal text-muted">(${r.category || ''})</span></div> </td> <td class="text-muted">${dateStr}</td> <td class="text-end"> ${resultCell} </td> <td> <button type="button" class="btn btn-sm btn-outline-primary view-result-overview" data-result-id="${r.id}">View</button> </td> </tr> `; }); labHtml += ` </tbody> </table> </div> `; } else { labHtml += '<p class="text-muted p-3">No recent lab/imaging results found.</p>'; } labTab.html(labHtml); // 2. Consultation History const consultTab = $('#consult-history'); let consultHtml = '<div class="accordion accordion-flush" id="consult-accordion">'; if (data.consultations && data.consultations.length > 0) { data.consultations.forEach((c, index) => { consultHtml += ` <div class="accordion-item"> <h2 class="accordion-header" id="consult-heading-${index}"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#consult-collapse-${index}"> <strong>${new Date(c.consultation_date).toLocaleDateString()}</strong> - ${c.chief_complaint || 'General Check-up'} </button> </h2> <div id="consult-collapse-${index}" class="accordion-collapse collapse" data-bs-parent="#consult-accordion"> <div class="accordion-body"> <p><strong>Doctor:</strong> ${c.doctor_name || 'N/A'}</p> <p><strong>Findings:</strong><br>${c.findings || 'N/A'}</p> <p><strong>Diagnosis:</strong><br>${c.diagnosis || 'N/A'}</p> </div> </div> </div>`; }); } else { consultHtml += '<p class="text-muted p-3">No consultation history found.</p>'; } consultHtml += '</div>'; consultTab.html(consultHtml); // 3. Prescription History const rxTab = $('#rx-history'); let rxHtml = '<div class="accordion accordion-flush" id="rx-accordion">'; if (data.consultations && data.consultations.length > 0) { let hasRx = false; data.consultations.forEach((c, index) => { const rxs = data.prescriptions[c.id]; if (rxs && rxs.length > 0) { hasRx = true; rxHtml += ` <div class="accordion-item"> <h2 class="accordion-header" id="rx-heading-${index}"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#rx-collapse-${index}"> <strong>${new Date(c.consultation_date).toLocaleDateString()}</strong> - ${rxs.length} item(s) </button> </h2> <div id="rx-collapse-${index}" class="accordion-collapse collapse" data-bs-parent="#rx-accordion"> <div class="accordion-body"> <ul class="list-unstyled">`; rxs.forEach(rx => { rxHtml += `<li><strong>${rx.medicine_name}</strong> - ${rx.dosage}, ${rx.frequency} for ${rx.duration}</li>`; }); rxHtml += ` </ul> </div> </div> </div>`; } }); if (!hasRx) { rxHtml += '<p class="text-muted p-3">No prescription history found.</p>'; } } else { rxHtml += '<p class="text-muted p-3">No prescription history found.</p>'; } rxHtml += '</div>'; rxTab.html(rxHtml); } function setUpHistoryPicker(consultations) { const picker = $('#history-picker'); const select = $('#history_template_select'); const emptyMsg = $('#history-picker-empty'); const historyTa = $('#consultationModal textarea[name="history"]'); select.empty().append(new Option('Use recent history (optional)...', '')); emptyMsg.hide(); picker.show(); const usable = (Array.isArray(consultations) ? consultations : []) .filter(c => String(c?.history ?? '').trim() !== ''); if (usable.length === 0) { emptyMsg.show(); return; } usable.forEach(c => { const dtRaw = c.consultation_date || c.created_at || ''; const dt = new Date(dtRaw); const labelDate = isNaN(dt.getTime()) ? String(dtRaw) : dt.toLocaleDateString(); const cc = String(c.chief_complaint || '').trim(); const label = `${labelDate}${cc ? ' - ' + cc : ''}`; const opt = new Option(label, String(c.id || '')); opt.dataset.history = String(c.history || ''); select.append(opt); }); const isEditing = String($('#edit_consultation_id').val() || '').trim() !== ''; const current = String(historyTa.val() || '').trim(); if (!isEditing && current === '') { const first = select.find('option').eq(1); if (first.length) { const h = String(first[0].dataset.history || ''); if (h.trim() !== '') { historyTa.val(h); select.val(first.val()); } } } } // --- Event Listeners --- $('#consultationModal select[name="patient_id"]').on('change', function() { const patientId = $(this).val(); $('#history_template_select').val(''); $('#history-picker-empty').hide(); if (patientId) { loadPatientHistory(patientId); } else { $('#patient-history-container').hide(); } }); $('#history_template_select').on('change', function() { const sel = this.options[this.selectedIndex]; const historyTa = $('#consultationModal textarea[name="history"]'); const h = sel && sel.dataset ? String(sel.dataset.history || '') : ''; if (String($(this).val() || '') === '') { return; } if (h.trim() !== '') { historyTa.val(h); historyTa.focus(); } }); function escapeHtml(value) { return String(value ?? '').replace(/[&<>"']/g, function (m) { return ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]); }); } function normalizeKey(value) { return String(value ?? '').toLowerCase().replace(/[^a-z0-9]+/g, ''); } function clampText(value, maxLen) { const s = String(value ?? ''); if (s.length <= maxLen) return s; return s.slice(0, Math.max(0, maxLen - 1)) + '…'; } function formatRefRange(value) { const raw = String(value ?? '').trim(); if (raw === '' || raw.toLowerCase() === '[dropdown]' || raw.toLowerCase().includes('dropdown')) { return '<span class="text-muted">—</span>'; } const norm = raw.replace(/\r\n/g, '\n'); let parts = []; if ((norm.includes('M:') || norm.includes('m:')) && (norm.includes('F:') || norm.includes('f:')) && norm.includes('/')) { parts = norm.split('/').map(s => s.trim()).filter(Boolean); } else if (norm.includes('\n')) { parts = norm.split('\n').map(s => s.trim()).filter(Boolean); } else { parts = [norm]; } return parts.map(p => `<div>${escapeHtml(p)}</div>`).join(''); } function tryParseJson(value) { if (typeof value !== 'string') return null; const s = value.trim(); if (s === '' || (s[0] !== '[' && s[0] !== '{')) return null; try { return JSON.parse(s); } catch (e) { return null; } } $(document).off('click.viewResultOverview').on('click.viewResultOverview', '.view-result-overview', function() { const id = String($(this).data('result-id') ?? ''); const rows = patientHistoryCache && Array.isArray(patientHistoryCache.lab_results) ? patientHistoryCache.lab_results : []; const r = rows.find(x => String(x.id) === id); if (!r) return; $('#resultOverviewTitle').text(`${r.test_name || 'Result'}${r.category ? ' (' + r.category + ')' : ''}`); const dt = new Date(r.result_date); $('#resultOverviewMeta').text(isNaN(dt.getTime()) ? '' : dt.toLocaleString()); const rvRaw = r.result_value ?? ''; const decoded = tryParseJson(rvRaw); let body = ''; const impression = (r.impression ?? '').toString().trim(); const remarks = (r.remarks ?? '').toString().trim(); const unit = (r.unit ?? '').toString().trim(); const normalRange = (r.normal_range ?? '').toString().trim(); const testType = (r.test_type ?? '').toString().trim(); if (Array.isArray(decoded)) { body += ` <div class="table-responsive"> <table class="table table-sm table-bordered align-middle mb-3"> <thead class="table-light"> <tr> <th>Component</th> <th style="width: 120px;">Result</th> <th style="width: 120px;">Unit</th> <th>Range</th> </tr> </thead> <tbody> `; decoded.forEach(comp => { const rawName = (comp?.name ?? ''); const key = normalizeKey(rawName); const tmpl = (r.components_meta && key && r.components_meta[key]) ? r.components_meta[key] : null; const name = escapeHtml(String(rawName || (tmpl?.name ?? ''))); const val = escapeHtml(comp?.result ?? ''); const unitRaw = String(comp?.unit ?? '').trim() || String(tmpl?.unit ?? '').trim(); const u = unitRaw ? escapeHtml(unitRaw) : ''; let rangeRaw = String(comp?.range ?? '').trim(); if (rangeRaw.toLowerCase() === '[dropdown]' || rangeRaw.toLowerCase().includes('dropdown')) { rangeRaw = ''; } if (!rangeRaw) { rangeRaw = String(tmpl?.range_display ?? '').trim(); } const rangeHtml = formatRefRange(rangeRaw); body += `<tr><td>${name}</td><td class="fw-bold">${val}</td><td>${u || '<span class="text-muted">—</span>'}</td><td class="ref-range">${rangeHtml}</td></tr>`; }); body += ` </tbody> </table> </div> `; } else { const display = escapeHtml(r.result_display || (typeof rvRaw === 'string' ? rvRaw.trim() : '') || 'View'); const u = unit ? ` <span class="text-muted">${escapeHtml(unit)}</span>` : ''; const range = normalRange ? `<div class="small text-muted mt-1">Range: ${escapeHtml(normalRange)}</div>` : ''; body += `<div class="fs-5 fw-bold mb-1">${display}${u}</div>${range}`; } if (impression !== '') { body += `<div class="mt-3"><div class="fw-bold">Impression</div><div>${escapeHtml(impression).replace(/\n/g, '<br>')}</div></div>`; } if (remarks !== '') { body += `<div class="mt-3"><div class="fw-bold">Remarks</div><div>${escapeHtml(remarks).replace(/\n/g, '<br>')}</div></div>`; } const atts = tryParseJson(r.attachments ?? ''); if (Array.isArray(atts) && atts.length > 0) { body += `<div class="mt-3"><div class="fw-bold">Attachments</div><div class="d-flex flex-wrap gap-2 mt-2">`; atts.forEach(f => { const file = String(f ?? '').trim(); if (!file) return; const href = `uploads/results/${encodeURIComponent(file)}`; const ext = file.split('.').pop().toLowerCase(); if (['jpg','jpeg','png','webp','gif'].includes(ext)) { body += `<a href="${href}" target="_blank"><img src="${href}" class="img-thumbnail" style="max-height: 120px;"></a>`; } else { body += `<a href="${href}" target="_blank" class="btn btn-sm btn-outline-secondary">${escapeHtml(file)}</a>`; } }); body += `</div></div>`; } else if (testType === 'Imaging' && (typeof rvRaw !== 'string' || rvRaw.trim() === '')) { body += `<div class="mt-3 text-muted">No attachment found.</div>`; } $('#resultOverviewBody').html(body); if (window.bootstrap) { new bootstrap.Modal(document.getElementById('resultOverviewModal')).show(); } }); var searchInput = document.getElementById('consultationSearch'); var table = document.getElementById('consultationTable'); if (searchInput && table) { searchInput.addEventListener('keyup', function() { var filter = searchInput.value.toLowerCase(); var rows = table.querySelectorAll('tbody tr'); rows.forEach(function(row) { var text = row.textContent.toLowerCase(); row.style.display = text.indexOf(filter) > -1 ? '' : 'none'; }); }); } var followSearch = document.getElementById('followupSearch'); var followTable = document.getElementById('followupTable'); if (followSearch && followTable) { followSearch.addEventListener('keyup', function() { var filter = followSearch.value.toLowerCase(); var rows = followTable.querySelectorAll('tbody tr'); rows.forEach(function(row) { var text = row.textContent.toLowerCase(); row.style.display = text.indexOf(filter) > -1 ? '' : 'none'; }); }); } var ccSelect = document.getElementById('chief_complaint_select'); var ccInput = document.getElementById('chief_complaint_input'); if (ccSelect && ccInput) { ccSelect.addEventListener('change', function() { var val = ccSelect.value; if (val && val !== '_other') { ccInput.value = val; ccInput.focus(); } else if (val === '_other') { if (!ccInput.value) { ccInput.value = ''; } ccInput.focus(); } }); } if (window.jQuery && window.jQuery.fn && window.jQuery.fn.select2) { var jq = window.jQuery; if (jq('.select2').length) { jq('.select2').select2({ width: '100%', dropdownParent: jq('#rxModal').length ? jq('#rxModal') : jq('body') }); } if (jq('.select2-modal').length) { jq('#consultationModal').on('shown.bs.modal', function () { jq('.select2-modal').each(function() { if (!jq(this).data('select2')) { jq(this).select2({ dropdownParent: jq('#consultationModal'), width: '100%' }); } }); }); } var rxModalEl = document.getElementById('rxModal'); if (rxModalEl) { var patientSelect = rxModalEl.querySelector('select[name="patient_id"]'); var doctorSelect = rxModalEl.querySelector('select[name="doctor_id"]'); var consultSelect = rxModalEl.querySelector('select[name="consultation_id"]'); if (consultSelect && patientSelect && doctorSelect) { jq(consultSelect).on('change.select2', function () { var opt = consultSelect.options[consultSelect.selectedIndex]; if (!opt || !opt.dataset) return; var patientId = opt.dataset.patientId || ''; var doctorId = opt.dataset.doctorId || ''; if (patientId) { patientSelect.value = patientId; jq(patientSelect).trigger('change.select2'); } if (doctorId) { doctorSelect.value = doctorId; jq(doctorSelect).trigger('change.select2'); } }); if (consultSelect.value) { jq(consultSelect).trigger('change.select2'); } } } } <?php if ($tab === 'prescriptions' && $can_prescriptions && $can_create_rx_from_consult && (isset($_GET['edit_prescription_id']) || isset($_GET['from_consultation_id']))): ?> if (window.bootstrap && document.getElementById('rxModal')) { var rxModal = new bootstrap.Modal(document.getElementById('rxModal')); rxModal.show(); } <?php endif; ?> var followCheck = document.getElementById('follow_up_check'); var followSection = document.getElementById('follow_up_section'); var followPreset = document.getElementById('follow_up_preset'); var followDays = document.getElementById('follow_up_days'); var followNotes = document.querySelector('input[name="follow_up_notes"]'); if (followCheck && followSection) { followCheck.addEventListener('change', function() { if (this.checked) { followSection.style.display = ''; } else { followSection.style.display = 'none'; if (followPreset) { followPreset.value = ''; } if (followDays) { followDays.value = ''; followDays.readOnly = false; } if (followNotes) { followNotes.value = ''; } } }); } if (followPreset && followDays) { followPreset.addEventListener('change', function() { var v = this.value; if (v && v !== 'custom') { followDays.value = v; followDays.readOnly = true; } else { followDays.value = ''; followDays.readOnly = false; } }); } // Auto-fill doctor based on patient schedule if (window.jQuery) { window.jQuery('#consultationModal select[name="patient_id"]').on('change', function() { var patientId = window.jQuery(this).val(); // Only fetch if we are adding a new record (not editing), or check if edit_id is empty var editId = document.getElementById('edit_consultation_id').value; if (patientId && !editId) { fetch('get_patient_schedule.php?patient_id=' + patientId) .then(response => response.json()) .then(data => { if (data.success && data.doctor_id) { var doctorSelect = document.querySelector('#consultationModal select[name="doctor_id"]'); var $doctorSelect = window.jQuery(doctorSelect); // Only update if not disabled (e.g. if user is not a doctor restricted to own ID) if (!$doctorSelect.prop('disabled')) { $doctorSelect.val(data.doctor_id).trigger('change'); } } }) .catch(err => console.error('Error fetching schedule:', err)); } }); } document.querySelectorAll('.view-rx-btn').forEach(function(btn) { btn.addEventListener('click', function() { var id = this.getAttribute('data-id'); var modalBody = document.getElementById('viewRxModalBody'); modalBody.innerHTML = '<div class="text-center py-3"><div class="spinner-border text-primary" role="status"></div></div>'; var viewModal = new bootstrap.Modal(document.getElementById('viewRxModal')); viewModal.show(); fetch('get_prescription_details.php?id=' + id) .then(function(response) { return response.text(); }) .then(function(html) { modalBody.innerHTML = html; }) .catch(function(err) { modalBody.innerHTML = '<div class="alert alert-danger">Error loading details.</div>'; }); }); }); var params = new URLSearchParams(window.location.search); var createNew = params.get('create_new'); var patientId = params.get('patient_id'); var doctorId = params.get('doctor_id'); if (createNew == '1' && document.getElementById('consultationModal')) { var consultModal = new bootstrap.Modal(document.getElementById('consultationModal')); consultModal.show(); if (patientId) { var patientSelect = document.querySelector('#consultationModal select[name="patient_id"]'); if (patientSelect) { // If using Select2 if (window.jQuery && window.jQuery(patientSelect).data('select2')) { window.jQuery(patientSelect).val(patientId).trigger('change'); } else { patientSelect.value = patientId; } } } if (doctorId) { var doctorSelect = document.querySelector('#consultationModal select[name="doctor_id"]'); if (doctorSelect) { // If using Select2 if (window.jQuery && window.jQuery(doctorSelect).data('select2')) { window.jQuery(doctorSelect).val(doctorId).trigger('change'); } else { doctorSelect.value = doctorId; } } } } var autoViewId = params.get('auto_view'); if (autoViewId) { var autoBtn = document.querySelector('.view-rx-btn[data-id="' + autoViewId + '"]'); if (autoBtn) { autoBtn.click(); } } document.querySelectorAll('.view-consult-btn').forEach(function(btn) { btn.addEventListener('click', function() { var id = this.getAttribute('data-id'); var modalBody = document.getElementById('viewConsultModalBody'); modalBody.innerHTML = '<div class="text-center py-3"><div class="spinner-border text-primary" role="status"></div></div>'; var viewModal = new bootstrap.Modal(document.getElementById('viewConsultModal')); viewModal.show(); fetch('get_consultation_details.php?id=' + id) .then(function(response) { return response.text(); }) .then(function(html) { modalBody.innerHTML = html; }) .catch(function(err) { modalBody.innerHTML = '<div class="alert alert-danger">Error loading details.</div>'; }); }); }); document.querySelectorAll('.edit-consult-btn').forEach(function(btn) { btn.addEventListener('click', function() { var id = this.getAttribute('data-id'); var modalEl = document.getElementById('consultationModal'); var modal = new bootstrap.Modal(modalEl); fetch('get_consultation_json.php?id=' + id) .then(response => response.json()) .then(data => { if (data.error) { alert(data.error); return; } document.getElementById('edit_consultation_id').value = data.id; modalEl.querySelector('.modal-title').textContent = 'Edit Consultation Record'; // Set Patient var patientSelect = modalEl.querySelector('select[name="patient_id"]'); if (window.jQuery && window.jQuery(patientSelect).data('select2')) { window.jQuery(patientSelect).val(data.patient_id).trigger('change'); } else { patientSelect.value = data.patient_id; } // Set Doctor var doctorSelect = modalEl.querySelector('select[name="doctor_id"]'); if (window.jQuery && window.jQuery(doctorSelect).data('select2')) { window.jQuery(doctorSelect).val(data.doctor_id).trigger('change'); } else { doctorSelect.value = data.doctor_id; } // Set text areas modalEl.querySelector('textarea[name="chief_complaint"]').value = data.chief_complaint || ''; modalEl.querySelector('textarea[name="history"]').value = data.history || ''; modalEl.querySelector('textarea[name="findings"]').value = data.findings || ''; modalEl.querySelector('textarea[name="diagnosis"]').value = data.diagnosis || ''; modalEl.querySelector('textarea[name="plan"]').value = data.plan || ''; // Set Follow up var hasFollowUp = (data.follow_up_days && data.follow_up_days > 0); var check = document.getElementById('follow_up_check'); if (check) { check.checked = hasFollowUp; check.dispatchEvent(new Event('change')); } if (hasFollowUp) { var days = data.follow_up_days; var preset = document.getElementById('follow_up_preset'); var daysInput = document.getElementById('follow_up_days'); var found = false; if (preset) { for (var i = 0; i < preset.options.length; i++) { if (preset.options[i].value == days) { preset.value = days; found = true; break; } } if (!found) { preset.value = 'custom'; } preset.dispatchEvent(new Event('change')); } if (!found && daysInput) { daysInput.value = days; } var notesInput = modalEl.querySelector('input[name="follow_up_notes"]'); if (notesInput) notesInput.value = data.follow_up_notes || ''; } modal.show(); }) .catch(err => { console.error(err); alert('Error loading data'); }); }); }); var consultationModalEl = document.getElementById('consultationModal'); if (consultationModalEl) { consultationModalEl.addEventListener('hidden.bs.modal', function () { document.getElementById('edit_consultation_id').value = ''; consultationModalEl.querySelector('.modal-title').textContent = 'Add Consultation Record'; consultationModalEl.querySelector('form').reset(); var patientSelect = consultationModalEl.querySelector('select[name="patient_id"]'); if (window.jQuery && window.jQuery(patientSelect).data('select2')) { window.jQuery(patientSelect).val('').trigger('change'); } var doctorSelect = consultationModalEl.querySelector('select[name="doctor_id"]'); if (window.jQuery && window.jQuery(doctorSelect).data('select2')) { // Try to reset to initial value if possible, or just empty // Ideally we should store the initial value. // For now, let's just clear it, user can re-select. // Or better, check if there is a current_doctor_id input hidden var currentDocInput = consultationModalEl.querySelector('input[name="doctor_id"]'); // Only exists if disabled if (!currentDocInput) { window.jQuery(doctorSelect).val('').trigger('change'); } } var check = document.getElementById('follow_up_check'); if (check && check.checked) { check.checked = false; check.dispatchEvent(new Event('change')); } }); } var followupAlertEl = document.getElementById('followupAlertModal'); if (followupAlertEl && window.bootstrap) { var followupAlertModal = new bootstrap.Modal(followupAlertEl); followupAlertModal.show(); } function markSelect2Invalid(selectEl, invalid) { if (!selectEl) return; if (invalid) { selectEl.classList.add('is-invalid'); } else { selectEl.classList.remove('is-invalid'); } if (window.jQuery) { const jq = window.jQuery; const container = jq(selectEl).next('.select2'); if (container.length) { const sel = container.find('.select2-selection'); if (invalid) sel.addClass('is-invalid'); else sel.removeClass('is-invalid'); } } } function showConsultationModalError(msg, fields = []) { const errBox = document.getElementById('consultationModalError'); if (errBox) { errBox.textContent = msg || 'Please correct the highlighted fields.'; errBox.classList.remove('d-none'); } const modalEl = document.getElementById('consultationModal'); if (!modalEl) return; const patientSel = modalEl.querySelector('select[name="patient_id"]'); const doctorSel = modalEl.querySelector('select[name="doctor_id"]'); markSelect2Invalid(patientSel, fields.includes('patient_id')); markSelect2Invalid(doctorSel, fields.includes('doctor_id')); const textFields = ['chief_complaint', 'history', 'findings', 'diagnosis', 'plan', 'invoice_id']; textFields.forEach(name => { const el = modalEl.querySelector(`[name="${name}"]`); if (!el) return; if (fields.includes(name)) el.classList.add('is-invalid'); else el.classList.remove('is-invalid'); }); } function inferErrorFields(msg) { const m = String(msg || '').toLowerCase(); const fields = []; if (m.includes('select a patient')) fields.push('patient_id'); if (m.includes('select a doctor')) fields.push('doctor_id'); if (m.includes('already exists')) { fields.push('patient_id'); fields.push('doctor_id'); } return fields; } if (consultWasPost && consultServerError) { const modalEl = document.getElementById('consultationModal'); if (modalEl && window.bootstrap) { const consultModal = new bootstrap.Modal(modalEl); consultModal.show(); if (consultPost) { const setVal = (selector, value) => { const el = modalEl.querySelector(selector); if (!el) return; if (window.jQuery && window.jQuery(el).data('select2')) { window.jQuery(el).val(value).trigger('change'); } else { el.value = value; } }; setVal('select[name="patient_id"]', consultPost.patient_id); setVal('select[name="doctor_id"]', consultPost.doctor_id); const ccInput = modalEl.querySelector('#chief_complaint_input'); if (ccInput) ccInput.value = consultPost.chief_complaint || ''; const taHistory = modalEl.querySelector('textarea[name="history"]'); if (taHistory) taHistory.value = consultPost.history || ''; const taFindings = modalEl.querySelector('textarea[name="findings"]'); if (taFindings) taFindings.value = consultPost.findings || ''; const taDx = modalEl.querySelector('textarea[name="diagnosis"]'); if (taDx) taDx.value = consultPost.diagnosis || ''; const taPlan = modalEl.querySelector('textarea[name="plan"]'); if (taPlan) taPlan.value = consultPost.plan || ''; const inv = modalEl.querySelector('input[name="invoice_id"]'); if (inv) inv.value = consultPost.invoice_id || ''; const followCheck = document.getElementById('follow_up_check'); if (followCheck) { followCheck.checked = !!consultPost.has_follow_up; followCheck.dispatchEvent(new Event('change')); } const followPreset = document.getElementById('follow_up_preset'); if (followPreset && consultPost.follow_up_preset) { followPreset.value = consultPost.follow_up_preset; followPreset.dispatchEvent(new Event('change')); } const followDays = document.getElementById('follow_up_days'); if (followDays && consultPost.follow_up_days) followDays.value = consultPost.follow_up_days; const followNotes = modalEl.querySelector('input[name="follow_up_notes"]'); if (followNotes) followNotes.value = consultPost.follow_up_notes || ''; } showConsultationModalError(consultServerError, inferErrorFields(consultServerError)); modalEl.querySelectorAll('input, textarea, select').forEach(el => { el.addEventListener('input', function() { el.classList.remove('is-invalid'); if (el.tagName === 'SELECT') markSelect2Invalid(el, false); const errBox = document.getElementById('consultationModalError'); if (errBox) errBox.classList.add('d-none'); }, { once: true }); el.addEventListener('change', function() { el.classList.remove('is-invalid'); if (el.tagName === 'SELECT') markSelect2Invalid(el, false); const errBox = document.getElementById('consultationModalError'); if (errBox) errBox.classList.add('d-none'); }, { once: true }); }); } } }); </script> <!-- Request Lab Modal --> <div class="modal fade" id="requestLabModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <form action="save_doctor_request.php" method="POST" target="_blank"> <input type="hidden" name="patient_id" id="req_patient_id"> <input type="hidden" name="doctor_id" id="req_doctor_id"> <input type="hidden" name="redirect" value="consultation.php"> <div class="modal-header"> <h5 class="modal-title">Request Lab/Imaging for <span id="req_patient_name"></span></h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <ul class="nav nav-tabs" id="reqTab" role="tablist"> <li class="nav-item"> <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#req-lab" type="button">Laboratory Tests</button> </li> <li class="nav-item"> <button class="nav-link" data-bs-toggle="tab" data-bs-target="#req-img" type="button">Imaging / Others</button> </li> </ul> <div class="tab-content p-3 border border-top-0 rounded-bottom"> <div class="tab-pane fade show active" id="req-lab"> <div class="row"> <?php if (!empty($req_categories)) { foreach ($req_categories as $cat => $tests) { if ($cat === 'Imaging' || $cat === 'Others') continue; echo '<div class="col-md-6 mb-3">'; echo '<h6 class="fw-bold text-primary">' . htmlspecialchars($cat) . '</h6>'; foreach ($tests as $t) { echo '<div class="form-check">'; echo '<input class="form-check-input" type="checkbox" name="test_ids[]" value="' . $t['id'] . '" id="req_test_' . $t['id'] . '">'; echo '<label class="form-check-label" for="req_test_' . $t['id'] . '">' . htmlspecialchars($t['name']) . '</label>'; echo '</div>'; } echo '</div>'; } } ?> </div> </div> <div class="tab-pane fade" id="req-img"> <div class="row"> <?php if (!empty($req_categories)) { foreach ($req_categories as $cat => $tests) { if ($cat !== 'Imaging' && $cat !== 'Others') continue; echo '<div class="col-md-6 mb-3">'; echo '<h6 class="fw-bold text-primary">' . htmlspecialchars($cat) . '</h6>'; foreach ($tests as $t) { echo '<div class="form-check">'; echo '<input class="form-check-input" type="checkbox" name="test_ids[]" value="' . $t['id'] . '" id="req_test_' . $t['id'] . '">'; echo '<label class="form-check-label" for="req_test_' . $t['id'] . '">' . htmlspecialchars($t['name']) . '</label>'; echo '</div>'; } echo '</div>'; } } ?> </div> </div> </div> <div class="mt-3"> <label class="form-label">Other Tests (Type manually if not in list)</label> <input type="text" name="other_tests" class="form-control" placeholder="e.g. Special Test 1, Custom Imaging"> </div> <div class="mt-3"> <label class="form-label">Clinical Abstract / Remarks</label> <textarea name="notes" class="form-control" rows="2"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save & Print Request</button> </div> </form> </div> </div> </div> <script> function openRequestModal(patientId, patientName, doctorId) { document.getElementById('req_patient_id').value = patientId; document.getElementById('req_doctor_id').value = doctorId; document.getElementById('req_patient_name').innerText = patientName; // Reset form var form = document.querySelector('#requestLabModal form'); if(form) form.reset(); var modal = new bootstrap.Modal(document.getElementById('requestLabModal')); modal.show(); } document.addEventListener('DOMContentLoaded', function() { const docSelect = document.querySelector('#consultationModal select[name="doctor_id"]'); const feeInput = document.getElementById('consultation_fee'); const discountSelect = document.getElementById('discount_id'); const netInput = document.getElementById('net_amount'); function calculateNet() { if (!feeInput || !discountSelect || !netInput) return; let fee = parseFloat(feeInput.value) || 0; let discountOption = discountSelect.options[discountSelect.selectedIndex]; let discountType = discountOption ? discountOption.getAttribute('data-type') : 'none'; let discountVal = discountOption ? (parseFloat(discountOption.getAttribute('data-val')) || 0) : 0; let discountAmount = 0; if (discountType === 'percent') { discountAmount = (fee * discountVal) / 100; } else if (discountType === 'fixed') { discountAmount = discountVal; } let net = Math.max(0, fee - discountAmount); netInput.value = net.toFixed(2); } if (docSelect) { // Use jQuery for select2 change event if available if (window.jQuery && $(docSelect).data('select2')) { $(docSelect).on('change', function() { let docId = $(this).val(); if (docId) { fetch('consultation.php?action=get_doctor_fee&doctor_id=' + docId) .then(r => r.json()) .then(data => { if (feeInput) { feeInput.value = parseFloat(data.fee).toFixed(2); calculateNet(); } }); } }); } else { docSelect.addEventListener('change', function() { let docId = this.value; if (docId) { fetch('consultation.php?action=get_doctor_fee&doctor_id=' + docId) .then(r => r.json()) .then(data => { if (feeInput) { feeInput.value = parseFloat(data.fee).toFixed(2); calculateNet(); } }); } }); } // Initial fetch if doctor selected and fee is 0 if (docSelect.value && (!feeInput.value || feeInput.value == '0.00')) { let docId = docSelect.value; fetch('consultation.php?action=get_doctor_fee&doctor_id=' + docId) .then(r => r.json()) .then(data => { if (feeInput) { feeInput.value = parseFloat(data.fee).toFixed(2); calculateNet(); } }); } } if (feeInput) feeInput.addEventListener('input', calculateNet); if (discountSelect) discountSelect.addEventListener('change', calculateNet); // Initial calculation calculateNet(); }); </script> <?php include('includes/footer.php'); ?>
Batal