<?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();
$period = isset($_GET['period']) ? $_GET['period'] : 'month';

// Calculate date range based on period
switch($period) {
    case 'week':
        $start_date = date('Y-m-d', strtotime('-7 days'));
        $period_label = 'This Week';
        break;
    case 'quarter':
        $start_date = date('Y-m-d', strtotime('-3 months'));
        $period_label = 'This Quarter';
        break;
    case 'year':
        $start_date = date('Y-m-d', strtotime('-1 year'));
        $period_label = 'This Year';
        break;
    case 'month':
    default:
        $start_date = date('Y-m-d', strtotime('-30 days'));
        $period_label = 'This Month';
        break;
}
$end_date = date('Y-m-d');
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Nursing Performance')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables/datatables.min.css" rel="stylesheet">
    <script src="assets/libs/chart.js/chart.min.js"></script>
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .performance-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .nurse-profile-card {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
            transition: background 0.2s;
        }
        
        .nurse-profile-card:hover {
            background: #f8fafc;
        }
        
        .nurse-profile-card:last-child {
            border-bottom: none;
        }
        
        .nurse-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.25rem;
        }
        
        .performance-metric {
            text-align: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
        }
        
        .metric-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2d7a2d;
        }
        
        .metric-label {
            color: #64748b;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
        
        .score-badge {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .score-excellent {
            background: #d1fae5;
            color: #065f46;
        }
        
        .score-good {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .score-average {
            background: #fef3c7;
            color: #92400e;
        }
        
        .score-needs-improvement {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin-bottom: 2rem;
        }
    </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 Performance</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">Performance</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-bar-chart-line me-2"></i>Staff Performance Metrics</h4>
                                <p class="mb-0">Track and analyze nursing staff performance - <?php echo $period_label; ?></p>
                            </div>
                            <button class="btn btn-light" onclick="window.print()">
                                <i class="ri-printer-line me-1"></i> Print Report
                            </button>
                        </div>
                    </div>

                    <!-- Period Selector -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label class="form-label">Select Period</label>
                            <select class="form-select" onchange="window.location.href='nursing_performance.php?period='+this.value">
                                <option value="week" <?php echo $period === 'week' ? 'selected' : ''; ?>>This Week</option>
                                <option value="month" <?php echo $period === 'month' ? 'selected' : ''; ?>>This Month</option>
                                <option value="quarter" <?php echo $period === 'quarter' ? 'selected' : ''; ?>>This Quarter</option>
                                <option value="year" <?php echo $period === 'year' ? 'selected' : ''; ?>>This Year</option>
                            </select>
                        </div>
                        <div class="col-md-9 d-flex align-items-end gap-2">
                            <button class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#exportModal">
                                <i class="ri-file-excel-line me-1"></i> Export to Excel
                            </button>
                            <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#reviewModal">
                                <i class="ri-star-line me-1"></i> Performance Review
                            </button>
                        </div>
                    </div>

                    <!-- Performance Charts -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="performance-card">
                                <h5 class="mb-3">Performance Trends</h5>
                                <div class="chart-container">
                                    <canvas id="performanceTrendChart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="performance-card">
                                <h5 class="mb-3">Staff Distribution</h5>
                                <div class="chart-container">
                                    <canvas id="staffDistributionChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="performance-card">
                                <h5 class="mb-3"><i class="ri-trophy-line me-2"></i>Individual Performance Metrics</h5>
                                <div class="table-responsive">
                                    <table id="performanceTable" class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Nurse</th>
                                                <th>Patients Cared</th>
                                                <th>Vitals Recorded</th>
                                                <th>Notes Entered</th>
                                                <th>Shifts Completed</th>
                                                <th>Attendance %</th>
                                                <th>Performance Score</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Top Performers -->
                    <div class="row">
                        <div class="col-12">
                            <div class="performance-card">
                                <h5 class="mb-3"><i class="ri-medal-line me-2"></i>Top Performers (<?php echo $period_label; ?>)</h5>
                                <div id="topPerformersList"></div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

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

    <!-- Performance Review Modal -->
    <div class="modal fade" id="reviewModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Submit Performance Review</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="reviewForm">
                        <div class="mb-3">
                            <label class="form-label">Select Nurse</label>
                            <select class="form-select" name="nurse_id" 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">Review Period</label>
                            <select class="form-select" name="review_period" required>
                                <option value="WEEKLY">Weekly</option>
                                <option value="MONTHLY">Monthly</option>
                                <option value="QUARTERLY">Quarterly</option>
                                <option value="ANNUAL">Annual</option>
                            </select>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Clinical Skills (1-10)</label>
                                <input type="number" class="form-control" name="clinical_skills" min="1" max="10" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Patient Care (1-10)</label>
                                <input type="number" class="form-control" name="patient_care" min="1" max="10" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Communication (1-10)</label>
                                <input type="number" class="form-control" name="communication" min="1" max="10" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Teamwork (1-10)</label>
                                <input type="number" class="form-control" name="teamwork" min="1" max="10" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Punctuality (1-10)</label>
                                <input type="number" class="form-control" name="punctuality" min="1" max="10" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Initiative (1-10)</label>
                                <input type="number" class="form-control" name="initiative" min="1" max="10" required>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Strengths</label>
                            <textarea class="form-control" name="strengths" rows="3" 
                                      placeholder="List key strengths and positive attributes..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Areas for Improvement</label>
                            <textarea class="form-control" name="improvements" rows="3" 
                                      placeholder="Identify areas that need development..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Overall Comments</label>
                            <textarea class="form-control" name="comments" rows="4" 
                                      required placeholder="Provide overall performance summary and recommendations..."></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="submitReview()">
                        <i class="ri-save-line me-1"></i> Submit Review
                    </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() {
            loadPerformanceTable();
            loadTopPerformers();
            initializeCharts();
        });
        
        function loadPerformanceTable() {
            $('#performanceTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: 'ajax/get_nursing_performance.php',
                    type: 'POST',
                    data: function(d) {
                        d.period = '<?php echo $period; ?>';
                        d.start_date = '<?php echo $start_date; ?>';
                        d.end_date = '<?php echo $end_date; ?>';
                    }
                },
                columns: [
                    { data: 'nurse_name' },
                    { data: 'patients_cared' },
                    { data: 'vitals_recorded' },
                    { data: 'notes_entered' },
                    { data: 'shifts_completed' },
                    { data: 'attendance_percent' },
                    { data: 'performance_score' },
                    { data: 'actions', orderable: false, searchable: false }
                ],
                order: [[6, 'desc']],
                pageLength: 25
            });
        }
        
        function loadTopPerformers() {
            $.post('ajax/get_top_performers.php', {
                period: '<?php echo $period; ?>',
                start_date: '<?php echo $start_date; ?>',
                end_date: '<?php echo $end_date; ?>'
            }, function(response) {
                if (response.success) {
                    $('#topPerformersList').html(response.html);
                }
            }, 'json');
        }
        
        function initializeCharts() {
            // Performance Trend Chart
            const trendCtx = document.getElementById('performanceTrendChart').getContext('2d');
            new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
                    datasets: [{
                        label: 'Average Performance Score',
                        data: [85, 87, 89, 91],
                        borderColor: '#2d7a2d',
                        backgroundColor: 'rgba(45, 122, 45, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
            
            // Staff Distribution Chart
            const distCtx = document.getElementById('staffDistributionChart').getContext('2d');
            new Chart(distCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Excellent', 'Good', 'Average', 'Needs Improvement'],
                    datasets: [{
                        data: [8, 12, 5, 2],
                        backgroundColor: [
                            '#10b981',
                            '#3b82f6',
                            '#f59e0b',
                            '#ef4444'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        function submitReview() {
            const formData = $('#reviewForm').serialize();
            
            if (!$('#reviewForm')[0].checkValidity()) {
                $('#reviewForm')[0].reportValidity();
                return;
            }
            
            $.post('ajax/submit_performance_review.php', formData, function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Review Submitted',
                        text: 'Performance review has been saved',
                        timer: 2000
                    }).then(() => {
                        $('#reviewModal').modal('hide');
                        $('#reviewForm')[0].reset();
                        $('#performanceTable').DataTable().ajax.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to submit review'
                    });
                }
            }, 'json');
        }
        
        function viewDetails(nurseId) {
            window.location.href = 'nurse_performance_details.php?nurse_id=' + nurseId;
        }
    </script>
</body>
</html>