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

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

$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";

// Helper function to evaluate Theatre Access Locks based on Workflow Rules
function getWorkflowLocks($conn, $req_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;

    $qTh = $conn->query("SELECT status FROM ipd_theatre_requests WHERE id = $req_id LIMIT 1");
    $th = $qTh->fetch_assoc();
    $th_status = $th['status'] ?? '';
    
    $is_post_surgery = in_array($th_status, ['Completed', 'Cancelled', 'Rejected']);

    // Evaluate Post-Surgery Rules (Patient Sent Back)
    if ($is_post_surgery) {
        if ($rules['block_new_theatre_post_surgery']) { $locks['block_new'] = true; $locks['reason_new'] = "Patient has already been discharged/transferred out of Theatre."; }
        if ($rules['block_edit_theatre_post_surgery']) { $locks['block_edit'] = true; $locks['reason_edit'] = "Patient has already been discharged/transferred out of Theatre."; }
    }

    return $locks;
}

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

        $locks = getWorkflowLocks($conn, $req_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>";
        }

        $qTh = $conn->query("SELECT status, procedure_name, remarks FROM ipd_theatre_requests WHERE id = $req_id");
        if($qTh && $th = $qTh->fetch_assoc()) {
            if ($th['status'] === 'Completed') {
                $alerts .= "<div class='alert alert-success text-dark py-3 mb-3 border-success fw-bold small shadow-sm rounded-3 d-flex align-items-center'><i class='fa-solid fa-check-double fa-2x me-3 text-success'></i> <div><span class='d-block fs-6'>Surgery Completed Successfully</span>Patient has been transferred out of Theatre and returned to active Ward status.</div></div>";
            } elseif ($th['status'] === 'In Progress') {
                $alerts .= "<div class='alert alert-primary text-primary py-3 mb-3 border-primary fw-bold small shadow-sm rounded-3 d-flex align-items-center'><i class='fa-solid fa-spinner fa-spin fa-2x me-3'></i> <div><span class='d-block fs-6'>Surgery Actively In Progress</span>Clinical documentation is actively being recorded. Bed is strictly reserved.</div></div>";
            } else {
                $alerts .= "<div class='alert alert-info text-dark py-3 mb-3 border-info fw-bold small shadow-sm rounded-3 d-flex align-items-center'><i class='fa-solid fa-clock fa-2x me-3 text-info'></i> <div><span class='d-block fs-6'>Status: " . $th['status'] . "</span>Awaiting intra-operative commencement.</div></div>";
            }
        }

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

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

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

        if ($tab === 'overview') {
            $stmt = $conn->prepare("
                SELECT t.procedure_name, t.urgency, t.remarks, t.surgical_notes, t.scheduled_date, t.status,
                       CONCAT(s.first_name, ' ', s.last_name) as surg,
                       CONCAT(a.first_name, ' ', a.last_name) as anes
                FROM ipd_theatre_requests t
                LEFT JOIN staff s ON t.surgeon_id = s.staff_id
                LEFT JOIN staff a ON t.anesthetist_id = a.staff_id
                WHERE t.id = ? LIMIT 1
            ");
            $stmt->bind_param("i", $req_id); $stmt->execute();
            $plan = $stmt->get_result()->fetch_assoc();
            
            $rem = !empty($plan['remarks']) ? $plan['remarks'] : 'No Request Notes / Handover Provided.';
            $snotes = !empty($plan['surgical_notes']) ? strip_tags($plan['surgical_notes'], '<p><br><b><i><u><strong><em><ul><ol><li><span><div>') : '<div class="text-center py-4 text-muted"><i class="fa-solid fa-lock fa-2x mb-2"></i><br>Surgery Not Completed Yet</div>';

            $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" style="letter-spacing:0.5px;"><i class="fa-solid fa-notes-medical me-2"></i> Initial Referral Notes</h6>
                        <p class="mb-0 fw-bold" style="color:#334155; font-size:14.5px; line-height:1.7;">'.htmlspecialchars($rem).'</p>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="p-4 rounded-4 bg-white border border-info 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:#0ea5e9;"></div>
                        <h6 class="fw-bold text-info mb-4 text-uppercase" style="letter-spacing:0.5px;"><i class="fa-solid fa-users me-2"></i> Clinical Team</h6>
                        <div class="d-flex align-items-center mb-3 bg-light p-3 rounded-3 border">
                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width:40px; height:40px;"><i class="fa fa-user-doctor"></i></div>
                            <div><span class="d-block small text-muted fw-bold text-uppercase">Lead Surgeon</span><span class="fw-bold text-dark fs-6">Dr. '.htmlspecialchars($plan['surg'] ?? 'Unassigned').'</span></div>
                        </div>
                        <div class="d-flex align-items-center bg-light p-3 rounded-3 border">
                            <div class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width:40px; height:40px;"><i class="fa fa-syringe"></i></div>
                            <div><span class="d-block small text-muted fw-bold text-uppercase">Anesthesiologist</span><span class="fw-bold text-dark fs-6">Dr. '.htmlspecialchars($plan['anes'] ?? 'Unassigned').'</span></div>
                        </div>
                    </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-check-double text-primary me-2"></i> Post-Operative Completion Notes</h6>
                        <div style="color:#1e293b; font-size:14.5px; line-height:1.8;" class="bg-white p-4 rounded-3 border border-primary border-opacity-25">'.$snotes.'</div>
                    </div>
                </div>
            </div>';
        } 
        else {
            $timeline = [];
            $filterQuery = ($tab === 'full_history') ? "" : " AND r.stage_id = " . (int)$tab;

            $qDyn = $conn->query("SELECT r.*, s.stage_name, st.first_name, st.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_theatre_dynamic_responses r 
                                  JOIN ipd_setup_clinical_stages s ON r.stage_id = s.id 
                                  LEFT JOIN staff st ON r.recorded_by = st.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.req_id = $req_id $filterQuery");
            
            while($r = $qDyn->fetch_assoc()) {
                $key = strtotime($r['recorded_at']) . '_dyn_' . $r['recorded_by'] . '_' . $r['stage_id'];
                if(!isset($timeline[$key])) {
                    $timeline[$key] = [
                        'type' => 'Surgical Record', 'title' => $r['stage_name'], 'stage_id' => $r['stage_id'],
                        'time' => $r['recorded_at'], 'author' => "Dr/Nurse " . $r['first_name'] . ' ' . $r['last_name'], 
                        'icon' => 'fa-scalpel', '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 surgical documentation has been entered for this stage yet.</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>";

                    // HIDE EDIT/DELETE BUTTONS IF WORKFLOW RULES BLOCK EDITING
                    $actions = "";
                    if (!$t['is_deleted'] && !$locks['block_edit']) {
                        $actions = "<button class='btn btn-sm btn-light border py-1 px-2 text-primary shadow-sm' onclick=\"editRecord({$t['stage_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['stage_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 (Exception $e) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>