<?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 scheduled for today
$procedures_sql = "SELECT ep.procedure_id, ep.procedure_number, ep.procedure_name, 
                   ep.scheduled_date, ep.scheduled_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,
                   doc_u.first_name as doctor_first, doc_u.last_name as doctor_last,
                   CONCAT(doc_u.first_name, ' ', doc_u.last_name) as doctor_name,
                   ep.pre_procedure_checklist, ep.consent_obtained
                   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 ('SCHEDULED', 'PRE_OP')
                   ORDER BY ep.scheduled_time ASC";
$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' => 'Pre-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;
        }
        
        .procedure-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 #2d7a2d;
            transition: all 0.2s;
        }
        
        .procedure-card:hover {
            transform: translateX(4px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .procedure-card.urgent {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        
        .checklist-container {
            background: #f8fafc;
            padding: 1.5rem;
            border-radius: 8px;
            margin-top: 1rem;
        }
        
        .checklist-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            background: white;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
        }
        
        .checklist-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        .checklist-item.checked {
            background: #d1fae5;
            border-color: #10b981;
        }
        
        .status-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .badge-scheduled {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-pre-op {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-ready {
            background: #d1fae5;
            color: #065f46;
        }
        
        .consent-status {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 600;
        }
        
        .consent-obtained {
            background: #d1fae5;
            color: #065f46;
        }
        
        .consent-pending {
            background: #fee2e2;
            color: #991b1b;
        }
    </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 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">Pre-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-stethoscope-line me-2"></i>Pre-Procedure Preparation</h4>
                                <p class="mb-0">Prepare patients for scheduled procedures and ensure readiness</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='pre_procedure_care.php?date='+this.value">
                        </div>
                        <div class="col-md-9 d-flex align-items-end">
                            <div class="alert alert-info mb-0 w-100">
                                <i class="ri-information-line me-2"></i>
                                <strong><?php echo $procedures->num_rows; ?></strong> procedures scheduled for <?php echo date('F d, Y', strtotime($date_filter)); ?>
                            </div>
                        </div>
                    </div>

                    <!-- Procedures List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($procedures->num_rows > 0): ?>
                                <?php while($proc = $procedures->fetch_assoc()): 
                                    $is_urgent = (strtotime($proc['scheduled_time']) - time()) < 3600; // Less than 1 hour
                                    $checklist = json_decode($proc['pre_procedure_checklist'], true);
                                ?>
                                    <div class="procedure-card <?php echo $is_urgent ? 'urgent' : ''; ?>">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <div class="d-flex justify-content-between align-items-start mb-3">
                                                    <div>
                                                        <h5 class="mb-2">
                                                            <?php echo htmlspecialchars($proc['procedure_name']); ?>
                                                            <?php if ($is_urgent): ?>
                                                                <span class="badge bg-danger ms-2">URGENT</span>
                                                            <?php endif; ?>
                                                        </h5>
                                                        <div class="text-muted small">
                                                            <strong>Procedure #:</strong> <?php echo $proc['procedure_number']; ?>
                                                        </div>
                                                    </div>
                                                    <span class="status-badge badge-<?php echo strtolower(str_replace('_', '-', $proc['status'])); ?>">
                                                        <?php echo str_replace('_', ' ', $proc['status']); ?>
                                                    </span>
                                                </div>
                                                
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <strong>Patient:</strong> <?php echo htmlspecialchars($proc['patient_name']); ?><br>
                                                        <small class="text-muted">
                                                            <?php echo $proc['patient_number']; ?> | 
                                                            <?php echo $proc['age']; ?>Y, <?php echo ucfirst($proc['gender']); ?>
                                                        </small>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <strong>Doctor:</strong> <?php echo htmlspecialchars($proc['doctor_name']); ?><br>
                                                        <strong>Time:</strong> <?php echo date('h:i A', strtotime($proc['scheduled_time'])); ?>
                                                    </div>
                                                </div>
                                                
                                                <div class="consent-status <?php echo $proc['consent_obtained'] ? 'consent-obtained' : 'consent-pending'; ?>">
                                                    <?php if ($proc['consent_obtained']): ?>
                                                        <i class="ri-checkbox-circle-line"></i> Consent Obtained
                                                    <?php else: ?>
                                                        <i class="ri-alert-line"></i> Consent Pending
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 text-end">
                                                <button class="btn btn-primary mb-2 w-100" 
                                                        onclick="openChecklist(<?php echo $proc['procedure_id']; ?>)">
                                                    <i class="ri-checkbox-multiple-line me-1"></i> Pre-Op Checklist
                                                </button>
                                                <button class="btn btn-success mb-2 w-100" 
                                                        onclick="markReady(<?php echo $proc['procedure_id']; ?>)">
                                                    <i class="ri-check-line me-1"></i> Mark Ready
                                                </button>
                                                <button class="btn btn-outline-secondary w-100" 
                                                        onclick="viewDetails(<?php echo $proc['procedure_id']; ?>)">
                                                    <i class="ri-eye-line me-1"></i> View Details
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="ri-information-line me-2"></i>
                                    No procedures scheduled for this date.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>

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

    <!-- Pre-Op Checklist Modal -->
    <div class="modal fade" id="checklistModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Pre-Procedure Checklist</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="checklistForm">
                        <input type="hidden" id="procedure_id" name="procedure_id">
                        
                        <div class="checklist-container">
                            <h6 class="mb-3">Patient Preparation</h6>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="patient_identified" id="check1">
                                <label for="check1">Patient identified using two identifiers (name, DOB, patient number)</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="consent_verified" id="check2">
                                <label for="check2">Informed consent obtained and verified</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="allergies_checked" id="check3">
                                <label for="check3">Allergies documented and communicated</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="npo_status" id="check4">
                                <label for="check4">NPO status confirmed (nothing by mouth as required)</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="vitals_recorded" id="check5">
                                <label for="check5">Baseline vital signs recorded</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="medications_reviewed" id="check6">
                                <label for="check6">Current medications reviewed</label>
                            </div>
                            
                            <h6 class="mt-4 mb-3">Pre-Operative Tasks</h6>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="iv_inserted" id="check7">
                                <label for="check7">IV line inserted and patent</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="site_marked" id="check8">
                                <label for="check8">Surgical/procedure site marked (if applicable)</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="jewelry_removed" id="check9">
                                <label for="check9">Jewelry, dentures, and prosthetics removed</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="gown_changed" id="check10">
                                <label for="check10">Patient changed into hospital gown</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="labs_available" id="check11">
                                <label for="check11">Required lab results available</label>
                            </div>
                            
                            <div class="checklist-item">
                                <input type="checkbox" name="checklist[]" value="equipment_ready" id="check12">
                                <label for="check12">Procedure equipment and supplies ready</label>
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <label class="form-label">Additional Notes</label>
                            <textarea class="form-control" name="notes" rows="3" 
                                      placeholder="Any additional observations or concerns..."></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="saveChecklist()">
                        <i class="ri-save-line me-1"></i> Save Checklist
                    </button>
                </div>
            </div>
        </div>
    </div>

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

    <script>
        // Handle checkbox interactions
        $(document).on('change', '.checklist-item input[type="checkbox"]', function() {
            if ($(this).is(':checked')) {
                $(this).closest('.checklist-item').addClass('checked');
            } else {
                $(this).closest('.checklist-item').removeClass('checked');
            }
        });
        
        function openChecklist(procedureId) {
            $('#procedure_id').val(procedureId);
            $('#checklistForm')[0].reset();
            $('.checklist-item').removeClass('checked');
            
            // Load existing checklist if available
            $.post('ajax/get_procedure_checklist.php', { procedure_id: procedureId }, function(response) {
                if (response.success && response.checklist) {
                    response.checklist.forEach(function(item) {
                        $('input[value="' + item + '"]').prop('checked', true).trigger('change');
                    });
                }
            }, 'json');
            
            const modal = new bootstrap.Modal(document.getElementById('checklistModal'));
            modal.show();
        }
        
        function saveChecklist() {
            const formData = $('#checklistForm').serialize();
            const checkedCount = $('.checklist-item input:checked').length;
            const totalCount = $('.checklist-item input').length;
            
            if (checkedCount < totalCount) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Incomplete Checklist',
                    text: 'Not all items are checked. Continue anyway?',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Save',
                    cancelButtonText: 'Review'
                }).then((result) => {
                    if (result.isConfirmed) {
                        submitChecklist(formData);
                    }
                });
            } else {
                submitChecklist(formData);
            }
        }
        
        function submitChecklist(formData) {
            $.post('ajax/save_preop_checklist.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Checklist Saved',
                        text: 'Pre-procedure checklist has been saved',
                        timer: 2000
                    }).then(() => {
                        $('#checklistModal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to save checklist'
                    });
                }
            }, 'json');
        }
        
        function markReady(procedureId) {
            Swal.fire({
                title: 'Mark Patient Ready?',
                text: 'Confirm all pre-procedure preparations are complete',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Patient Ready',
                confirmButtonColor: '#10b981'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/mark_procedure_ready.php', { procedure_id: procedureId }, function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Patient Ready',
                                text: 'Patient marked as ready for procedure',
                                timer: 2000
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message || 'Failed to update status'
                            });
                        }
                    }, 'json');
                }
            });
        }
        
        function viewDetails(procedureId) {
            window.location.href = 'procedure_details.php?id=' + procedureId;
        }
    </script>
</body>
</html>