<?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();
$procedure_id = isset($_GET['procedure_id']) ? intval($_GET['procedure_id']) : 0;

// Get procedure and patient details
$proc_sql = "SELECT ep.*, 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
             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 ep.procedure_id = ?";
$stmt = $conn->prepare($proc_sql);
$stmt->bind_param('i', $procedure_id);
$stmt->execute();
$procedure = $stmt->get_result()->fetch_assoc();

if (!$procedure) {
    header('Location: post_procedure_care.php');
    exit();
}

// Get vital signs history for this procedure
$vitals_sql = "SELECT * FROM vital_signs 
               WHERE patient_id = ? 
               AND recorded_date >= ?
               ORDER BY recorded_date DESC
               LIMIT 10";
$stmt = $conn->prepare($vitals_sql);
$procedure_date = $procedure['scheduled_date'];
$stmt->bind_param('is', $procedure['patient_id'], $procedure_date);
$stmt->execute();
$vitals_history = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Recovery Monitoring')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="assets/libs/chart.js/chart.min.js"></script>
    <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;
        }
        
        .monitoring-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .patient-header {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .vital-monitor {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            border: 2px solid #e2e8f0;
        }
        
        .vital-value-large {
            font-size: 2rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .vital-label-large {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            font-weight: 600;
        }
        
        .status-indicator {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
        }
        
        .status-normal {
            background: #10b981;
        }
        
        .status-warning {
            background: #f59e0b;
            animation: pulse 2s infinite;
        }
        
        .status-critical {
            background: #ef4444;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .chart-container {
            position: relative;
            height: 300px;
        }
        
        .timeline-item {
            padding: 1rem;
            border-left: 3px solid #2d7a2d;
            margin-left: 1rem;
            position: relative;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -8px;
            top: 1.25rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #2d7a2d;
        }
        
        .recovery-stage {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
        }
        
        .stage {
            flex: 1;
            text-align: center;
            padding: 1rem;
            background: #f1f5f9;
            border-radius: 8px;
            position: relative;
        }
        
        .stage.active {
            background: #d1fae5;
            color: #065f46;
            font-weight: 600;
        }
        
        .stage.completed {
            background: #10b981;
            color: white;
        }
        
        .alert-box {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
    </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">Recovery Monitoring</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"><a href="post_procedure_care.php">Post-Procedure Care</a></li>
                                        <li class="breadcrumb-item active">Recovery Monitoring</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="patient-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-2"><?php echo htmlspecialchars($procedure['patient_name']); ?></h4>
                                        <div class="text-muted">
                                            <strong>Patient #:</strong> <?php echo $procedure['patient_number']; ?> | 
                                            <?php echo $procedure['age']; ?>Y, <?php echo ucfirst($procedure['gender']); ?><br>
                                            <strong>Procedure:</strong> <?php echo htmlspecialchars($procedure['procedure_name']); ?><br>
                                            <strong>Performed By:</strong> <?php echo htmlspecialchars($procedure['doctor_name']); ?> | 
                                            <?php echo date('M d, Y', strtotime($procedure['scheduled_date'])); ?>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <span class="status-indicator status-normal"></span>
                                            <strong>Status: Stable</strong>
                                        </div>
                                        <button class="btn btn-success" onclick="dischargePatient()">
                                            <i class="ri-logout-box-line me-1"></i> Discharge Patient
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recovery Stages -->
                    <div class="row">
                        <div class="col-12">
                            <div class="monitoring-card">
                                <h5 class="mb-3"><i class="ri-time-line me-2"></i>Recovery Stages</h5>
                                <div class="recovery-stage">
                                    <div class="stage completed">
                                        <i class="ri-check-line"></i><br>
                                        <strong>Immediate Post-Op</strong><br>
                                        <small>0-2 hours</small>
                                    </div>
                                    <div class="stage active">
                                        <i class="ri-pulse-line"></i><br>
                                        <strong>Active Recovery</strong><br>
                                        <small>2-6 hours</small>
                                    </div>
                                    <div class="stage">
                                        <i class="ri-heart-line"></i><br>
                                        <strong>Observation</strong><br>
                                        <small>6-12 hours</small>
                                    </div>
                                    <div class="stage">
                                        <i class="ri-home-heart-line"></i><br>
                                        <strong>Ready for Discharge</strong><br>
                                        <small>12+ hours</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Current Vitals -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="monitoring-card">
                                <div class="vital-monitor">
                                    <div class="vital-value-large" id="currentBP">120/80</div>
                                    <div class="vital-label-large">Blood Pressure</div>
                                    <div class="status-indicator status-normal mt-2"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="monitoring-card">
                                <div class="vital-monitor">
                                    <div class="vital-value-large" id="currentHR">72</div>
                                    <div class="vital-label-large">Heart Rate (bpm)</div>
                                    <div class="status-indicator status-normal mt-2"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="monitoring-card">
                                <div class="vital-monitor">
                                    <div class="vital-value-large" id="currentTemp">36.8</div>
                                    <div class="vital-label-large">Temperature (°C)</div>
                                    <div class="status-indicator status-normal mt-2"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="monitoring-card">
                                <div class="vital-monitor">
                                    <div class="vital-value-large" id="currentSpO2">98</div>
                                    <div class="vital-label-large">SpO2 (%)</div>
                                    <div class="status-indicator status-normal mt-2"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts and Timeline -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="monitoring-card">
                                <h5 class="mb-3"><i class="ri-line-chart-line me-2"></i>Vital Signs Trends</h5>
                                <div class="chart-container">
                                    <canvas id="vitalsChart"></canvas>
                                </div>
                            </div>
                            
                            <div class="monitoring-card">
                                <h5 class="mb-3"><i class="ri-history-line me-2"></i>Vitals History</h5>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Time</th>
                                                <th>BP</th>
                                                <th>HR</th>
                                                <th>Temp</th>
                                                <th>SpO2</th>
                                                <th>Pain</th>
                                                <th>Recorded By</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($vitals_history->num_rows > 0): ?>
                                                <?php while($vital = $vitals_history->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><?php echo date('H:i', strtotime($vital['recorded_date'])); ?></td>
                                                        <td><?php echo $vital['blood_pressure']; ?></td>
                                                        <td><?php echo $vital['pulse_rate']; ?></td>
                                                        <td><?php echo $vital['temperature']; ?>°C</td>
                                                        <td><?php echo $vital['oxygen_saturation']; ?>%</td>
                                                        <td><?php echo $vital['pain_score'] ?? 'N/A'; ?></td>
                                                        <td><small class="text-muted">Staff</small></td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="7" class="text-center text-muted">No vitals recorded yet</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="monitoring-card">
                                <h5 class="mb-3"><i class="ri-task-line me-2"></i>Recovery Checklist</h5>
                                
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check1" checked>
                                    <label class="form-check-label" for="check1">
                                        Vital signs stable
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check2" checked>
                                    <label class="form-check-label" for="check2">
                                        Pain controlled
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check3" checked>
                                    <label class="form-check-label" for="check3">
                                        No active bleeding
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check4">
                                    <label class="form-check-label" for="check4">
                                        Tolerating fluids/food
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check5">
                                    <label class="form-check-label" for="check5">
                                        Voided (if required)
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check6">
                                    <label class="form-check-label" for="check6">
                                        Able to ambulate
                                    </label>
                                </div>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" id="check7">
                                    <label class="form-check-label" for="check7">
                                        Discharge instructions given
                                    </label>
                                </div>
                            </div>
                            
                            <div class="monitoring-card">
                                <h5 class="mb-3"><i class="ri-alarm-warning-line me-2"></i>Quick Actions</h5>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-primary" onclick="recordVitals()">
                                        <i class="ri-heart-pulse-line me-1"></i> Record Vitals
                                    </button>
                                    <button class="btn btn-success" onclick="addNote()">
                                        <i class="ri-file-add-line me-1"></i> Add Note
                                    </button>
                                    <button class="btn btn-warning" onclick="reportIssue()">
                                        <i class="ri-alert-line me-1"></i> Report Issue
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

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

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

    <script>
        $(document).ready(function() {
            initializeChart();
            startAutoRefresh();
        });
        
        function initializeChart() {
            const ctx = document.getElementById('vitalsChart').getContext('2d');
            
            // Sample data - in production, load from server
            const timeLabels = ['10:00', '10:30', '11:00', '11:30', '12:00', '12:30'];
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timeLabels,
                    datasets: [{
                        label: 'Heart Rate',
                        data: [75, 72, 74, 71, 73, 72],
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        yAxisID: 'y'
                    }, {
                        label: 'SpO2',
                        data: [97, 98, 98, 97, 98, 98],
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        yAxisID: 'y1'
                    }, {
                        label: 'Temperature',
                        data: [36.7, 36.8, 36.8, 36.9, 36.8, 36.8],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        yAxisID: 'y2'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            position: 'left',
                            title: {
                                display: true,
                                text: 'Heart Rate (bpm)'
                            }
                        },
                        y1: {
                            type: 'linear',
                            position: 'right',
                            title: {
                                display: true,
                                text: 'SpO2 (%)'
                            },
                            grid: {
                                drawOnChartArea: false
                            }
                        },
                        y2: {
                            type: 'linear',
                            display: false
                        }
                    }
                }
            });
        }
        
        function startAutoRefresh() {
            setInterval(function() {
                // Refresh vitals - in production, load from server
                console.log('Auto-refreshing vitals...');
            }, 60000); // Every minute
        }
        
        function recordVitals() {
            window.location.href = 'patient_vitals.php?patient_id=<?php echo $procedure['patient_id']; ?>&procedure_id=<?php echo $procedure_id; ?>';
        }
        
        function addNote() {
            window.location.href = 'nursing_notes.php?patient_id=<?php echo $procedure['patient_id']; ?>&procedure_id=<?php echo $procedure_id; ?>';
        }
        
        function reportIssue() {
            window.location.href = 'post_procedure_care.php?report_complication=<?php echo $procedure_id; ?>';
        }
        
        function dischargePatient() {
            const checkedItems = $('input[type="checkbox"]:checked').length;
            const totalItems = $('input[type="checkbox"]').length;
            
            if (checkedItems < totalItems) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Incomplete Checklist',
                    text: `Only ${checkedItems} of ${totalItems} discharge criteria are met. Continue anyway?`,
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Discharge',
                    cancelButtonText: 'Review Checklist'
                }).then((result) => {
                    if (result.isConfirmed) {
                        processDischarge();
                    }
                });
            } else {
                processDischarge();
            }
        }
        
        function processDischarge() {
            Swal.fire({
                title: 'Discharge Patient',
                html: `
                    <div class="text-start">
                        <div class="mb-3">
                            <label class="form-label">Discharge Instructions Given</label>
                            <textarea id="discharge_instructions" class="form-control" rows="4" 
                                      placeholder="Enter discharge instructions..."></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Follow-up Appointment</label>
                            <input type="date" id="followup_date" class="form-control">
                        </div>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Complete Discharge',
                confirmButtonColor: '#10b981',
                preConfirm: () => {
                    return {
                        instructions: document.getElementById('discharge_instructions').value,
                        followup: document.getElementById('followup_date').value
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/discharge_patient.php', {
                        procedure_id: <?php echo $procedure_id; ?>,
                        instructions: result.value.instructions,
                        followup_date: result.value.followup
                    }, function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Patient Discharged',
                                text: 'Patient has been successfully discharged',
                                timer: 2000
                            }).then(() => {
                                window.location.href = 'post_procedure_care.php';
                            });
                        } else {
                            Swal.fire('Error', response.message || 'Failed to discharge patient', 'error');
                        }
                    }, 'json');
                }
            });
        }
    </script>
</body>
</html>