<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'RESIDENT_DOCTOR') {
    header('Location: index.php');
    exit();
}

$page_title = "Supervisor Feedback & Evaluations";
$user_id = $_SESSION['user_id'];

// Get resident doctor ID
$doctor_sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
$stmt = $conn->prepare($doctor_sql);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$doctor = $stmt->get_result()->fetch_assoc();
$resident_doctor_id = $doctor['doctor_id'];

// Get date filter
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

// Fetch feedback records
$feedback_sql = "SELECT 
                    sf.*,
                    sv.full_name as supervisor_name,
                    d.specialization as supervisor_specialty
                  FROM supervisor_feedback sf
                  INNER JOIN doctors d ON sf.supervisor_id = d.doctor_id
                  INNER JOIN users sv ON d.user_id = sv.user_id
                  WHERE sf.resident_doctor_id = ?
                  AND sf.feedback_date BETWEEN ? AND ?
                  ORDER BY sf.feedback_date DESC, sf.created_at DESC";

$stmt = $conn->prepare($feedback_sql);
$stmt->bind_param('iss', $resident_doctor_id, $date_from, $date_to);
$stmt->execute();
$feedback_records = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_feedback,
                SUM(CASE WHEN is_formal_evaluation = 1 THEN 1 ELSE 0 END) as formal_evaluations,
                SUM(CASE WHEN resident_acknowledged = 1 THEN 1 ELSE 0 END) as acknowledged,
                ROUND(AVG(overall_rating), 1) as avg_overall_rating,
                ROUND(AVG(clinical_knowledge), 1) as avg_clinical,
                ROUND(AVG(procedural_skills), 1) as avg_procedural,
                ROUND(AVG(communication_skills), 1) as avg_communication,
                ROUND(AVG(professionalism), 1) as avg_professionalism
              FROM supervisor_feedback
              WHERE resident_doctor_id = ?
              AND feedback_date BETWEEN ? AND ?";

$stmt = $conn->prepare($stats_sql);
$stmt->bind_param('iss', $resident_doctor_id, $date_from, $date_to);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #1e5a1e 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
            height: 100%;
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 1rem;
        }
        
        .stat-icon.primary { background: linear-gradient(135deg, #2d7a2d 0%, #1e5a1e 100%); color: white; }
        .stat-icon.success { background: linear-gradient(135deg, #059669 0%, #047857 100%); color: white; }
        .stat-icon.info { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
        
        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .feedback-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.2s;
        }
        
        .feedback-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border-color: #2d7a2d;
        }
        
        .feedback-card.formal {
            border-left: 4px solid #2d7a2d;
        }
        
        .rating-bar {
            height: 8px;
            background: #f1f5f9;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .rating-fill {
            height: 100%;
            background: linear-gradient(to right, #dc2626, #f59e0b, #059669);
            transition: width 0.3s;
        }
        
        .competency-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin: 1rem 0;
        }
        
        .competency-item {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
        }
        
        .competency-label {
            font-size: 0.75rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .competency-score {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .badge-feedback-type {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .badge-daily { background: #dbeafe; color: #1e40af; }
        .badge-weekly { background: #dcfce7; color: #166534; }
        .badge-monthly { background: #fef3c7; color: #92400e; }
        .badge-quarterly { background: #f3e8ff; color: #6b21a8; }
        .badge-annual { background: #fee2e2; color: #991b1b; }
        
        .status-draft { color: #64748b; }
        .status-submitted { color: #3b82f6; }
        .status-acknowledged { color: #059669; }
    </style>
</head>

<body>
    <div class="wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="content-page">
            <div class="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"><?php echo $page_title; ?></h3>
                                <p class="mb-0 opacity-75">Track your performance evaluations and supervisor feedback</p>
                            </div>
                        </div>
                    </div>

                    <!-- Date Filter -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="chart-card">
                                <form method="GET" class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">From Date</label>
                                        <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">To Date</label>
                                        <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <button type="submit" class="btn btn-primary me-2">
                                                <i class="ri-filter-line me-1"></i> Apply
                                            </button>
                                            <a href="supervisor_feedback.php" class="btn btn-outline-secondary">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </a>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Overview -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon primary">
                                    <i class="ri-feedback-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['total_feedback']; ?></div>
                                <div class="stat-label">Total Feedback</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="ri-file-check-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['formal_evaluations']; ?></div>
                                <div class="stat-label">Formal Evaluations</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon warning">
                                    <i class="ri-star-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['avg_overall_rating'] ?? 'N/A'; ?></div>
                                <div class="stat-label">Overall Rating (Avg)</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon info">
                                    <i class="ri-check-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['acknowledged']; ?></div>
                                <div class="stat-label">Acknowledged</div>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Metrics -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Average Performance Scores</h5>
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span class="text-muted">Clinical Knowledge</span>
                                                <strong><?php echo $stats['avg_clinical'] ?? 'N/A'; ?>/10</strong>
                                            </div>
                                            <div class="rating-bar">
                                                <div class="rating-fill" style="width: <?php echo ($stats['avg_clinical'] ?? 0) * 10; ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span class="text-muted">Procedural Skills</span>
                                                <strong><?php echo $stats['avg_procedural'] ?? 'N/A'; ?>/10</strong>
                                            </div>
                                            <div class="rating-bar">
                                                <div class="rating-fill" style="width: <?php echo ($stats['avg_procedural'] ?? 0) * 10; ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span class="text-muted">Communication</span>
                                                <strong><?php echo $stats['avg_communication'] ?? 'N/A'; ?>/10</strong>
                                            </div>
                                            <div class="rating-bar">
                                                <div class="rating-fill" style="width: <?php echo ($stats['avg_communication'] ?? 0) * 10; ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span class="text-muted">Professionalism</span>
                                                <strong><?php echo $stats['avg_professionalism'] ?? 'N/A'; ?>/10</strong>
                                            </div>
                                            <div class="rating-bar">
                                                <div class="rating-fill" style="width: <?php echo ($stats['avg_professionalism'] ?? 0) * 10; ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Feedback Records -->
                    <div class="row">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Feedback History</h5>
                                
                                <?php if ($feedback_records->num_rows > 0): ?>
                                    <?php while($feedback = $feedback_records->fetch_assoc()): ?>
                                    <div class="feedback-card <?php echo $feedback['is_formal_evaluation'] ? 'formal' : ''; ?>">
                                        <div class="d-flex justify-content-between mb-3">
                                            <div>
                                                <h6 class="mb-1">
                                                    <?php echo htmlspecialchars($feedback['supervisor_name']); ?>
                                                    <?php if ($feedback['is_formal_evaluation']): ?>
                                                        <span class="badge bg-danger ms-2">FORMAL EVALUATION</span>
                                                    <?php endif; ?>
                                                </h6>
                                                <small class="text-muted">
                                                    <i class="ri-user-line me-1"></i><?php echo htmlspecialchars($feedback['supervisor_specialty']); ?>
                                                    <i class="ri-calendar-line ms-3 me-1"></i><?php echo date('M d, Y', strtotime($feedback['feedback_date'])); ?>
                                                    <span class="badge-feedback-type badge-<?php echo strtolower($feedback['feedback_type']); ?> ms-2">
                                                        <?php echo $feedback['feedback_type']; ?>
                                                    </span>
                                                </small>
                                            </div>
                                            <div class="text-end">
                                                <div class="mb-2">
                                                    <?php if ($feedback['overall_rating']): ?>
                                                        <span class="badge bg-warning" style="font-size: 1rem; padding: 0.5rem 1rem;">
                                                            <?php echo $feedback['overall_rating']; ?>/10
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="status-<?php echo strtolower($feedback['status']); ?>">
                                                    <?php echo $feedback['status']; ?>
                                                </span>
                                            </div>
                                        </div>

                                        <?php if ($feedback['evaluation_period_start']): ?>
                                        <div class="mb-3">
                                            <small class="text-muted">
                                                <i class="ri-calendar-event-line me-1"></i>
                                                Evaluation Period: 
                                                <?php echo date('M d, Y', strtotime($feedback['evaluation_period_start'])); ?> - 
                                                <?php echo date('M d, Y', strtotime($feedback['evaluation_period_end'])); ?>
                                            </small>
                                        </div>
                                        <?php endif; ?>

                                        <?php if ($feedback['clinical_knowledge'] || $feedback['procedural_skills'] || $feedback['communication_skills']): ?>
                                        <div class="competency-grid mb-3">
                                            <?php if ($feedback['clinical_knowledge']): ?>
                                            <div class="competency-item">
                                                <div class="competency-label">Clinical Knowledge</div>
                                                <div class="competency-score"><?php echo $feedback['clinical_knowledge']; ?>/10</div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($feedback['procedural_skills']): ?>
                                            <div class="competency-item">
                                                <div class="competency-label">Procedural Skills</div>
                                                <div class="competency-score"><?php echo $feedback['procedural_skills']; ?>/10</div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($feedback['communication_skills']): ?>
                                            <div class="competency-item">
                                                <div class="competency-label">Communication</div>
                                                <div class="competency-score"><?php echo $feedback['communication_skills']; ?>/10</div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($feedback['professionalism']): ?>
                                            <div class="competency-item">
                                                <div class="competency-label">Professionalism</div>
                                                <div class="competency-score"><?php echo $feedback['professionalism']; ?>/10</div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>

                                        <div class="mb-2">
                                            <strong>Feedback:</strong>
                                            <p class="mb-2"><?php echo nl2br(htmlspecialchars($feedback['specific_feedback'])); ?></p>
                                        </div>

                                        <?php if ($feedback['strengths']): ?>
                                        <div class="mb-2">
                                            <strong class="text-success"><i class="ri-thumb-up-line me-1"></i>Strengths:</strong>
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($feedback['strengths'])); ?></p>
                                        </div>
                                        <?php endif; ?>

                                        <?php if ($feedback['areas_for_improvement']): ?>
                                        <div class="mb-2">
                                            <strong class="text-warning"><i class="ri-focus-line me-1"></i>Areas for Improvement:</strong>
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($feedback['areas_for_improvement'])); ?></p>
                                        </div>
                                        <?php endif; ?>

                                        <?php if ($feedback['recommendations']): ?>
                                        <div class="mb-3">
                                            <strong class="text-info"><i class="ri-lightbulb-line me-1"></i>Recommendations:</strong>
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($feedback['recommendations'])); ?></p>
                                        </div>
                                        <?php endif; ?>

                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <?php if (!$feedback['resident_acknowledged']): ?>
                                                <button class="btn btn-sm btn-success acknowledge-btn" data-id="<?php echo $feedback['feedback_id']; ?>">
                                                    <i class="ri-check-line me-1"></i> Acknowledge
                                                </button>
                                                <?php else: ?>
                                                <span class="text-success">
                                                    <i class="ri-check-double-line me-1"></i>
                                                    Acknowledged on <?php echo date('M d, Y', strtotime($feedback['acknowledged_at'])); ?>
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                            <button class="btn btn-sm btn-outline-primary view-feedback-btn" data-id="<?php echo $feedback['feedback_id']; ?>">
                                                <i class="ri-eye-line me-1"></i> View Full Details
                                            </button>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center text-muted py-5">
                                        <i class="ri-feedback-line" style="font-size: 3rem;"></i>
                                        <p class="mt-3">No feedback records found for the selected period</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </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 src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Acknowledge feedback
            $('.acknowledge-btn').on('click', function() {
                const feedbackId = $(this).data('id');
                
                Swal.fire({
                    title: 'Acknowledge Feedback',
                    text: 'Optional: Add your comments on this feedback',
                    input: 'textarea',
                    inputPlaceholder: 'Enter your comments (optional)...',
                    showCancelButton: true,
                    confirmButtonText: 'Acknowledge',
                    confirmButtonColor: '#059669'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/acknowledge_feedback.php',
                            type: 'POST',
                            data: {
                                feedback_id: feedbackId,
                                resident_comments: result.value || ''
                            },
                            success: function(response) {
                                const data = JSON.parse(response);
                                if (data.success) {
                                    Swal.fire('Success!', data.message, 'success').then(() => location.reload());
                                } else {
                                    Swal.fire('Error!', data.message, 'error');
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>