<?php
session_start();
require '../includes/config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    header('Location: login.php');
    exit;
}

$student_id = $_SESSION['user_id'];
$class_id = $_SESSION['class_id'] ?? null;
$error = '';
$staff_list = [];
$debug_log = [];

// Get student's class and programs
$query = "SELECT u.class_id, u.role, u.is_deleted, cps.program_id 
          FROM users u 
          LEFT JOIN class_program_students cps ON u.class_id = cps.class_id
          WHERE u.id = ? AND u.role = 'student'";
$stmt = mysqli_prepare($conn, $query);
if (!$stmt) {
    $error = "Database error: Unable to prepare student query.";
    $debug_log[] = "Error: Failed to prepare student query: " . mysqli_error($conn);
} else {
    mysqli_stmt_bind_param($stmt, 's', $student_id);
    if (!mysqli_stmt_execute($stmt)) {
        $error = "Database error: Failed to fetch student data.";
        $debug_log[] = "Error: Failed to execute student query: " . mysqli_error($conn);
    } else {
        $result = mysqli_stmt_get_result($stmt);
        $student_data = mysqli_fetch_all($result, MYSQLI_ASSOC);
        mysqli_stmt_close($stmt);

        if (empty($student_data)) {
            $error = "Student ID not found in users table. Please contact the administrator.";
            $debug_log[] = "Error: No user found for ID: $student_id";
        } else {
            $class_id = $student_data[0]['class_id'] ?? null;
            $role = $student_data[0]['role'] ?? null;
            $is_deleted = $student_data[0]['is_deleted'] ?? null;
            $program_ids = array_unique(array_filter(array_column($student_data, 'program_id')));
            $debug_log[] = "Student ID: $student_id, Role: $role, Is Deleted: $is_deleted, Class ID: " . ($class_id ?? 'null') . ", Program IDs: " . (empty($program_ids) ? 'none' : implode(',', $program_ids));

            if ($is_deleted == 1) {
                $error = "Your account is marked as deleted. Please contact the administrator.";
                $debug_log[] = "Error: User account is deleted.";
            } elseif (!$class_id) {
                $error = "You are not assigned to a class. Administrator: Please update class_id for student $student_id in the users table.";
                $debug_log[] = "Error: No class assigned to student.";
            } elseif (empty($program_ids)) {
                $error = "You are not assigned to a program. Administrator: Please assign student $student_id to a program in class_program_students.";
                $debug_log[] = "Error: No programs assigned to student.";
            } else {
                // Log active forms
                $form_query = "SELECT form_id, start_date, end_date FROM evaluation_forms WHERE CURDATE() BETWEEN start_date AND end_date";
                $form_result = mysqli_query($conn, $form_query);
                if ($form_result) {
                    $forms = mysqli_fetch_all($form_result, MYSQLI_ASSOC);
                    $debug_log[] = "Active forms: " . (empty($forms) ? 'none' : json_encode($forms));
                } else {
                    $debug_log[] = "Error: Failed to fetch active forms: " . mysqli_error($conn);
                }

                // Get staff assigned to the student's class and programs with active forms
                $placeholders = implode(',', array_fill(0, count($program_ids), '?'));
                $query = "SELECT DISTINCT u.id AS staff_id, u.first_name, u.last_name, 
                          (SELECT COUNT(*) 
                           FROM responses_new r 
                           JOIN questions q ON r.question_id = q.question_id 
                           JOIN class_program_staff_forms cpsf2 ON q.form_id = cpsf2.form_id 
                           WHERE r.staff_id = u.id AND r.student_id = ? 
                           AND cpsf2.class_id = ? AND cpsf2.program_id IN ($placeholders)
                          ) AS evaluation_count
                          FROM users u
                          JOIN class_program_staff_forms cpsf ON u.id = cpsf.staff_id
                          JOIN evaluation_forms f ON cpsf.form_id = f.form_id
                          WHERE cpsf.class_id = ? AND cpsf.program_id IN ($placeholders)
                          AND u.role = 'staff' AND u.is_deleted = 0
                          AND CURDATE() BETWEEN f.start_date AND f.end_date";
                $stmt = mysqli_prepare($conn, $query);
                if (!$stmt) {
                    $error = "Database error: Unable to prepare staff query.";
                    $debug_log[] = "Error: Failed to prepare staff query: " . mysqli_error($conn);
                } else {
                    $params = array_merge([$student_id, $class_id], $program_ids, [$class_id], $program_ids);
                    mysqli_stmt_bind_param($stmt, str_repeat('s', count($params)), ...$params);
                    if (!mysqli_stmt_execute($stmt)) {
                        $error = "Database error: Failed to fetch staff list.";
                        $debug_log[] = "Error: Failed to execute staff query: " . mysqli_error($conn);
                    } else {
                        $result = mysqli_stmt_get_result($stmt);
                        $staff_list = mysqli_fetch_all($result, MYSQLI_ASSOC);
                        mysqli_stmt_close($stmt);
                        $debug_log[] = "Staff fetched: " . count($staff_list);
                        foreach ($staff_list as $staff) {
                            $debug_log[] = "Staff ID: {$staff['staff_id']}, Name: {$staff['first_name']} {$staff['last_name']}, Evaluations: {$staff['evaluation_count']}";
                        }
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Student Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/student.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h2>Student Dashboard</h2>
        <p>Welcome, <?php echo htmlspecialchars($_SESSION['first_name'] . ' ' . $_SESSION['last_name']); ?>!</p>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <div class="alert alert-info">
                <h5>Debug Information (for admin):</h5>
                <pre><?php echo htmlspecialchars(implode("\n", $debug_log)); ?></pre>
            </div>
        <?php endif; ?>
        <h3>Evaluate Staff Members</h3>
        <?php if (empty($staff_list)): ?>
            <p>No staff members available for evaluation. <?php echo $error ? '' : 'No active evaluation forms assigned.'; ?></p>
        <?php else: ?>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Staff Name</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($staff_list as $staff): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($staff['first_name'] . ' ' . $staff['last_name']); ?></td>
                            <td>
                                <?php echo $staff['evaluation_count'] > 0 ? 'Completed' : 'Pending'; ?>
                            </td>
                            <td>
                                <?php if ($staff['evaluation_count'] == 0): ?>
                                    <a href="evaluation.php?staff_id=<?php echo urlencode($staff['staff_id']); ?>" class="btn btn-primary btn-sm">Evaluate</a>
                                <?php else: ?>
                                    <span class="text-muted">Evaluation Submitted</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <a href="logout.php" class="btn btn-secondary mt-3">Logout</a>
    </div>
</body>
</html>