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

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

$conn = db_connect();
$procedure_id = isset($_GET['procedure_id']) ? intval($_GET['procedure_id']) : 0;

// Get procedure details
$proc_sql = "SELECT ep.*, 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, u.phone as patient_phone,
             CONCAT(doc_u.first_name, ' ', doc_u.last_name) as doctor_name,
             ep.pre_procedure_checklist
             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: scheduled_procedures.php');
    exit();
}

$checklist = json_decode($procedure['pre_procedure_checklist'], true) ?: [];
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pre-Procedure Preparation')); ?>
    <?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 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .procedure-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .checklist-section {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .checklist-item {
            display: flex;
            align-items: start;
            gap: 1rem;
            padding: 1rem;
            margin-bottom: 0.5rem;
            background: white;
            border-radius: 8px;
            border: 2px solid #e2e8f0;
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .checklist-item:hover {
            border-color: #2d7a2d;
        }
        
        .checklist-item.completed {
            background: #d1fae5;
            border-color: #10b981;
        }
        
        .checklist-checkbox {
            width: 24px;
            height: 24px;
            cursor: pointer;
            flex-shrink: 0;
        }
        
        .checklist-label {
            flex: 1;
            cursor: pointer;
        }
        
        .progress-bar-container {
            background: #e2e8f0;
            height: 30px;
            border-radius: 15px;
            overflow: hidden;
            margin-bottom: 1.5rem;
        }
        
        .progress-bar-fill {
            height: 100%;
            background: linear-gradient(90deg, #2d7a2d 0%, #26a69a 100%);
            transition: width 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }
        
        .time-remaining {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
        }
        
        .critical-alert {
            background: #fee2e2;
            border-left: 4px solid #ef4444;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
        }
    </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">Pre-Procedure Preparation</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="scheduled_procedures.php">Scheduled Procedures</a></li>
                                        <li class="breadcrumb-item active">Pre-Procedure Prep</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Time Remaining Alert -->
                    <?php
                    $scheduled_time = strtotime($procedure['scheduled_date'] . ' ' . $procedure['scheduled_time']);
                    $time_diff = $scheduled_time - time();
                    $hours = floor($time_diff / 3600);
                    $minutes = floor(($time_diff % 3600) / 60);
                    $is_urgent = $time_diff < 3600; // Less than 1 hour
                    ?>
                    
                    <?php if ($is_urgent): ?>
                    <div class="critical-alert">
                        <i class="ri-alarm-warning-line me-2"></i>
                        <strong>URGENT:</strong> Procedure scheduled in <?php echo $hours; ?>h <?php echo $minutes; ?>m
                    </div>
                    <?php else: ?>
                    <div class="time-remaining">
                        <i class="ri-time-line me-2"></i>
                        <strong>Time Remaining:</strong> <?php echo $hours; ?> hours <?php echo $minutes; ?> minutes until procedure
                    </div>
                    <?php endif; ?>

                    <!-- Patient & Procedure Info -->
                    <div class="row">
                        <div class="col-xl-4">
                            <div class="patient-card">
                                <h5 class="mb-3"><i class="ri-user-line me-2"></i>Patient Information</h5>
                                <div class="mb-2">
                                    <strong>Name:</strong><br>
                                    <?php echo htmlspecialchars($procedure['patient_name']); ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Patient Number:</strong><br>
                                    <?php echo htmlspecialchars($procedure['patient_number']); ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Age/Gender:</strong><br>
                                    <?php echo $procedure['age']; ?> years, <?php echo ucfirst($procedure['gender']); ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Contact:</strong><br>
                                    <?php echo htmlspecialchars($procedure['patient_phone']); ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-8">
                            <div class="procedure-card">
                                <h5 class="mb-3"><i class="ri-stethoscope-line me-2"></i>Procedure Details</h5>
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <strong>Procedure:</strong><br>
                                        <?php echo htmlspecialchars($procedure['procedure_name']); ?>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <strong>Procedure #:</strong><br>
                                        <?php echo htmlspecialchars($procedure['procedure_number']); ?>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <strong>Scheduled Time:</strong><br>
                                        <?php echo date('h:i A', strtotime($procedure['scheduled_time'])); ?>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <strong>Performing Doctor:</strong><br>
                                        <?php echo htmlspecialchars($procedure['doctor_name']); ?>
                                    </div>
                                    <div class="col-12 mt-2">
                                        <strong>Description:</strong><br>
                                        <?php echo htmlspecialchars($procedure['procedure_description'] ?? 'No description available'); ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Preparation Progress -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="mb-3">Preparation Progress</h5>
                                    <div class="progress-bar-container">
                                        <div class="progress-bar-fill" id="progressBar" style="width: 0%;">
                                            <span id="progressText">0% Complete</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pre-Procedure Checklist -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="mb-4"><i class="ri-checkbox-multiple-line me-2"></i>Pre-Procedure Checklist</h5>
                                    
                                    <form id="prepChecklistForm">
                                        <input type="hidden" name="procedure_id" value="<?php echo $procedure_id; ?>">
                                        
                                        <div class="checklist-section">
                                            <h6 class="mb-3">Patient Identification & Consent</h6>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="patient_identified">
                                                <label class="checklist-label">
                                                    <strong>Patient Identified</strong><br>
                                                    <small class="text-muted">Verify using two identifiers (name, DOB, patient number)</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="consent_verified">
                                                <label class="checklist-label">
                                                    <strong>Informed Consent Verified</strong><br>
                                                    <small class="text-muted">Consent form signed and understood by patient</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="allergy_check">
                                                <label class="checklist-label">
                                                    <strong>Allergies Documented</strong><br>
                                                    <small class="text-muted">All allergies documented and communicated to team</small>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="checklist-section">
                                            <h6 class="mb-3">Pre-Operative Preparation</h6>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="npo_status">
                                                <label class="checklist-label">
                                                    <strong>NPO Status Confirmed</strong><br>
                                                    <small class="text-muted">Nothing by mouth as per protocol</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="vitals_recorded">
                                                <label class="checklist-label">
                                                    <strong>Baseline Vitals Recorded</strong><br>
                                                    <small class="text-muted">Blood pressure, heart rate, temperature, SpO2</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="iv_access">
                                                <label class="checklist-label">
                                                    <strong>IV Access Established</strong><br>
                                                    <small class="text-muted">IV line inserted and patent</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="jewelry_removed">
                                                <label class="checklist-label">
                                                    <strong>Personal Items Removed</strong><br>
                                                    <small class="text-muted">Jewelry, dentures, prosthetics secured</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="gown_changed">
                                                <label class="checklist-label">
                                                    <strong>Hospital Gown Applied</strong><br>
                                                    <small class="text-muted">Patient changed into appropriate gown</small>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="checklist-section">
                                            <h6 class="mb-3">Clinical Preparation</h6>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="site_marked">
                                                <label class="checklist-label">
                                                    <strong>Surgical Site Marked (if applicable)</strong><br>
                                                    <small class="text-muted">Site marked by surgeon</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="preop_meds">
                                                <label class="checklist-label">
                                                    <strong>Pre-Op Medications Given</strong><br>
                                                    <small class="text-muted">As per anesthesia orders</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="labs_available">
                                                <label class="checklist-label">
                                                    <strong>Lab Results Available</strong><br>
                                                    <small class="text-muted">Required lab work completed and reviewed</small>
                                                </label>
                                            </div>
                                            
                                            <div class="checklist-item" onclick="toggleCheck(this)">
                                                <input type="checkbox" class="checklist-checkbox" name="checklist[]" value="equipment_ready">
                                                <label class="checklist-label">
                                                    <strong>Equipment & Supplies Ready</strong><br>
                                                    <small class="text-muted">All necessary equipment prepared</small>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Additional Notes</label>
                                            <textarea class="form-control" name="prep_notes" rows="3" 
                                                      placeholder="Any additional observations or concerns..."></textarea>
                                        </div>
                                        
                                        <div class="d-flex gap-2 justify-content-end">
                                            <a href="scheduled_procedures.php" class="btn btn-light">Cancel</a>
                                            <button type="button" class="btn btn-success" onclick="savePreparation()">
                                                <i class="ri-save-line me-1"></i> Save Preparation
                                            </button>
                                            <button type="button" class="btn btn-primary" onclick="markPatientReady()">
                                                <i class="ri-check-double-line me-1"></i> Mark Patient Ready
                                            </button>
                                        </div>
                                    </form>
                                </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() {
            updateProgress();
            
            // Load existing checklist
            <?php if (!empty($checklist)): ?>
                <?php foreach($checklist as $item): ?>
                    $('input[value="<?php echo $item; ?>"]').prop('checked', true)
                        .closest('.checklist-item').addClass('completed');
                <?php endforeach; ?>
                updateProgress();
            <?php endif; ?>
        });
        
        function toggleCheck(element) {
            const checkbox = $(element).find('input[type="checkbox"]');
            checkbox.prop('checked', !checkbox.prop('checked'));
            
            if (checkbox.prop('checked')) {
                $(element).addClass('completed');
            } else {
                $(element).removeClass('completed');
            }
            
            updateProgress();
        }
        
        function updateProgress() {
            const total = $('input[type="checkbox"]').length;
            const checked = $('input[type="checkbox"]:checked').length;
            const percentage = Math.round((checked / total) * 100);
            
            $('#progressBar').css('width', percentage + '%');
            $('#progressText').text(percentage + '% Complete (' + checked + '/' + total + ')');
        }
        
        function savePreparation() {
            const formData = $('#prepChecklistForm').serialize();
            
            $.post('ajax/save_prep_checklist.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Saved',
                        text: 'Preparation checklist saved',
                        timer: 2000
                    });
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            }, 'json');
        }
        
        function markPatientReady() {
            const total = $('input[type="checkbox"]').length;
            const checked = $('input[type="checkbox"]:checked').length;
            
            if (checked < total) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Incomplete Checklist',
                    text: 'Not all checklist items are completed. Mark patient ready anyway?',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Mark Ready'
                }).then((result) => {
                    if (result.isConfirmed) {
                        submitReadyStatus();
                    }
                });
            } else {
                submitReadyStatus();
            }
        }
        
        function submitReadyStatus() {
            const formData = $('#prepChecklistForm').serialize() + '&mark_ready=1';
            
            $.post('ajax/mark_patient_ready_nurse.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Patient Ready',
                        text: 'Patient marked as ready for procedure',
                        timer: 2000
                    }).then(() => {
                        window.location.href = 'scheduled_procedures.php';
                    });
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            }, 'json');
        }
    </script>
</body>
</html>