<?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();

// Get current shift statistics
$stats_sql = "SELECT 
                COUNT(DISTINCT n.nurse_id) as total_nurses,
                COUNT(DISTINCT CASE WHEN n.shift_type = 'DAY' THEN n.nurse_id END) as day_shift,
                COUNT(DISTINCT CASE WHEN n.shift_type = 'NIGHT' THEN n.nurse_id END) as night_shift,
                COUNT(DISTINCT CASE WHEN n.shift_type = 'ROTATING' THEN n.nurse_id END) as rotating_shift
              FROM nurses n
              WHERE n.is_active = 1";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Get today's date for shift display
$today = date('Y-m-d');
$current_hour = date('H');
$current_shift = ($current_hour >= 6 && $current_hour < 18) ? 'DAY' : 'NIGHT';
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Shift Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables/datatables.min.css" rel="stylesheet">
    <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;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-left: 4px solid #2d7a2d;
            margin-bottom: 1.5rem;
            transition: transform 0.2s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
            font-weight: 600;
        }
        
        .shift-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .current-shift-banner {
            background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            text-align: center;
        }
        
        .current-shift-banner.night {
            background: linear-gradient(135deg, #6366f1 0%, #4338ca 100%);
        }
        
        .handover-card {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .nurse-status {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .status-on-duty {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-off-duty {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status-break {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-day-shift {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-night-shift {
            background: #e0e7ff;
            color: #4338ca;
        }
        
        .badge-rotating {
            background: #dbeafe;
            color: #1e40af;
        }
    </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">Shift Management</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">Nursing Staff</li>
                                        <li class="breadcrumb-item active">Shift Management</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-time-line me-2"></i>Shift Management & Handover</h4>
                                <p class="mb-0">Monitor current shifts, manage handovers, and track staff availability</p>
                            </div>
                            <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#handoverModal">
                                <i class="ri-refresh-line me-1"></i> Initiate Shift Handover
                            </button>
                        </div>
                    </div>

                    <!-- Current Shift Banner -->
                    <div class="current-shift-banner <?php echo $current_shift === 'NIGHT' ? 'night' : ''; ?>">
                        <h3><i class="ri-time-line me-2"></i>Current Shift: <?php echo $current_shift; ?> SHIFT</h3>
                        <p class="mb-0">
                            <?php 
                            if ($current_shift === 'DAY') {
                                echo '6:00 AM - 6:00 PM | ' . date('l, F d, Y');
                            } else {
                                echo '6:00 PM - 6:00 AM | ' . date('l, F d, Y');
                            }
                            ?>
                        </p>
                    </div>

                    <!-- Statistics -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo $stats['total_nurses']; ?></div>
                                <div class="stat-label">Total Active Nurses</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #f59e0b;"><?php echo $stats['day_shift']; ?></div>
                                <div class="stat-label">Day Shift Staff</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #6366f1;"><?php echo $stats['night_shift']; ?></div>
                                <div class="stat-label">Night Shift Staff</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #3b82f6;"><?php echo $stats['rotating_shift']; ?></div>
                                <div class="stat-label">Rotating Staff</div>
                            </div>
                        </div>
                    </div>

                    <!-- Current Shift Details -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="shift-card">
                                <h5 class="mb-3"><i class="ri-user-line me-2"></i>Nurses on Duty</h5>
                                <div class="table-responsive">
                                    <table id="shiftTable" class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Nurse Name</th>
                                                <th>Shift Type</th>
                                                <th>Ward Assignment</th>
                                                <th>Shift Time</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Shift Timeline -->
                        <div class="col-xl-4">
                            <div class="shift-card">
                                <h5 class="mb-3"><i class="ri-calendar-check-line me-2"></i>Shift Timeline</h5>
                                
                                <div class="timeline">
                                    <div class="alert alert-info">
                                        <strong>Day Shift</strong><br>
                                        6:00 AM - 6:00 PM<br>
                                        <small class="text-muted">12 hours</small>
                                    </div>
                                    
                                    <div class="alert alert-dark">
                                        <strong>Night Shift</strong><br>
                                        6:00 PM - 6:00 AM<br>
                                        <small class="text-muted">12 hours</small>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <strong>Break Times</strong><br>
                                        • Meal Break: 30 minutes<br>
                                        • Rest Breaks: 15 min (×2)<br>
                                        <small class="text-muted">Staggered throughout shift</small>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Quick Actions -->
                            <div class="shift-card">
                                <h5 class="mb-3"><i class="ri-settings-3-line me-2"></i>Quick Actions</h5>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-outline-success" onclick="markBreak()">
                                        <i class="ri-time-line me-1"></i> Mark Break
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="viewAttendance()">
                                        <i class="ri-file-list-3-line me-1"></i> View Attendance
                                    </button>
                                    <button class="btn btn-outline-warning" onclick="emergencyCall()">
                                        <i class="ri-alarm-warning-line me-1"></i> Emergency Call
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Handovers -->
                    <div class="row">
                        <div class="col-12">
                            <div class="shift-card">
                                <h5 class="mb-3"><i class="ri-history-line me-2"></i>Recent Shift Handovers</h5>
                                <div id="handoversList"></div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

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

    <!-- Handover Modal -->
    <div class="modal fade" id="handoverModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Shift Handover Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="handoverForm">
                        <div class="mb-3">
                            <label class="form-label">Handover Type</label>
                            <select class="form-select" name="handover_type" required>
                                <option value="">Select Type</option>
                                <option value="DAY_TO_NIGHT">Day to Night Shift</option>
                                <option value="NIGHT_TO_DAY">Night to Day Shift</option>
                                <option value="EMERGENCY">Emergency Handover</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Outgoing Nurse</label>
                            <select class="form-select" name="outgoing_nurse" required>
                                <option value="">Select Nurse</option>
                                <?php
                                $nurses_sql = "SELECT n.nurse_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name
                                               FROM nurses n
                                               INNER JOIN users u ON n.user_id = u.user_id
                                               WHERE n.is_active = 1
                                               ORDER BY u.first_name, u.last_name";
                                $nurses_result = $conn->query($nurses_sql);
                                while($nurse = $nurses_result->fetch_assoc()) {
                                    echo '<option value="' . $nurse['nurse_id'] . '">' . htmlspecialchars($nurse['nurse_name']) . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Incoming Nurse</label>
                            <select class="form-select" name="incoming_nurse" required>
                                <option value="">Select Nurse</option>
                                <?php
                                $nurses_result = $conn->query($nurses_sql);
                                while($nurse = $nurses_result->fetch_assoc()) {
                                    echo '<option value="' . $nurse['nurse_id'] . '">' . htmlspecialchars($nurse['nurse_name']) . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Patient Updates</label>
                            <textarea class="form-control" name="patient_updates" rows="4" 
                                      required placeholder="Summary of patient conditions, any critical issues, pending tasks..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Pending Tasks</label>
                            <textarea class="form-control" name="pending_tasks" rows="3" 
                                      placeholder="List any incomplete tasks that need to be handed over..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Critical Notes</label>
                            <textarea class="form-control" name="critical_notes" rows="3" 
                                      placeholder="Any urgent matters requiring immediate attention..."></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="submitHandover()">
                        <i class="ri-save-line me-1"></i> Submit Handover
                    </button>
                </div>
            </div>
        </div>
    </div>

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

    <script>
        $(document).ready(function() {
            loadShiftTable();
            loadHandovers();
            
            // Auto-refresh every 5 minutes
            setInterval(function() {
                $('#shiftTable').DataTable().ajax.reload(null, false);
                loadHandovers();
            }, 300000);
        });
        
        function loadShiftTable() {
            $('#shiftTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: 'ajax/get_current_shifts.php',
                    type: 'POST',
                    data: function(d) {
                        d.shift_type = '<?php echo $current_shift; ?>';
                        d.date = '<?php echo $today; ?>';
                    }
                },
                columns: [
                    { data: 'nurse_name' },
                    { data: 'shift_type' },
                    { data: 'ward_assignment' },
                    { data: 'shift_time' },
                    { data: 'status' },
                    { data: 'actions', orderable: false, searchable: false }
                ],
                pageLength: 25,
                order: [[0, 'asc']]
            });
        }
        
        function loadHandovers() {
            $.post('ajax/get_recent_handovers.php', function(response) {
                if (response.success) {
                    $('#handoversList').html(response.html);
                }
            }, 'json');
        }
        
        function submitHandover() {
            const formData = $('#handoverForm').serialize();
            
            if (!$('#handoverForm')[0].checkValidity()) {
                $('#handoverForm')[0].reportValidity();
                return;
            }
            
            $.post('ajax/submit_shift_handover.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Handover Submitted',
                        text: 'Shift handover has been recorded successfully',
                        timer: 2000
                    }).then(() => {
                        $('#handoverModal').modal('hide');
                        $('#handoverForm')[0].reset();
                        loadHandovers();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to submit handover'
                    });
                }
            }, 'json');
        }
        
        function markBreak() {
            Swal.fire({
                title: 'Mark Break',
                input: 'select',
                inputOptions: {
                    'START': 'Start Break',
                    'END': 'End Break'
                },
                inputPlaceholder: 'Select action',
                showCancelButton: true,
                confirmButtonText: 'Submit'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Implement break tracking
                    Swal.fire('Success', 'Break status updated', 'success');
                }
            });
        }
        
        function viewAttendance() {
            window.location.href = 'nursing_attendance.php';
        }
        
        function emergencyCall() {
            Swal.fire({
                icon: 'warning',
                title: 'Emergency Call',
                text: 'This will notify all available staff',
                showCancelButton: true,
                confirmButtonText: 'Send Alert',
                confirmButtonColor: '#ef4444'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Implement emergency notification
                    Swal.fire('Alert Sent', 'All staff have been notified', 'success');
                }
            });
        }
    </script>
</body>
</html>