<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Verify Role Access
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    $redirect_url = match ($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'LAB_TECHNICIAN' => 'lab_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php',
        default => 'index.php'
    };
    header("Location: $redirect_url");
    exit();
}

// Fetch user details
$sql_user_details = "SELECT full_name FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$val = $stmt_user->get_result()->fetch_assoc();
$full_name = $val['full_name'];

// Get scheduled procedures for today
$procedures_sql = "SELECT 
    pp.procedure_id,
    pp.procedure_number,
    pp.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    ept.procedure_name,
    ept.procedure_code,
    pp.procedure_date,
    pp.procedure_time,
    pp.status,
    pp.pre_procedure_notes,
    pp.performed_by,
    doc.full_name as doctor_name,
    TIMESTAMPDIFF(MINUTE, NOW(), CONCAT(pp.procedure_date, ' ', IFNULL(pp.procedure_time, '00:00:00'))) as time_until_procedure
FROM patient_procedures pp
INNER JOIN patients p ON pp.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
LEFT JOIN doctors d ON pp.performed_by = d.doctor_id
LEFT JOIN users doc ON d.user_id = doc.user_id
WHERE DATE(pp.procedure_date) = CURDATE()
AND pp.status IN ('SCHEDULED', 'PREPARING', 'IN_PROGRESS')
ORDER BY pp.procedure_time";

$procedures_result = $conn->query($procedures_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Preparation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .procedure-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
            transition: all 0.3s;
        }
        
        .procedure-card:hover {
            border-color: #66CDAA;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .procedure-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #f1f5f9;
        }
        
        .procedure-info {
            flex: 1;
        }
        
        .procedure-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .procedure-meta {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .procedure-time {
            text-align: right;
        }
        
        .time-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
            margin-bottom: 0.5rem;
        }
        
        .time-urgent {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .time-soon {
            background: #fef3c7;
            color: #92400e;
        }
        
        .time-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-scheduled {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-preparing {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-in-progress {
            background: #dcfce7;
            color: #166534;
        }
        
        .patient-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 1.25rem;
            margin-right: 1rem;
        }
        
        .notes-section {
            margin-top: 1rem;
            padding: 1rem;
            background: #fffbeb;
            border-left: 4px solid #fbbf24;
            border-radius: 6px;
        }
        
        .notes-title {
            font-weight: 600;
            color: #92400e;
            margin-bottom: 0.5rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
            background: white;
            border-radius: 12px;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
        
        .btn-prep {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            border: none;
            color: white;
            padding: 0.5rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-prep:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.2);
        }
        
        .modal-prep {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            overflow-y: auto;
        }
        
        .modal-content-prep {
            background: white;
            margin: 2% auto;
            padding: 0;
            border-radius: 12px;
            max-width: 800px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        }
        
        .modal-header-prep {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-body-prep {
            padding: 2rem;
        }
        
        .close-modal {
            color: white;
            font-size: 2rem;
            font-weight: bold;
            cursor: pointer;
            background: none;
            border: none;
        }
        
        .close-modal:hover {
            opacity: 0.8;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-1">
                                    <i class="ri-surgical-mask-line me-2"></i>Pre-Procedure Patient Preparation
                                </h3>
                                <p class="mb-0 opacity-75">Prepare patients for scheduled procedures</p>
                            </div>
                            <div>
                                <button class="btn btn-light" onclick="location.reload()">
                                    <i class="ri-refresh-line me-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics -->
                    <div class="row mb-4">
                        <?php
                        $total_today = 0;
                        $preparing = 0;
                        $in_progress = 0;
                        $scheduled = 0;
                        
                        $procedures_result->data_seek(0);
                        while ($proc = $procedures_result->fetch_assoc()) {
                            $total_today++;
                            if ($proc['status'] == 'PREPARING') $preparing++;
                            if ($proc['status'] == 'IN_PROGRESS') $in_progress++;
                            if ($proc['status'] == 'SCHEDULED') $scheduled++;
                        }
                        ?>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="text-muted mb-2">Total Today</h6>
                                            <h3 class="mb-0"><?php echo $total_today; ?></h3>
                                        </div>
                                        <div>
                                            <i class="ri-calendar-line" style="font-size: 2.5rem; color: #66CDAA; opacity: 0.3;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="text-muted mb-2">Scheduled</h6>
                                            <h3 class="mb-0"><?php echo $scheduled; ?></h3>
                                        </div>
                                        <div>
                                            <i class="ri-time-line" style="font-size: 2.5rem; color: #3b82f6; opacity: 0.3;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="text-muted mb-2">Preparing</h6>
                                            <h3 class="mb-0"><?php echo $preparing; ?></h3>
                                        </div>
                                        <div>
                                            <i class="ri-loader-line" style="font-size: 2.5rem; color: #f59e0b; opacity: 0.3;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="text-muted mb-2">In Progress</h6>
                                            <h3 class="mb-0"><?php echo $in_progress; ?></h3>
                                        </div>
                                        <div>
                                            <i class="ri-check-line" style="font-size: 2.5rem; color: #10b981; opacity: 0.3;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Procedures List -->
                    <div class="row">
                        <div class="col-12">
                            <?php 
                            $procedures_result->data_seek(0);
                            if ($procedures_result->num_rows > 0): 
                            ?>
                                <?php while ($procedure = $procedures_result->fetch_assoc()): 
                                    $time_until = $procedure['time_until_procedure'];
                                    $time_class = 'time-normal';
                                    if ($time_until <= 30 && $time_until > 0) {
                                        $time_class = 'time-urgent';
                                    } elseif ($time_until <= 60 && $time_until > 0) {
                                        $time_class = 'time-soon';
                                    }
                                ?>
                                <div class="procedure-card">
                                    <div class="procedure-header">
                                        <div class="d-flex align-items-center procedure-info">
                                            <div class="patient-avatar">
                                                <?php echo strtoupper(substr($procedure['patient_name'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <div class="procedure-title">
                                                    <?php echo htmlspecialchars($procedure['procedure_name']); ?>
                                                </div>
                                                <div class="procedure-meta">
                                                    <strong><?php echo htmlspecialchars($procedure['patient_name']); ?></strong> • 
                                                    <?php echo $procedure['patient_number']; ?> • 
                                                    Procedure #<?php echo $procedure['procedure_number']; ?>
                                                </div>
                                                <div class="procedure-meta mt-1">
                                                    <i class="ri-user-line"></i> Dr. <?php echo htmlspecialchars($procedure['doctor_name'] ?? 'Not Assigned'); ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="procedure-time">
                                            <div class="time-badge <?php echo $time_class; ?>">
                                                <?php echo $procedure['procedure_time'] ? date('H:i', strtotime($procedure['procedure_time'])) : 'Not Set'; ?>
                                            </div>
                                            <div class="mt-2">
                                                <span class="status-badge status-<?php echo strtolower($procedure['status']); ?>">
                                                    <?php echo $procedure['status']; ?>
                                                </span>
                                            </div>
                                            <?php if ($time_until > 0): ?>
                                            <div class="mt-2">
                                                <small class="text-muted">
                                                    <?php 
                                                    if ($time_until < 60) {
                                                        echo $time_until . ' minutes';
                                                    } else {
                                                        $hours = floor($time_until / 60);
                                                        $mins = $time_until % 60;
                                                        echo $hours . 'h ' . $mins . 'm';
                                                    }
                                                    ?>
                                                </small>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <?php if ($procedure['pre_procedure_notes']): ?>
                                    <div class="notes-section">
                                        <div class="notes-title">
                                            <i class="ri-alert-line"></i> Pre-Procedure Notes
                                        </div>
                                        <p class="mb-0"><?php echo htmlspecialchars($procedure['pre_procedure_notes']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="text-end mt-3">
                                        <button class="btn btn-secondary me-2" onclick="addNotes(<?php echo $procedure['procedure_id']; ?>, '<?php echo htmlspecialchars($procedure['patient_name']); ?>')">
                                            <i class="ri-file-text-line me-1"></i>Add Notes
                                        </button>
                                        
                                        <?php if ($procedure['status'] == 'SCHEDULED'): ?>
                                        <button class="btn-prep" onclick="markPrepping(<?php echo $procedure['procedure_id']; ?>)">
                                            <i class="ri-loader-line me-1"></i>Mark as Preparing
                                        </button>
                                        <?php elseif ($procedure['status'] == 'PREPARING'): ?>
                                        <span class="badge bg-warning" style="font-size: 1rem; padding: 0.5rem 1rem;">
                                            <i class="ri-loader-line me-1"></i>Patient Preparation in Progress
                                        </span>
                                        <?php elseif ($procedure['status'] == 'IN_PROGRESS'): ?>
                                        <span class="badge bg-success" style="font-size: 1rem; padding: 0.5rem 1rem;">
                                            <i class="ri-check-line me-1"></i>Procedure In Progress
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="ri-calendar-check-line"></i>
                                    <h5>No Procedures Scheduled Today</h5>
                                    <p>There are no procedures scheduled for today</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <!-- Add Notes Modal -->
    <div id="notesModal" class="modal-prep">
        <div class="modal-content-prep">
            <div class="modal-header-prep">
                <h5 class="mb-0">
                    <i class="ri-file-text-line me-2"></i>Add Pre-Procedure Notes
                </h5>
                <button class="close-modal" onclick="closeNotesModal()">&times;</button>
            </div>
            <div class="modal-body-prep">
                <form id="notesForm">
                    <input type="hidden" id="notes_procedure_id" name="procedure_id">
                    
                    <div class="mb-3">
                        <p class="mb-2"><strong>Patient:</strong> <span id="notes_patient_name"></span></p>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Pre-Procedure Notes</label>
                        <textarea class="form-control" id="pre_procedure_notes" name="pre_procedure_notes" 
                                  rows="6" required placeholder="Enter any important notes, observations, or special instructions..."></textarea>
                    </div>
                    
                    <div class="text-end mt-4">
                        <button type="button" class="btn btn-secondary me-2" onclick="closeNotesModal()">Cancel</button>
                        <button type="submit" class="btn-prep">
                            <i class="ri-save-line me-1"></i>Save Notes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    function addNotes(procedureId, patientName) {
        document.getElementById('notes_procedure_id').value = procedureId;
        document.getElementById('notes_patient_name').textContent = patientName;
        document.getElementById('notesModal').style.display = 'block';
    }
    
    function closeNotesModal() {
        document.getElementById('notesModal').style.display = 'none';
        document.getElementById('notesForm').reset();
    }
    
    // Handle notes form submission
    document.getElementById('notesForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        Swal.fire({
            title: 'Saving Notes...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        fetch('save_procedure_notes.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Notes Saved',
                    text: data.message,
                    timer: 2000
                }).then(() => {
                    closeNotesModal();
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: data.message
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while saving notes'
            });
        });
    });
    
    function markPrepping(procedureId) {
        Swal.fire({
            title: 'Mark as Preparing?',
            text: 'Update procedure status to preparing',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Mark as Preparing',
            confirmButtonColor: '#66CDAA',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'mark_procedure_preparing.php',
                    method: 'POST',
                    data: { procedure_id: procedureId },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Status Updated!',
                                text: response.message,
                                timer: 2000
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to update procedure status'
                        });
                    }
                });
            }
        });
    }
    
    // Close modal when clicking outside
    window.onclick = function(event) {
        const modal = document.getElementById('notesModal');
        if (event.target == modal) {
            closeNotesModal();
        }
    }
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>