<?php
require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'HEAD_NURSE') {
    header('Location: unauthorized.php');
    exit();
}

$conn = db_connect();
$date_filter = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Get procedures completed today requiring post-op care
$procedures_sql = "SELECT ep.procedure_id, ep.procedure_number, ep.procedure_name, 
                   ep.scheduled_date, ep.procedure_end_time, ep.status,
                   p.patient_id, p.patient_number,
                   CONCAT(u.first_name, ' ', u.last_name) as patient_name,
                   TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
                   u.gender,
                   CONCAT(doc_u.first_name, ' ', doc_u.last_name) as doctor_name,
                   ep.post_procedure_notes, ep.post_op_status
                   FROM ent_procedures ep
                   INNER JOIN patients p ON ep.patient_id = p.patient_id
                   INNER JOIN users u ON p.user_id = u.user_id
                   LEFT JOIN doctors d ON ep.doctor_id = d.doctor_id
                   LEFT JOIN users doc_u ON d.user_id = doc_u.user_id
                   WHERE DATE(ep.scheduled_date) = ?
                   AND ep.status IN ('COMPLETED', 'POST_OP', 'RECOVERY')
                   ORDER BY ep.procedure_end_time DESC";
$stmt = $conn->prepare($procedures_sql);
$stmt->bind_param('s', $date_filter);
$stmt->execute();
$procedures = $stmt->get_result();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Post-Procedure Care')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .patient-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
            border-left: 4px solid #10b981;
            transition: all 0.2s;
        }
        
        .patient-card:hover {
            transform: translateX(4px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .patient-card.critical {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        
        .status-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .badge-recovery {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-post-op {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-stable {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-discharged {
            background: #e2e8f0;
            color: #475569;
        }
        
        .vital-display {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 1rem;
            margin: 1rem 0;
        }
        
        .vital-item {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            text-align: center;
        }
        
        .vital-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .vital-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }
        
        .care-plan-box {
            background: #f0fdf4;
            border: 1px solid #86efac;
            padding: 1rem;
            border-radius: 8px;
            margin-top: 1rem;
        }
        
        .time-elapsed {
            background: #e0e7ff;
            color: #4338ca;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 600;
            display: inline-block;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Post-Procedure Care</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Patient Procedures</li>
                                        <li class="breadcrumb-item active">Post-Procedure Care</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-heartbeat-line me-2"></i>Post-Procedure Monitoring</h4>
                                <p class="mb-0">Monitor and care for patients in recovery after procedures</p>
                            </div>
                        </div>
                    </div>

                    <!-- Date Filter -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label class="form-label">Select Date</label>
                            <input type="date" class="form-control" value="<?php echo $date_filter; ?>" 
                                   onchange="window.location.href='post_procedure_care.php?date='+this.value">
                        </div>
                        <div class="col-md-9 d-flex align-items-end">
                            <div class="alert alert-success mb-0 w-100">
                                <i class="ri-check-line me-2"></i>
                                <strong><?php echo $procedures->num_rows; ?></strong> patients in post-procedure care
                            </div>
                        </div>
                    </div>

                    <!-- Patients List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($procedures->num_rows > 0): ?>
                                <?php while($proc = $procedures->fetch_assoc()): 
                                    $time_since = '';
                                    if ($proc['procedure_end_time']) {
                                        $diff = time() - strtotime($proc['procedure_end_time']);
                                        $hours = floor($diff / 3600);
                                        $minutes = floor(($diff % 3600) / 60);
                                        $time_since = $hours . 'h ' . $minutes . 'm';
                                    }
                                ?>
                                    <div class="patient-card">
                                        <div class="row">
                                            <div class="col-md-7">
                                                <div class="d-flex justify-content-between align-items-start mb-3">
                                                    <div>
                                                        <h5 class="mb-1"><?php echo htmlspecialchars($proc['patient_name']); ?></h5>
                                                        <div class="text-muted small">
                                                            <strong>Patient #:</strong> <?php echo $proc['patient_number']; ?> | 
                                                            <?php echo $proc['age']; ?>Y, <?php echo ucfirst($proc['gender']); ?>
                                                        </div>
                                                    </div>
                                                    <span class="status-badge badge-<?php echo strtolower(str_replace('_', '-', $proc['status'])); ?>">
                                                        <?php echo str_replace('_', ' ', $proc['status']); ?>
                                                    </span>
                                                </div>
                                                
                                                <div class="mb-2">
                                                    <strong>Procedure:</strong> <?php echo htmlspecialchars($proc['procedure_name']); ?><br>
                                                    <strong>Performed By:</strong> <?php echo htmlspecialchars($proc['doctor_name']); ?>
                                                </div>
                                                
                                                <?php if ($time_since): ?>
                                                    <div class="time-elapsed">
                                                        <i class="ri-time-line me-1"></i>
                                                        Time Since Procedure: <?php echo $time_since; ?>
                                                    </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($proc['post_procedure_notes']): ?>
                                                    <div class="care-plan-box">
                                                        <strong><i class="ri-file-text-line me-1"></i>Post-Op Notes:</strong><br>
                                                        <?php echo nl2br(htmlspecialchars($proc['post_procedure_notes'])); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <div class="col-md-5">
                                                <div class="d-grid gap-2">
                                                    <button class="btn btn-primary" 
                                                            onclick="recordVitals(<?php echo $proc['patient_id']; ?>, <?php echo $proc['procedure_id']; ?>)">
                                                        <i class="ri-heart-pulse-line me-1"></i> Record Vitals
                                                    </button>
                                                    <button class="btn btn-success" 
                                                            onclick="addPostOpNote(<?php echo $proc['procedure_id']; ?>)">
                                                        <i class="ri-file-add-line me-1"></i> Add Nursing Note
                                                    </button>
                                                    <button class="btn btn-warning" 
                                                            onclick="reportComplication(<?php echo $proc['procedure_id']; ?>)">
                                                        <i class="ri-alert-line me-1"></i> Report Complication
                                                    </button>
                                                    <button class="btn btn-info" 
                                                            onclick="viewRecovery(<?php echo $proc['procedure_id']; ?>)">
                                                        <i class="ri-eye-line me-1"></i> View Recovery Chart
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="ri-information-line me-2"></i>
                                    No patients in post-procedure care for this date.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Post-Op Note Modal -->
    <div class="modal fade" id="postOpNoteModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Post-Procedure Nursing Note</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="postOpNoteForm">
                        <input type="hidden" id="note_procedure_id" name="procedure_id">
                        
                        <div class="mb-3">
                            <label class="form-label">Assessment Time</label>
                            <input type="time" class="form-control" name="assessment_time" value="<?php echo date('H:i'); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Pain Level (0-10)</label>
                            <input type="range" class="form-range" name="pain_level" min="0" max="10" value="0" id="painRange">
                            <div class="d-flex justify-content-between">
                                <span>0 (No Pain)</span>
                                <strong id="painValue">0</strong>
                                <span>10 (Worst Pain)</span>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Consciousness Level</label>
                            <select class="form-select" name="consciousness_level" required>
                                <option value="ALERT">Alert and Oriented</option>
                                <option value="DROWSY">Drowsy but Responsive</option>
                                <option value="CONFUSED">Confused</option>
                                <option value="UNRESPONSIVE">Unresponsive</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Nausea/Vomiting</label>
                            <select class="form-select" name="nausea_status">
                                <option value="NONE">None</option>
                                <option value="MILD">Mild Nausea</option>
                                <option value="MODERATE">Moderate Nausea</option>
                                <option value="VOMITING">Vomiting</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Wound/Site Assessment</label>
                            <textarea class="form-control" name="wound_assessment" rows="3" 
                                      placeholder="Describe wound condition, drainage, swelling, etc."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Nursing Observations</label>
                            <textarea class="form-control" name="observations" rows="4" required
                                      placeholder="Document patient condition, responses, interventions performed..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Interventions Provided</label>
                            <textarea class="form-control" name="interventions" rows="3" 
                                      placeholder="List any care provided (medications, positioning, etc.)"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="savePostOpNote()">
                        <i class="ri-save-line me-1"></i> Save Note
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Complication Report Modal -->
    <div class="modal fade" id="complicationModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Report Post-Procedure Complication</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="complicationForm">
                        <input type="hidden" id="comp_procedure_id" name="procedure_id">
                        
                        <div class="alert alert-warning">
                            <i class="ri-alert-line me-2"></i>
                            This will immediately notify the responsible physician
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Complication Type *</label>
                            <select class="form-select" name="complication_type" required>
                                <option value="">Select Type</option>
                                <option value="BLEEDING">Bleeding</option>
                                <option value="INFECTION">Signs of Infection</option>
                                <option value="RESPIRATORY">Respiratory Distress</option>
                                <option value="CARDIAC">Cardiac Event</option>
                                <option value="PAIN">Uncontrolled Pain</option>
                                <option value="ALLERGIC">Allergic Reaction</option>
                                <option value="OTHER">Other</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Severity *</label>
                            <select class="form-select" name="severity" required>
                                <option value="MILD">Mild</option>
                                <option value="MODERATE">Moderate</option>
                                <option value="SEVERE">Severe</option>
                                <option value="CRITICAL">Critical</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Description *</label>
                            <textarea class="form-control" name="description" rows="4" required
                                      placeholder="Detailed description of the complication..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Immediate Actions Taken</label>
                            <textarea class="form-control" name="actions_taken" rows="3" 
                                      placeholder="Describe immediate interventions performed..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" onclick="submitComplication()">
                        <i class="ri-alert-line me-1"></i> Report Complication
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        // Pain range slider
        $('#painRange').on('input', function() {
            $('#painValue').text($(this).val());
        });
        
        function recordVitals(patientId, procedureId) {
            window.location.href = 'patient_vitals.php?patient_id=' + patientId + '&procedure_id=' + procedureId;
        }
        
        function addPostOpNote(procedureId) {
            $('#note_procedure_id').val(procedureId);
            $('#postOpNoteForm')[0].reset();
            $('#painRange').val(0).trigger('input');
            
            const modal = new bootstrap.Modal(document.getElementById('postOpNoteModal'));
            modal.show();
        }
        
        function savePostOpNote() {
            const formData = $('#postOpNoteForm').serialize();
            
            if (!$('#postOpNoteForm')[0].checkValidity()) {
                $('#postOpNoteForm')[0].reportValidity();
                return;
            }
            
            $.post('ajax/save_postop_note.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Note Saved',
                        text: 'Post-procedure note recorded successfully',
                        timer: 2000
                    }).then(() => {
                        $('#postOpNoteModal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to save note'
                    });
                }
            }, 'json');
        }
        
        function reportComplication(procedureId) {
            $('#comp_procedure_id').val(procedureId);
            $('#complicationForm')[0].reset();
            
            const modal = new bootstrap.Modal(document.getElementById('complicationModal'));
            modal.show();
        }
        
        function submitComplication() {
            const formData = $('#complicationForm').serialize();
            
            if (!$('#complicationForm')[0].checkValidity()) {
                $('#complicationForm')[0].reportValidity();
                return;
            }
            
            $.post('ajax/report_complication.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Complication Reported',
                        text: 'The physician has been notified',
                        timer: 2000
                    }).then(() => {
                        $('#complicationModal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to report complication'
                    });
                }
            }, 'json');
        }
        
        function viewRecovery(procedureId) {
            window.location.href = 'recovery_monitoring.php?procedure_id=' + procedureId;
        }
    </script>
</body>
</html>