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

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

$student_id = $_SESSION['user_id'];
$staff_id = isset($_GET['staff_id']) ? trim($_GET['staff_id']) : '';
$error = '';
$success = '';
$has_evaluated = false;
$questions = [];
$debug_log = [];

// Validate staff_id
if (empty($staff_id)) {
    $error = "Invalid staff ID.";
    $debug_log[] = "Error: Invalid staff ID.";
} else {
    // Get student's class and programs
    $query = "SELECT u.class_id, 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 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 execute query.";
            $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);

            $class_id = $student_data[0]['class_id'] ?? null;
            $program_ids = array_column($student_data, 'program_id');
            $debug_log[] = "Student ID: $student_id, Class ID: " . ($class_id ?? 'null') . ", Program IDs: " . implode(',', $program_ids);

            if (!$class_id) {
                $error = "You are not assigned to a class.";
                $debug_log[] = "Error: No class assigned to student.";
            } elseif (empty($program_ids)) {
                $error = "You are not assigned to a program.";
                $debug_log[] = "Error: No programs assigned to student.";
            } else {
                // Check if staff is assigned to the student's class and any program with a form
                $query = "SELECT COUNT(*) as count FROM class_program_staff_forms cpsf
                          JOIN class_program_staff cps ON cpsf.class_id = cps.class_id AND cpsf.program_id = cps.program_id AND cpsf.staff_id = cps.staff_id
                          WHERE cpsf.class_id = ? AND cpsf.program_id IN (" . implode(',', array_fill(0, count($program_ids), '?')) . ") AND cpsf.staff_id = ?";
                $stmt = mysqli_prepare($conn, $query);
                if (!$stmt) {
                    $error = "Database error: Unable to prepare staff assignment query.";
                    $debug_log[] = "Error: Failed to prepare staff assignment query: " . mysqli_error($conn);
                } else {
                    $params = array_merge([$class_id], $program_ids, [$staff_id]);
                    mysqli_stmt_bind_param($stmt, str_repeat('i', count($params)), ...$params);
                    if (!mysqli_stmt_execute($stmt)) {
                        $error = "Database error: Failed to verify staff assignment.";
                        $debug_log[] = "Error: Failed to execute staff assignment query: " . mysqli_error($conn);
                    } else {
                        $result = mysqli_stmt_get_result($stmt);
                        $count = mysqli_fetch_assoc($result)['count'];
                        mysqli_stmt_close($stmt);
                        $debug_log[] = "Staff assignment check: Count = $count";
                        if ($count == 0) {
                            $error = "No evaluation forms assigned for this staff.";
                            $debug_log[] = "Error: No forms found for staff_id=$staff_id, class_id=$class_id, program_ids=" . implode(',', $program_ids);
                        }
                    }
                }
            }
        }
    }

    // Check if student has already evaluated this staff
    if (!$error) {
        $query = "SELECT COUNT(*) as count FROM responses_new r
                  JOIN questions q ON r.question_id = q.question_id
                  JOIN class_program_staff_forms cpsf ON q.form_id = cpsf.form_id
                  JOIN evaluation_forms f ON q.form_id = f.form_id
                  WHERE r.staff_id = ? AND r.student_id = ? AND cpsf.class_id = ? 
                  AND cpsf.program_id IN (" . implode(',', array_fill(0, count($program_ids), '?')) . ")
                  AND CURDATE() BETWEEN f.start_date AND f.end_date";
        $stmt = mysqli_prepare($conn, $query);
        if (!$stmt) {
            $error = "Database error: Unable to prepare evaluation check query.";
            $debug_log[] = "Error: Failed to prepare evaluation check query: " . mysqli_error($conn);
        } else {
            $params = array_merge([$staff_id, $student_id, $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 check prior evaluations.";
                $debug_log[] = "Error: Failed to execute evaluation check query: " . mysqli_error($conn);
            } else {
                $result = mysqli_stmt_get_result($stmt);
                $count = mysqli_fetch_assoc($result)['count'];
                mysqli_stmt_close($stmt);
                $debug_log[] = "Evaluation check: Count = $count";
                if ($count > 0) {
                    $has_evaluated = true;
                    $debug_log[] = "Student has already evaluated staff_id=$staff_id";
                }
            }
        }
    }

    // Get questions for the staff, class, and programs (if not evaluated)
    if (!$has_evaluated && !$error) {
        $query = "SELECT q.*, f.form_id, f.title 
                  FROM questions q 
                  JOIN evaluation_forms f ON q.form_id = f.form_id 
                  JOIN class_program_staff_forms cpsf ON q.form_id = cpsf.form_id
                  JOIN class_program_staff cps ON cpsf.class_id = cps.class_id AND cpsf.program_id = cps.program_id AND cpsf.staff_id = cps.staff_id
                  WHERE cpsf.class_id = ? AND cpsf.program_id IN (" . implode(',', array_fill(0, count($program_ids), '?')) . ") 
                  AND cpsf.staff_id = ? AND CURDATE() BETWEEN f.start_date AND f.end_date
                  ORDER BY f.form_id, q.question_id";
        $stmt = mysqli_prepare($conn, $query);
        if (!$stmt) {
            $error = "Database error: Unable to prepare questions query.";
            $debug_log[] = "Error: Failed to prepare questions query: " . mysqli_error($conn);
        } else {
            $params = array_merge([$class_id], $program_ids, [$staff_id]);
            mysqli_stmt_bind_param($stmt, str_repeat('s', count($params)), ...$params);
            if (!mysqli_stmt_execute($stmt)) {
                $error = "Database error: Failed to fetch questions.";
                $debug_log[] = "Error: Failed to execute questions query: " . mysqli_error($conn);
            } else {
                $result = mysqli_stmt_get_result($stmt);
                $questions = $result ? mysqli_fetch_all($result, MYSQLI_ASSOC) : [];
                mysqli_stmt_close($stmt);
                $debug_log[] = "Questions fetched: " . count($questions);
                if (empty($questions)) {
                    $error = "No active questions found for this evaluation.";
                    $debug_log[] = "Error: No questions found for staff_id=$staff_id, class_id=$class_id, program_ids=" . implode(',', $program_ids);
                }
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($error) && !$has_evaluated) {
    $answers = $_POST['answers'] ?? [];
    $form_ids = $_POST['form_id'] ?? [];
    $errors = [];

    // Validate answers
    foreach ($questions as $q) {
        $question_id = $q['question_id'];
        if (!isset($answers[$question_id])) {
            if ($q['question_type'] !== 'text' && $q['question_type'] !== 'checkboxes') {
                $errors[] = "Answer required for: " . htmlspecialchars($q['question_text']);
            }
            continue;
        }

        $answer = $answers[$question_id];
        if (is_array($answer)) {
            $answer = implode(',', array_map('trim', $answer));
        } else {
            $answer = trim($answer);
        }

        // Validate required fields
        if (empty($answer) && $q['question_type'] !== 'text' && $q['question_type'] !== 'checkboxes') {
            $errors[] = "Answer required for: " . htmlspecialchars($q['question_text']);
            continue;
        }

        // Validate options for choice-based questions
        if (in_array($q['question_type'], ['multiple_choice', 'single_choice', 'checkboxes', 'dropdown'])) {
            $valid_options = array_map('trim', explode(',', $q['options']));
            $selected_options = array_map('trim', explode(',', $answer));
            foreach ($selected_options as $opt) {
                if (!empty($opt) && !in_array($opt, $valid_options)) {
                    $errors[] = "Invalid option selected for: " . htmlspecialchars($q['question_text']);
                    break;
                }
            }
        } elseif ($q['question_type'] == 'rating') {
            if (!is_numeric($answer) || $answer < 1 || $answer > 5) {
                $errors[] = "Invalid rating for: " . htmlspecialchars($q['question_text']);
            }
        } elseif ($q['question_type'] == 'yes_no') {
            if (!in_array($answer, ['Yes', 'No'])) {
                $errors[] = "Invalid answer for: " . htmlspecialchars($q['question_text']);
            }
        }
    }

    if (!empty($errors)) {
        $error = implode('<br>', $errors);
    } else {
        // Insert responses
        foreach ($answers as $question_id => $answer) {
            $answer = is_array($answer) ? implode(',', array_map('trim', $answer)) : trim($answer);
            if ($answer === '' && in_array($questions[array_search($question_id, array_column($questions, 'question_id'))]['question_type'], ['text', 'checkboxes'])) {
                continue; // Skip empty optional answers
            }
            $query = "INSERT INTO responses_new (form_id, staff_id, student_id, question_id, answer) VALUES (?, ?, ?, ?, ?)";
            $stmt = mysqli_prepare($conn, $query);
            if ($stmt) {
                $form_id = $form_ids[$question_id] ?? $questions[array_search($question_id, array_column($questions, 'question_id'))]['form_id'];
                mysqli_stmt_bind_param($stmt, 'issss', $form_id, $staff_id, $student_id, $question_id, $answer);
                if (!mysqli_stmt_execute($stmt)) {
                    $error .= "Failed to save response for question ID $question_id.<br>";
                }
                mysqli_stmt_close($stmt);
            } else {
                $error .= "Database error: Unable to prepare response insertion.<br>";
            }
        }
        if (empty($error)) {
            $success = "Evaluation submitted successfully!";
            $has_evaluated = true;
            $questions = [];
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Evaluate Staff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/evaluate.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Evaluate Staff</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?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; ?>
        <?php if ($has_evaluated): ?>
            <div class="alert alert-info">You have already evaluated this staff member.</div>
            <a href="student_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
        <?php elseif (empty($questions)): ?>
            <p>No active evaluation forms available.</p>
            <a href="student_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
        <?php else: ?>
            <form method="POST">
                <?php
                $current_form_id = null;
                foreach ($questions as $q):
                    if ($current_form_id !== $q['form_id']):
                        if ($current_form_id !== null):
                            echo '</div>'; // Close previous form section
                        endif;
                        $current_form_id = $q['form_id'];
                ?>
                        <div class="card mb-3">
                            <div class="card-header">
                                <h4><?php echo htmlspecialchars($q['title']); ?></h4>
                            </div>
                            <div class="card-body">
                <?php endif; ?>
                                <div class="mb-3">
                                    <input type="hidden" name="form_id[<?php echo $q['question_id']; ?>]" value="<?php echo $q['form_id']; ?>">
                                    <label class="form-label">
                                        <?php echo htmlspecialchars($q['question_text']); ?>
                                        <?php if (in_array($q['question_type'], ['text', 'checkboxes'])): ?>
                                            <small>(Optional)</small>
                                        <?php endif; ?>
                                    </label>
                                    <?php if ($q['question_type'] == 'short_answer'): ?>
                                        <input type="text" name="answers[<?php echo $q['question_id']; ?>]" class="form-control" required>
                                    <?php elseif ($q['question_type'] == 'paragraph'): ?>
                                        <textarea name="answers[<?php echo $q['question_id']; ?>]" class="form-control" rows="4" required></textarea>
                                    <?php elseif ($q['question_type'] == 'multiple_choice' || $q['question_type'] == 'single_choice'): ?>
                                        <div>
                                            <?php if (!empty($q['options'])): ?>
                                                <?php foreach (explode(',', $q['options']) as $opt): ?>
                                                    <div class="form-check">
                                                        <input type="radio" name="answers[<?php echo $q['question_id']; ?>]" value="<?php echo htmlspecialchars($opt); ?>" class="form-check-input" required>
                                                        <label class="form-check-label"><?php echo htmlspecialchars($opt); ?></label>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <p>No options available.</p>
                                            <?php endif; ?>
                                        </div>
                                    <?php elseif ($q['question_type'] == 'checkboxes'): ?>
                                        <div>
                                            <?php if (!empty($q['options'])): ?>
                                                <?php foreach (explode(',', $q['options']) as $opt): ?>
                                                    <div class="form-check">
                                                        <input type="checkbox" name="answers[<?php echo $q['question_id']; ?>][]" value="<?php echo htmlspecialchars($opt); ?>" class="form-check-input">
                                                        <label class="form-check-label"><?php echo htmlspecialchars($opt); ?></label>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <p>No options available.</p>
                                            <?php endif; ?>
                                        </div>
                                    <?php elseif ($q['question_type'] == 'dropdown'): ?>
                                        <select name="answers[<?php echo $q['question_id']; ?>]" class="form-control" required>
                                            <option value="">Select an option</option>
                                            <?php if (!empty($q['options'])): ?>
                                                <?php foreach (explode(',', $q['options']) as $opt): ?>
                                                    <option value="<?php echo htmlspecialchars($opt); ?>"><?php echo htmlspecialchars($opt); ?></option>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </select>
                                    <?php elseif ($q['question_type'] == 'rating'): ?>
                                        <select name="answers[<?php echo $q['question_id']; ?>]" class="form-control" required>
                                            <option value="">Select rating</option>
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                            <?php endfor; ?>
                                        </select>
                                    <?php elseif ($q['question_type'] == 'text'): ?>
                                        <textarea name="answers[<?php echo $q['question_id']; ?>]" class="form-control" rows="4"></textarea>
                                    <?php elseif ($q['question_type'] == 'yes_no'): ?>
                                        <div>
                                            <div class="form-check">
                                                <input type="radio" name="answers[<?php echo $q['question_id']; ?>]" value="Yes" class="form-check-input" required>
                                                <label class="form-check-label">Yes</label>
                                            </div>
                                            <div class="form-check">
                                                <input type="radio" name="answers[<?php echo $q['question_id']; ?>]" value="No" class="form-check-input">
                                                <label class="form-check-label">No</label>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                <?php endforeach; ?>
                <?php if ($current_form_id !== null): ?>
                            </div>
                        </div>
                <?php endif; ?>
                <button type="submit" class="btn btn-primary">Submit</button>
                <a href="student_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            </form>
        <?php endif; ?>
    </div>

    <script>
        // Rating stars functionality
        document.querySelectorAll('.rating-star').forEach(star => {
            star.addEventListener('click', function() {
                const value = this.getAttribute('data-value');
                const hiddenInput = document.getElementById('rating-value');
                hiddenInput.value = value;
                
                // Update star display
                document.querySelectorAll('.rating-star').forEach(s => {
                    const starValue = s.getAttribute('data-value');
                    s.classList.toggle('active', starValue <= value);
                    s.classList.toggle('text-warning', starValue <= value);
                });
            });
        });

        // Optional: Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const requiredQuestions = document.querySelectorAll('[required]');
            let isValid = true;
            
            requiredQuestions.forEach(q => {
                if (!q.value) {
                    q.classList.add('is-invalid');
                    isValid = false;
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('Please complete all required questions');
            }
        });
    </script>
</body>
</html>