<?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();
$selected_week = isset($_GET['week']) ? $_GET['week'] : date('Y-\WW');

// Parse the week
$year = substr($selected_week, 0, 4);
$week = substr($selected_week, 6);

// Calculate week start and end dates
$dto = new DateTime();
$dto->setISODate($year, $week);
$week_start = $dto->format('Y-m-d');
$dto->modify('+6 days');
$week_end = $dto->format('Y-m-d');

// Get all nurses
$nurses_sql = "SELECT n.nurse_id, u.user_id, CONCAT(u.first_name, ' ', u.last_name) as nurse_name,
               n.shift_type, n.ward_assignments, n.specialization
               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);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Nursing Roster')); ?>
    <?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;
        }
        
        .roster-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .roster-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .roster-table th {
            background: #2d7a2d;
            color: white;
            padding: 1rem;
            text-align: center;
            font-weight: 600;
            border: 1px solid #26a69a;
        }
        
        .roster-table td {
            padding: 1rem;
            border: 1px solid #e2e8f0;
            text-align: center;
            vertical-align: top;
            min-height: 80px;
        }
        
        .roster-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .nurse-name-cell {
            text-align: left;
            font-weight: 600;
            background: #f8fafc;
        }
        
        .shift-cell {
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
        }
        
        .shift-cell:hover {
            background: #f1f5f9;
        }
        
        .shift-day {
            background: #fef3c7;
            border-left: 3px solid #f59e0b;
        }
        
        .shift-night {
            background: #e0e7ff;
            border-left: 3px solid #4338ca;
        }
        
        .shift-off {
            background: #f1f5f9;
            color: #94a3b8;
        }
        
        .shift-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .shift-badge-day {
            background: #fbbf24;
            color: #78350f;
        }
        
        .shift-badge-night {
            background: #6366f1;
            color: white;
        }
        
        .shift-badge-off {
            background: #e2e8f0;
            color: #64748b;
        }
        
        .legend {
            display: flex;
            gap: 2rem;
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }
    </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">Nursing Roster</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">Roster</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-calendar-line me-2"></i>Staff Roster Management</h4>
                                <p class="mb-0">Week of <?php echo date('M d', strtotime($week_start)); ?> - <?php echo date('M d, Y', strtotime($week_end)); ?></p>
                            </div>
                            <div class="d-flex gap-2">
                                <button class="btn btn-light" onclick="window.print()">
                                    <i class="ri-printer-line me-1"></i> Print
                                </button>
                                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bulkAssignModal">
                                    <i class="ri-calendar-schedule-line me-1"></i> Bulk Assign
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Week Selector -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label">Select Week</label>
                            <div class="input-group">
                                <input type="week" class="form-control" id="weekSelector" 
                                       value="<?php echo $selected_week; ?>">
                                <button class="btn btn-success" onclick="loadWeek()">
                                    <i class="ri-search-line"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-8 d-flex align-items-end gap-2">
                            <button class="btn btn-outline-secondary" onclick="changeWeek(-1)">
                                <i class="ri-arrow-left-line me-1"></i> Previous Week
                            </button>
                            <button class="btn btn-outline-secondary" onclick="changeWeek(1)">
                                Next Week <i class="ri-arrow-right-line ms-1"></i>
                            </button>
                            <button class="btn btn-outline-primary" onclick="loadCurrentWeek()">
                                <i class="ri-calendar-line me-1"></i> This Week
                            </button>
                        </div>
                    </div>

                    <!-- Legend -->
                    <div class="legend">
                        <div class="legend-item">
                            <div class="legend-color" style="background: #fef3c7;"></div>
                            <span>Day Shift (6AM - 6PM)</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #e0e7ff;"></div>
                            <span>Night Shift (6PM - 6AM)</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #f1f5f9;"></div>
                            <span>Off Duty</span>
                        </div>
                    </div>

                    <!-- Roster Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="roster-card">
                                <div class="table-responsive">
                                    <table class="roster-table">
                                        <thead>
                                            <tr>
                                                <th style="text-align: left; min-width: 200px;">Nurse</th>
                                                <?php
                                                $current_date = new DateTime($week_start);
                                                for ($i = 0; $i < 7; $i++) {
                                                    echo '<th>';
                                                    echo $current_date->format('D') . '<br>';
                                                    echo '<small>' . $current_date->format('M d') . '</small>';
                                                    echo '</th>';
                                                    $current_date->modify('+1 day');
                                                }
                                                ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while($nurse = $nurses_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td class="nurse-name-cell">
                                                        <div><?php echo htmlspecialchars($nurse['nurse_name']); ?></div>
                                                        <small class="text-muted">
                                                            <?php echo ucfirst($nurse['shift_type']); ?> Shift
                                                            <?php if ($nurse['specialization']): ?>
                                                                | <?php echo htmlspecialchars($nurse['specialization']); ?>
                                                            <?php endif; ?>
                                                        </small>
                                                    </td>
                                                    <?php
                                                    $current_date = new DateTime($week_start);
                                                    for ($i = 0; $i < 7; $i++) {
                                                        $date_str = $current_date->format('Y-m-d');
                                                        $day_num = $current_date->format('N'); // 1=Mon, 7=Sun
                                                        
                                                        // Default shift based on nurse's shift_type
                                                        $shift = 'OFF';
                                                        if ($day_num <= 5) { // Weekdays
                                                            $shift = $nurse['shift_type'] === 'NIGHT' ? 'NIGHT' : 'DAY';
                                                        }
                                                        
                                                        $cell_class = 'shift-cell shift-' . strtolower($shift);
                                                        $badge_class = 'shift-badge shift-badge-' . strtolower($shift);
                                                        
                                                        echo '<td class="' . $cell_class . '" ';
                                                        echo 'onclick="editShift(' . $nurse['nurse_id'] . ', \'' . $date_str . '\', \'' . $shift . '\')">';
                                                        if ($shift !== 'OFF') {
                                                            echo '<span class="' . $badge_class . '">' . $shift . '</span>';
                                                        } else {
                                                            echo '<span class="' . $badge_class . '">OFF</span>';
                                                        }
                                                        echo '</td>';
                                                        
                                                        $current_date->modify('+1 day');
                                                    }
                                                    ?>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

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

    <!-- Edit Shift Modal -->
    <div class="modal fade" id="editShiftModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Shift Assignment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editShiftForm">
                        <input type="hidden" id="edit_nurse_id" name="nurse_id">
                        <input type="hidden" id="edit_date" name="date">
                        
                        <div class="mb-3">
                            <label class="form-label">Shift Type</label>
                            <select class="form-select" id="edit_shift_type" name="shift_type">
                                <option value="DAY">Day Shift (6AM - 6PM)</option>
                                <option value="NIGHT">Night Shift (6PM - 6AM)</option>
                                <option value="OFF">Off Duty</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Ward Assignment</label>
                            <select class="form-select" name="ward_assignment">
                                <option value="">Select Ward</option>
                                <option value="ENT_WARD">ENT Ward</option>
                                <option value="GENERAL">General Ward</option>
                                <option value="ICU">ICU</option>
                                <option value="EMERGENCY">Emergency</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="2" 
                                      placeholder="Any special instructions or notes"></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="saveShift()">Save Shift</button>
                </div>
            </div>
        </div>
    </div>

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

    <script>
        function loadWeek() {
            const week = $('#weekSelector').val();
            window.location.href = 'nursing_roster.php?week=' + week;
        }
        
        function changeWeek(offset) {
            const currentWeek = '<?php echo $selected_week; ?>';
            const [year, week] = currentWeek.split('-W');
            
            const date = new Date(year, 0, 1 + (week - 1) * 7);
            date.setDate(date.getDate() + (offset * 7));
            
            const newYear = date.getFullYear();
            const newWeek = getWeekNumber(date);
            
            window.location.href = 'nursing_roster.php?week=' + newYear + '-W' + String(newWeek).padStart(2, '0');
        }
        
        function loadCurrentWeek() {
            const now = new Date();
            const year = now.getFullYear();
            const week = getWeekNumber(now);
            window.location.href = 'nursing_roster.php?week=' + year + '-W' + String(week).padStart(2, '0');
        }
        
        function getWeekNumber(d) {
            d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
            d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
            const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
            return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
        }
        
        function editShift(nurseId, date, currentShift) {
            $('#edit_nurse_id').val(nurseId);
            $('#edit_date').val(date);
            $('#edit_shift_type').val(currentShift);
            
            const modal = new bootstrap.Modal(document.getElementById('editShiftModal'));
            modal.show();
        }
        
        function saveShift() {
            const formData = $('#editShiftForm').serialize();
            
            $.post('ajax/save_nurse_shift.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Shift Updated',
                        text: 'The shift assignment has been saved',
                        timer: 1500
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to save shift'
                    });
                }
            }, 'json');
        }
    </script>
</body>
</html>