<?php
session_start();
ini_set('display_errors', 0); 
error_reporting(E_ALL);
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

$conn->query("SET FOREIGN_KEY_CHECKS=0");

$staff_id = (int)($_SESSION['staff_id'] ?? 1);
$action = $_POST['action'] ?? '';

$sys = $conn->query("SELECT date_format, time_format FROM system_workflow_rules LIMIT 1")->fetch_assoc();
$df = $sys['date_format'] ?? 'd-M-Y';
$tf = ($sys['time_format'] == '24') ? 'H:i' : 'h:i A';
$global_date_format = "$df, $tf";

function getWorkflowLocks($conn, $visit_id) {
    $locks = ['block_new' => false, 'block_edit' => false, 'reason_new' => '', 'reason_edit' => ''];
    $rules = $conn->query("SELECT * FROM system_workflow_rules LIMIT 1")->fetch_assoc();
    if (!$rules) return $locks;
    $ep = $conn->query("SELECT status FROM ipd_admission_episodes WHERE visit_master_id = $visit_id LIMIT 1")->fetch_assoc();
    $ep_status = $ep['status'] ?? '';
    $is_discharge = in_array($ep_status, ['Pending Discharge', 'Discharged']);
    $qTh = $conn->query("SELECT status FROM ipd_theatre_requests WHERE visit_id = $visit_id ORDER BY id DESC LIMIT 1");
    $th = $qTh->fetch_assoc();
    $is_theatre_pending = ($ep_status === 'In Theatre' || ($th && in_array($th['status'], ['Pending', 'Scheduled', 'In Progress'])));
    $is_theatre_revert = ($th && in_array($th['status'], ['Cancelled', 'Rejected']));
    
    if ($is_discharge) {
        if ($rules['block_new_ipd_on_discharge']) { $locks['block_new'] = true; $locks['reason_new'] = "Patient is recommended for discharge."; }
        if ($rules['block_edit_ipd_on_discharge']) { $locks['block_edit'] = true; $locks['reason_edit'] = "Patient is recommended for discharge."; }
    }
    if ($is_theatre_pending) {
        if ($rules['block_new_ipd_on_theatre_req']) { $locks['block_new'] = true; $locks['reason_new'] = "Patient is currently assigned to the Operating Theatre."; }
        if ($rules['block_edit_ipd_on_theatre_req']) { $locks['block_edit'] = true; $locks['reason_edit'] = "Patient is currently assigned to the Operating Theatre."; }
    }
    if ($is_theatre_revert && !$is_theatre_pending && !$is_discharge) {
        if ($rules['block_new_ipd_on_theatre_revert']) { $locks['block_new'] = true; $locks['reason_new'] = "Patient was reverted/rejected from Theatre."; }
    }
    return $locks;
}

try {
    if ($action === 'fetch_clinical_alerts') {
        $visit_id = (int)$_POST['visit_id'];
        $alerts = "";

        $locks = getWorkflowLocks($conn, $visit_id);

        if ($locks['block_new'] || $locks['block_edit']) {
            $lockMsg = "New Entries: " . ($locks['block_new'] ? "<span class='text-danger'>Blocked</span>" : "Allowed") . " | Edits: " . ($locks['block_edit'] ? "<span class='text-danger'>Blocked</span>" : "Allowed");
            $alerts .= "<div class='alert alert-danger text-danger py-3 mb-3 border-danger fw-bold small shadow-sm rounded-3 d-flex align-items-center'><i class='fa-solid fa-lock fa-2x me-3'></i> <div><span class='d-block fs-6'>Chart Locked by Workflow Rules</span>{$lockMsg}</div></div>";
        }

        $qTrans = $conn->query("SELECT requested_ward, transfer_type FROM clinical_admission_requests WHERE visit_master_id = $visit_id AND status = 'Pending' AND transfer_type IN ('Ward Transfer', 'Theatre Transfer') ORDER BY id DESC LIMIT 1");
        if ($qTrans && $tr = $qTrans->fetch_assoc()) {
            $icon = $tr['transfer_type'] === 'Theatre Transfer' ? 'fa-scalpel-line-dashed text-danger' : 'fa-right-left text-primary';
            $alerts .= "<div class='alert alert-warning text-dark py-2 mb-2 border-warning fw-bold small shadow-sm rounded-3'><i class='fa-solid {$icon} me-2'></i> Transfer Pending: Awaiting acceptance by " . htmlspecialchars($tr['requested_ward']) . ". Patient's bed remains occupied until transfer is cleared.</div>";
        }

        $qTh = $conn->query("SELECT status, procedure_name FROM ipd_theatre_requests WHERE visit_id = $visit_id AND status NOT IN ('Completed', 'Cancelled') ORDER BY id DESC LIMIT 1");
        if($qTh && $th = $qTh->fetch_assoc()) {
            $alerts .= "<div class='alert alert-danger text-danger py-2 mb-2 border-danger fw-bold small shadow-sm rounded-3'><i class='fa-solid fa-procedures me-2'></i> Patient is currently IN THEATRE for: " . htmlspecialchars($th['procedure_name']) . " (" . $th['status'] . "). Ward bed is actively reserved.</div>";
        }

        $qBt = $conn->query("SELECT blood_product, blood_group FROM ipd_transfusion_charts WHERE visit_id = $visit_id AND status = 'Started' AND is_deleted = 0");
        if($qBt && $qBt->num_rows > 0) {
            while($bt = $qBt->fetch_assoc()) {
                $alerts .= "<div class='alert alert-danger text-danger py-2 mb-2 border-danger fw-bold small shadow-sm rounded-3'><i class='fa-solid fa-droplet me-2'></i> CRITICAL: Active Blood Transfusion (" . htmlspecialchars($bt['blood_product'] . " " . $bt['blood_group']) . "). Monitor Vitals strictly.</div>";
            }
        }

        $qRx = $conn->query("SELECT COUNT(id) as cnt FROM clinical_prescriptions WHERE visit_id = $visit_id AND status = 'Pending Pharmacy'");
        if($qRx && $qRx->fetch_assoc()['cnt'] > 0) {
            $alerts .= "<div class='alert alert-primary text-primary py-2 mb-2 border-primary fw-bold small shadow-sm rounded-3'><i class='fa-solid fa-pills me-2'></i> Pharmacy has pending prescriptions to dispense.</div>";
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'html' => $alerts, 'locks' => $locks]); exit;
    }

    if ($action === 'fetch_tab_data') {
        $visit_id = (int)$_POST['visit_id'];
        $tab = $_POST['tab'] ?? 'overview';
        $html = '';

        $locks = getWorkflowLocks($conn, $visit_id);

        if ($tab === 'overview') {
            $stmt = $conn->prepare("SELECT e.provisional_diagnosis, e.principal_complaint, e.admission_notes, c.treatment_plan FROM ipd_admission_episodes e LEFT JOIN clinical_admission_requests c ON e.visit_master_id = c.visit_master_id WHERE e.visit_master_id = ? LIMIT 1");
            $stmt->bind_param("i", $visit_id); $stmt->execute();
            $plan = $stmt->get_result()->fetch_assoc();
            
            $diag = !empty($plan['provisional_diagnosis']) ? $plan['provisional_diagnosis'] : 'Not Specified';
            $comp = !empty($plan['principal_complaint']) ? $plan['principal_complaint'] : 'Not Specified';
            $treat = !empty($plan['treatment_plan']) ? strip_tags($plan['treatment_plan'], '<p><br><b><i><u><strong><em><ul><ol><li><span><div>') : (!empty($plan['admission_notes']) ? strip_tags($plan['admission_notes'], '<p><br><b><i><u><strong><em><ul><ol><li><span><div>') : 'No explicit plan recorded.');

            $html .= '<div class="row g-4"><div class="col-md-6"><div class="p-4 rounded-4 bg-white border border-primary border-opacity-25 shadow-sm h-100 position-relative overflow-hidden"><div class="position-absolute top-0 start-0 w-100" style="height:4px; background:#3b82f6;"></div><h6 class="fw-bold text-primary mb-3 text-uppercase"><i class="fa-solid fa-stethoscope me-2"></i> Principal Diagnosis</h6><p class="mb-0 fw-bold" style="color:#0f172a; font-size:14.5px;">'.htmlspecialchars($diag).'</p></div></div><div class="col-md-6"><div class="p-4 rounded-4 bg-white border border-danger border-opacity-25 shadow-sm h-100 position-relative overflow-hidden"><div class="position-absolute top-0 start-0 w-100" style="height:4px; background:#ef4444;"></div><h6 class="fw-bold text-danger mb-3 text-uppercase"><i class="fa-solid fa-triangle-exclamation me-2"></i> Principal Complaint</h6><p class="mb-0 fw-bold" style="color:#0f172a; font-size:14.5px;">'.htmlspecialchars($comp).'</p></div></div><div class="col-12"><div class="p-4 rounded-4 shadow-sm" style="background:#f0f9ff; border:1px solid #bae6fd;"><h6 class="fw-bold text-dark mb-3 text-uppercase"><i class="fa-solid fa-clipboard-list text-primary me-2"></i> Ward Treatment Plan & Instructions</h6><div style="color:#334155; font-size:14px; font-weight:600; line-height:1.6;" class="bg-white p-4 rounded-3 border border-primary border-opacity-25">'.$treat.'</div></div></div></div>';
        } 
        
        elseif ($tab === 'pharmacy_meds') {
            $qRx = $conn->query("SELECT p.*, s.first_name, s.last_name FROM clinical_prescriptions p LEFT JOIN staff s ON p.prescribed_by = s.staff_id WHERE p.visit_id = $visit_id ORDER BY p.id DESC");
            $html = '<div class="table-responsive bg-white rounded-4 shadow-sm border p-0"><table class="table table-hover align-middle mb-0"><thead class="table-light"><tr><th class="px-4 py-3">Date/Time Ordered</th><th>Medication</th><th>Dosage & Freq</th><th>Pharmacy Status</th><th>Prescriber</th></tr></thead><tbody>';
            
            if ($qRx && $qRx->num_rows > 0) {
                while($rx = $qRx->fetch_assoc()) {
                    $badge = 'bg-secondary';
                    if ($rx['status'] == 'Dispensed') $badge = 'bg-success';
                    elseif (in_array($rx['status'], ['Billed', 'Partially Dispensed'])) $badge = 'bg-info text-dark';
                    elseif ($rx['status'] == 'Pending Pharmacy') $badge = 'bg-warning text-dark';
                    elseif ($rx['status'] == 'Returned') $badge = 'bg-dark';
                    elseif (in_array($rx['status'], ['Rejected', 'Cancelled', 'Stopped'])) $badge = 'bg-danger';
                    
                    $html .= "<tr>
                        <td class='px-4 fw-bold text-muted'>".date($global_date_format, strtotime($rx['created_at']))."</td>
                        <td><b class='text-primary'>{$rx['drug_name']}</b><br><small class='text-muted'>{$rx['formulation']} {$rx['strength']}</small></td>
                        <td>{$rx['dose']} {$rx['frequency']} for {$rx['duration_days']} Days<br><span class='badge bg-light text-dark border shadow-sm mt-1'>Qty Ordered: {$rx['quantity']}</span></td>
                        <td><span class='badge {$badge} px-3 py-2 rounded-pill shadow-sm'>{$rx['status']}</span></td>
                        <td class='small fw-bold'><i class='fa-solid fa-user-doctor text-muted me-1'></i> Dr. {$rx['first_name']} {$rx['last_name']}</td>
                    </tr>";
                }
            } else {
                $html .= "<tr><td colspan='5' class='text-center py-5 text-muted'><i class='fa-solid fa-pills fa-3x opacity-25 mb-3 d-block'></i> No medications have been prescribed for this encounter.</td></tr>";
            }
            $html .= '</tbody></table></div>';
        }
        
        else {
            $timeline = [];

            if ($tab === 'full_history') {
                $qOpd = $conn->query("SELECT n.*, s.first_name, s.last_name FROM clinical_notes n LEFT JOIN staff s ON n.doctor_id = s.staff_id WHERE n.visit_id = $visit_id");
                while($r = $qOpd->fetch_assoc()) {
                    $key = strtotime($r['created_at']) . '_opd_' . $r['id'];
                    $items = [];
                    if(!empty($r['chief_complaint'])) $items[] = ['name' => 'Chief Complaint', 'value' => $r['chief_complaint']];
                    if(!empty($r['clinical_history'])) $items[] = ['name' => 'Clinical History', 'value' => $r['clinical_history']];
                    if(!empty($r['examination_notes'])) $items[] = ['name' => 'Examination', 'value' => $r['examination_notes']];
                    if(!empty($r['treatment_plan_notes'])) $items[] = ['name' => 'Treatment Plan', 'value' => $r['treatment_plan_notes']];
                    $timeline[$key] = ['type' => 'General Consultation', 'title' => 'Doctor Initial Assessment', 'time' => $r['created_at'], 'author' => "Dr. " . trim($r['first_name'] . ' ' . $r['last_name']), 'icon' => 'fa-user-doctor', 'color' => 'success', 'is_deleted' => 0, 'items' => $items, 'form_id' => 0];
                }

                $qVit = $conn->query("SELECT v.*, s.first_name, s.last_name FROM patient_vitals v LEFT JOIN staff s ON v.recorded_by = s.staff_id WHERE v.visit_id = $visit_id");
                while($r = $qVit->fetch_assoc()) {
                    $key = strtotime($r['recorded_at']) . '_vit_' . $r['id'];
                    $items = [];
                    if(!empty($r['bp_systolic']) && !empty($r['bp_diastolic'])) $items[] = ['name' => 'Blood Pressure', 'value' => $r['bp_systolic'].'/'.$r['bp_diastolic'].' mmHg'];
                    if(!empty($r['pulse_rate'])) $items[] = ['name' => 'Pulse Rate', 'value' => $r['pulse_rate'].' bpm'];
                    if(!empty($r['temperature'])) $items[] = ['name' => 'Temperature', 'value' => $r['temperature'].' °C'];
                    if(!empty($r['spo2'])) $items[] = ['name' => 'SpO2', 'value' => $r['spo2'].' %'];

                    if(!empty($items)) {
                        $timeline[$key] = ['type' => 'Triage & Vitals', 'title' => 'Patient Vital Signs', 'time' => $r['recorded_at'], 'author' => "Nurse " . trim($r['first_name'] . ' ' . $r['last_name']), 'icon' => 'fa-heart-pulse', 'color' => 'danger', 'is_deleted' => 0, 'items' => $items, 'form_id' => 0];
                    }
                }
            }

            $filterQuery = ($tab === 'full_history') ? "" : " AND r.module_name = 'form_" . (int)$tab . "'";
            $qDyn = $conn->query("SELECT r.*, f.form_name, f.id as form_id, s.first_name, s.last_name, e.first_name as e_fname, e.last_name as e_lname, d.first_name as d_fname, d.last_name as d_lname FROM ipd_dynamic_responses r JOIN ipd_forms f ON r.module_name = CONCAT('form_', f.id) LEFT JOIN staff s ON r.recorded_by = s.staff_id LEFT JOIN staff e ON r.edited_by = e.staff_id LEFT JOIN staff d ON r.deleted_by = d.staff_id WHERE r.visit_id = $visit_id $filterQuery");
            
            while($r = $qDyn->fetch_assoc()) {
                $key = strtotime($r['recorded_at']) . '_dyn_' . $r['recorded_by'] . '_' . $r['module_name'];
                if(!isset($timeline[$key])) {
                    $timeline[$key] = ['type' => 'In-Patient Ward Record', 'title' => $r['form_name'], 'form_id' => $r['form_id'], 'time' => $r['recorded_at'], 'author' => "Dr/Nurse " . $r['first_name'] . ' ' . $r['last_name'], 'icon' => 'fa-file-medical', 'color' => 'primary', 'is_deleted' => $r['is_deleted'], 'deleted_at' => $r['deleted_at'], 'deleted_by' => trim($r['d_fname']." ".$r['d_lname']), 'edited_at' => $r['edited_at'], 'edited_by' => trim($r['e_fname']." ".$r['e_lname']), 'items' => []];
                }
                if ($r['edited_at'] && (!isset($timeline[$key]['edited_at']) || $r['edited_at'] > $timeline[$key]['edited_at'])) {
                    $timeline[$key]['edited_at'] = $r['edited_at']; $timeline[$key]['edited_by'] = trim($r['e_fname']." ".$r['e_lname']);
                }
                $timeline[$key]['items'][] = ['name' => $r['field_name'], 'value' => $r['field_value']];
            }

            krsort($timeline); 
            
            if(empty($timeline)) {
                $html = '<div class="empty-state text-center py-5"><i class="fa-solid fa-folder-open fa-4x text-muted mb-3 opacity-50"></i><h5 class="text-muted fw-bold">No Records Found</h5><p class="small text-muted">No clinical history recorded for this encounter.</p></div>';
            } else {
                $html .= '<div class="timeline-container ps-3 border-start border-2 border-primary border-opacity-25 ms-2">';
                foreach($timeline as $t) {
                    $delClass = $t['is_deleted'] ? 'deleted-record' : '';
                    $badges = "";
                    if ($t['is_deleted']) $badges .= "<span class='badge bg-danger ms-2 shadow-sm'><i class='fa-solid fa-ban me-1'></i> Voided by {$t['deleted_by']} on ".date($global_date_format, strtotime($t['deleted_at']))."</span>";
                    elseif (!empty($t['edited_at'])) $badges .= "<span class='badge bg-warning text-dark ms-2 shadow-sm'><i class='fa-solid fa-pen me-1'></i> Edited by {$t['edited_by']} on ".date($global_date_format, strtotime($t['edited_at']))."</span>";

                    $actions = "";
                    if (!$t['is_deleted'] && $t['form_id'] > 0 && !$locks['block_edit']) {
                        $actions = "<button class='btn btn-sm btn-light border py-1 px-2 text-primary shadow-sm' onclick=\"editRecord({$t['form_id']}, '{$t['time']}')\"><i class='fa-solid fa-pen me-1'></i> Edit</button> <button class='btn btn-sm btn-light border py-1 px-2 text-danger shadow-sm ms-1' onclick=\"deleteRecord({$t['form_id']}, '{$t['time']}')\"><i class='fa-solid fa-trash'></i></button>";
                    }

                    $html .= "<div class='position-relative mb-4 ps-4 $delClass'><div class='position-absolute top-0 start-0 translate-middle bg-white rounded-circle border border-3 border-{$t['color']}' style='width:20px; height:20px; margin-left:-2px;'></div><div class='small text-muted fw-bold mb-2'>".date($global_date_format, strtotime($t['time']))." <span class='badge bg-{$t['color']} bg-opacity-10 text-{$t['color']} ms-2 border border-{$t['color']} border-opacity-25'>{$t['type']}</span> $badges</div><div class='card border-0 shadow-sm rounded-4 bg-white border-primary border-opacity-25 overflow-hidden'><div class='card-header bg-light border-bottom-0 py-3 d-flex justify-content-between align-items-center'><div><span class='fw-bold text-dark fs-6'><i class='fa-solid {$t['icon']} text-{$t['color']} me-2'></i>{$t['title']}</span></div> <div><span class='small text-muted fw-bold me-3'><i class='fa-solid fa-user-pen me-1'></i>{$t['author']}</span> $actions</div></div><div class='card-body p-4'><div class='row g-4'>";
                    
                    $vitalsHtml = ''; $textHtml = '';
                    foreach($t['items'] as $item) {
                        $name = htmlspecialchars($item['name']);
                        if (strpos($name, '_raw_') === 0) continue; 
                        
                        $val = strip_tags($item['value'], '<p><br><b><i><u><strong><em><ul><ol><li><span><div>');

                        if(strlen($item['value']) < 50 && !preg_match('/(Notes|Plan|Complaint|Remarks|History|Requested|Ordered|Dispatch|Return|Outcome|Diagnoses)/i', $name)) {
                            $vitalsHtml .= "<div class='col-auto'><div class='border rounded-3 px-4 py-2 text-center bg-light shadow-sm'><div class='small text-muted text-uppercase fw-bold mb-1' style='font-size:10px; letter-spacing:0.5px;'>{$name}</div><div class='fw-bold fs-6 text-dark'>{$val}</div></div></div>";
                        } else {
                            $textHtml .= "<div class='col-12'><h6 class='fw-bold text-primary mb-2 small text-uppercase'><i class='fa-solid fa-caret-right me-1'></i> {$name}</h6><div class='p-3 bg-light rounded-3 text-dark border border-white shadow-sm' style='font-size:14px; line-height:1.6;'>{$val}</div></div>";
                        }
                    }
                    if($vitalsHtml != '') $html .= "<div class='col-12'><div class='d-flex flex-wrap gap-2'>{$vitalsHtml}</div></div>";
                    $html .= $textHtml . "</div></div></div></div>";
                }
                $html .= "</div>";
            }
        }
        
        ob_end_clean(); echo json_encode(['status' => 'success', 'html' => $html]); exit;
    }

} catch (Throwable $e) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>