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

// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', '/Applications/XAMPP/xamppfiles/htdocs/appraisal/public/debug.log');

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

$role = $_SESSION['role'];
$user_id = $_SESSION['user_id'];
$error_message = '';

// Directory for temporary chart images (for staff PDF export)
if ($role === 'staff') {
    $tmp_dir = __DIR__ . '/tmp/';
    $fallback_tmp_dir = __DIR__ . '/fallback_tmp/';
    $selected_tmp_dir = $tmp_dir;

    // Try creating primary directory
    if (!is_dir($tmp_dir)) {
        if (!@mkdir($tmp_dir, 0755, true)) {
            error_log("Failed to create directory '$tmp_dir': " . error_get_last()['message']);
            $selected_tmp_dir = $fallback_tmp_dir;
        } else {
            @chmod($tmp_dir, 0755);
            if (!@chown($tmp_dir, 'daemon') || !@chgrp($tmp_dir, 'daemon')) {
                error_log("Failed to set ownership of '$tmp_dir' to daemon:daemon");
            }
        }
    }

    // Try creating fallback directory if needed
    if ($selected_tmp_dir === $fallback_tmp_dir && !is_dir($fallback_tmp_dir)) {
        if (!@mkdir($fallback_tmp_dir, 0755, true)) {
            error_log("Failed to create fallback directory '$fallback_tmp_dir': " . error_get_last()['message']);
            $selected_tmp_dir = null;
        } else {
            @chmod($fallback_tmp_dir, 0755);
            if (!@chown($fallback_tmp_dir, 'daemon') || !@chgrp($fallback_tmp_dir, 'daemon')) {
                error_log("Failed to set ownership of '$fallback_tmp_dir' to daemon:daemon");
            }
        }
    }

    // Verify writability
    if ($selected_tmp_dir && (!is_dir($selected_tmp_dir) || !is_writable($selected_tmp_dir))) {
        $error_message = "Cannot create or write to temporary directory '$tmp_dir' or fallback '$fallback_tmp_dir'. Generating PDF without charts.";
        error_log("Temporary directory error: $error_message");
        $selected_tmp_dir = null; // Disable chart generation
    }

    $tmp_dir = $selected_tmp_dir;
}

// Check database connection
if (mysqli_connect_errno()) {
    $error_message = "Database connection failed: " . mysqli_connect_error();
    error_log("Database connection error: " . mysqli_connect_error());
}

// Fetch counts for admin dashboard
$total_students = $total_staff = $total_programs = 0;
$submitted_counts = $unsubmitted_counts = $dates = [];
if ($role == 'admin' && empty($error_message)) {
    // Total students
    $query = "SELECT COUNT(*) as total FROM users WHERE role = 'student' AND is_deleted = 0";
    $result = mysqli_query($conn, $query);
    if ($result) {
        $total_students = mysqli_fetch_assoc($result)['total'];
    } else {
        $error_message = "Failed to fetch total students: " . mysqli_error($conn);
        error_log("Query error (total students): " . mysqli_error($conn));
    }

    // Total staff
    $query = "SELECT COUNT(*) as total FROM users WHERE role = 'staff' AND is_deleted = 0";
    $result = mysqli_query($conn, $query);
    if ($result) {
        $total_staff = mysqli_fetch_assoc($result)['total'];
    } else {
        $error_message .= (empty($error_message) ? "" : "; ") . "Failed to fetch total staff: " . mysqli_error($conn);
        error_log("Query error (total staff): " . mysqli_error($conn));
    }

    // Total programs
    $query = "SELECT COUNT(*) as total FROM programs";
    $result = mysqli_query($conn, $query);
    if ($result) {
        $total_programs = mysqli_fetch_assoc($result)['total'];
    } else {
        $error_message .= (empty($error_message) ? "" : "; ") . "Failed to fetch total programs: " . mysqli_error($conn);
        error_log("Query error (total programs): " . mysqli_error($conn));
    }

    // Fetch evaluation data for line graph (last 30 days)
    $start_date = date('Y-m-d', strtotime('-30 days'));
    $end_date = date('Y-m-d');
    
    // Submitted evaluations (grouped by form end_date)
    $query = "SELECT DATE(f.end_date) as eval_date, COUNT(*) as count 
              FROM responses r 
              JOIN evaluation_forms f ON r.form_id = f.form_id 
              WHERE f.end_date BETWEEN ? AND ? 
              GROUP BY DATE(f.end_date)";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'ss', $start_date, $end_date);
        mysqli_stmt_execute($stmt);
        $submitted_data = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    } else {
        $error_message .= (empty($error_message) ? "" : "; ") . "Failed to prepare submitted evaluations query: " . mysqli_error($conn);
        error_log("Prepare error (submitted evaluations): " . mysqli_error($conn));
        $submitted_data = [];
    }

    // Unsubmitted evaluations (forms not responded to by students)
    $query = "SELECT DATE(f.end_date) as due_date, 
                     (SELECT COUNT(*) FROM users u WHERE u.role = 'student' AND u.is_deleted = 0) - COUNT(r.form_id) as count
              FROM evaluation_forms f 
              LEFT JOIN responses r ON r.form_id = f.form_id 
              WHERE f.end_date BETWEEN ? AND ? 
              GROUP BY DATE(f.end_date)";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'ss', $start_date, $end_date);
        mysqli_stmt_execute($stmt);
        $unsubmitted_data = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    } else {
        $error_message .= (empty($error_message) ? "" : "; ") . "Failed to prepare unsubmitted evaluations query: " . mysqli_error($conn);
        error_log("Prepare error (unsubmitted evaluations): " . mysqli_error($conn));
        $unsubmitted_data = [];
    }

    // Prepare data for Chart.js
    $dates = [];
    $submitted_counts = [];
    $unsubmitted_counts = [];
    $current_date = new DateTime($start_date);
    $end = new DateTime($end_date);
    while ($current_date <= $end) {
        $date_str = $current_date->format('Y-m-d');
        $dates[] = $date_str;
        $submitted_counts[$date_str] = 0;
        $unsubmitted_counts[$date_str] = 0;
        $current_date->modify('+1 day');
    }

    foreach ($submitted_data as $row) {
        $submitted_counts[$row['eval_date']] = (int)$row['count'];
    }
    foreach ($unsubmitted_data as $row) {
        $unsubmitted_counts[$row['due_date']] = (int)$row['count'];
    }

    $submitted_counts = array_values($submitted_counts);
    $unsubmitted_counts = array_values($unsubmitted_counts);
    $dates = array_map(function($date) { return date('M d', strtotime($date)); }, $dates);
}

if ($role == 'student') {
    // Get staff assigned to student's class and program
    $query = "SELECT DISTINCT u.id, u.first_name, u.last_name, c.class_name, p.program_name
              FROM users u 
              JOIN class_program_staff cps ON u.id = cps.staff_id
              JOIN classes c ON cps.class_id = c.class_id
              JOIN programs p ON cps.program_id = p.program_id
              JOIN class_program_students cpss ON cps.class_id = cpss.class_id AND cps.program_id = cpss.program_id
              WHERE cpss.student_id = ? AND u.is_deleted = 0";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        $staff = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    } else {
        $error_message = "Failed to fetch assigned staff: " . mysqli_error($conn);
        error_log("Prepare error (student staff query): " . mysqli_error($conn));
        $staff = [];
    }
} elseif ($role == 'staff') {
    // Get evaluation results (existing table)
    $query = "SELECT f.title, q.question_text, r.answer 
              FROM responses r 
              JOIN questions q ON r.question_id = q.question_id 
              JOIN evaluation_forms f ON r.form_id = f.form_id 
              WHERE r.staff_id = ? 
              AND CURDATE() > f.end_date";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        mysqli_stmt_execute($stmt);
        $results = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    } else {
        $error_message = "Failed to fetch evaluation results: " . mysqli_error($conn);
        error_log("Prepare error (staff results query): " . mysqli_error($conn));
        $results = [];
    }

    // Get detailed evaluation report
    $grouped_results = [];
    $report_error = '';

    // Non-single-choice questions
    $query = "SELECT f.form_id, f.title, q.question_id, q.question_text, q.question_type, q.options, r.answer
              FROM responses_new r 
              JOIN questions q ON r.question_id = q.question_id 
              JOIN evaluation_forms f ON r.form_id = f.form_id 
              WHERE r.staff_id = ? AND q.question_type != 'single_choice'";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_id);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            $non_single_choice = mysqli_fetch_all($result, MYSQLI_ASSOC);
            foreach ($non_single_choice as $row) {
                $form_id = $row['form_id'];
                $question_id = $row['question_id'];
                if (!isset($grouped_results[$form_id])) {
                    $grouped_results[$form_id] = [
                        'title' => $row['title'],
                        'questions' => []
                    ];
                }
                if (!isset($grouped_results[$form_id]['questions'][$question_id])) {
                    $grouped_results[$form_id]['questions'][$question_id] = [
                        'question_text' => $row['question_text'],
                        'question_type' => $row['question_type'],
                        'answers' => []
                    ];
                }
                $grouped_results[$form_id]['questions'][$question_id]['answers'][] = $row['answer'];
            }
        } else {
            $report_error = "Query execution failed (non-single_choice): " . mysqli_error($conn);
            error_log("Query error (non-single_choice): " . mysqli_error($conn));
        }
        mysqli_stmt_close($stmt);
    } else {
        $report_error = "Query preparation failed (non-single_choice): " . mysqli_error($conn);
        error_log("Prepare error (non-single_choice): " . mysqli_error($conn));
    }

    // Single-choice questions
    $query = "SELECT f.form_id, f.title, q.question_id, q.question_text, q.question_type, q.options, 
                     r.answer, COUNT(r.answer) AS answer_count, 
                     (SELECT COUNT(*) FROM responses_new r2 WHERE r2.question_id = q.question_id AND r2.staff_id = ?) AS total_count
              FROM responses_new r 
              JOIN questions q ON r.question_id = q.question_id 
              JOIN evaluation_forms f ON r.form_id = f.form_id 
              WHERE r.staff_id = ? AND q.question_type = 'single_choice'
              GROUP BY f.form_id, f.title, q.question_id, q.question_text, q.question_type, q.options, r.answer";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'ss', $user_id, $user_id);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            $raw_results = mysqli_fetch_all($result, MYSQLI_ASSOC);
            foreach ($raw_results as $row) {
                $form_id = $row['form_id'];
                $question_id = $row['question_id'];
                if (!isset($grouped_results[$form_id])) {
                    $grouped_results[$form_id] = [
                        'title' => $row['title'],
                        'questions' => []
                    ];
                }
                if (!isset($grouped_results[$form_id]['questions'][$question_id])) {
                    $grouped_results[$form_id]['questions'][$question_id] = [
                        'question_text' => $row['question_text'],
                        'question_type' => $row['question_type'],
                        'total_count' => $row['total_count'],
                        'answers' => []
                    ];
                }
                $grouped_results[$form_id]['questions'][$question_id]['answers'][$row['answer']] = $row['answer_count'];
            }
        } else {
            $report_error = "Query execution failed (single_choice): " . mysqli_error($conn);
            error_log("Query error (single_choice): " . mysqli_error($conn));
        }
        mysqli_stmt_close($stmt);
    } else {
        $report_error = "Query preparation failed (single_choice): " . mysqli_error($conn);
        error_log("Prepare error (single_choice): " . mysqli_error($conn));
    }

    if (empty($grouped_results) && !$report_error) {
        $report_error = "No responses found for Staff ID: $user_id";
    }
}

// Chart generation functions for PDF
function generatePieChart($data, $labels, $filename) {
    $width = 300;
    $height = 200;
    $image = imagecreatetruecolor($width, $height);
    $bg = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bg);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    imagestring($image, 5, 10, 10, "Pie Chart: " . basename($filename), $text_color);
    foreach ($labels as $i => $label) {
        imagestring($image, 3, 10, 30 + ($i * 20), "$label: {$data[$i]}%", $text_color);
    }
    imagepng($image, $filename);
    imagedestroy($image);
}

function generateLineGraph($data, $labels, $filename) {
    $width = 400;
    $height = 200;
    $image = imagecreatetruecolor($width, $height);
    $bg = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bg);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    imagestring($image, 5, 10, 10, "Line Graph: " . basename($filename), $text_color);
    foreach ($labels as $i => $label) {
        imagestring($image, 3, 10, 30 + ($i * 20), "$label: {$data[$i]}%", $text_color);
    }
    imagepng($image, $filename);
    imagedestroy($image);
}

// Handle PDF export for staff
if ($role === 'staff' && isset($_GET['export']) && empty($error_message)) {
    $output = ob_get_contents();
    $output_length = strlen($output);
    if ($output_length > 0) {
        ob_end_clean();
        die("Unexpected output before PDF (length: $output_length): '" . htmlspecialchars($output) . "'");
    }

    ob_start();
    $pdf = new TCPDF();
    $pdf->SetMargins(15, 15, 15);
    $pdf->SetAutoPageBreak(true, 15);
    $pdf->AddPage();

    // Add letterhead image
    $letterhead_path = '../public/images/letterhead.jpg';
    if (file_exists($letterhead_path)) {
        $pdf->Image($letterhead_path, 10, 10, 190, 0, 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        $pdf->SetY(50);
    } else {
        $pdf->SetY(15);
    }

    // Main title
    $pdf->SetFont('helvetica', 'B', 18);
    $pdf->SetTextColor(0, 51, 102); // Blue
    $pdf->Cell(0, 10, "Evaluation Report for Staff ID: $user_id", 0, 1, 'C');
    $pdf->Ln(10);

    foreach ($grouped_results as $form_id => $form) {
        // Form title with background
        $pdf->SetFont('helvetica', 'B', 14);
        $pdf->SetFillColor(200, 255, 200); // Light green
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 10, $form['title'], 1, 1, 'L', true);
        $pdf->Ln(5);

        // Collect data for line graph
        $line_graph_data = [];
        $line_graph_labels = [];

        foreach ($form['questions'] as $question_id => $question) {
            // Question text
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->MultiCell(0, 8, $question['question_text'], 1, 'L');
            $pdf->SetFont('helvetica', '', 10);
            $pdf->SetTextColor(100, 100, 100); // Gray

            if ($question['question_type'] === 'single_choice') {
                $answer_text = [];
                $pie_data = [];
                $pie_labels = [];
                foreach ($question['answers'] as $answer => $count) {
                    $percentage = $question['total_count'] > 0 ? round(($count / $question['total_count']) * 100, 2) : 0;
                    $answer_text[] = htmlspecialchars("$answer: $percentage%");
                    $pie_data[] = $percentage;
                    $pie_labels[] = $answer;
                }
                // Render answers as HTML with inline CSS
                $html = '<ul style="margin: 5px; padding-left: 20px;">';
                foreach ($answer_text as $text) {
                    $html .= '<li style="color: #646464; font-size: 10pt;">' . $text . '</li>';
                }
                $html .= '</ul>';
                $pdf->writeHTML($html, true, false, true, false, '');

                // Generate and add pie chart (if tmp_dir is available)
                if ($tmp_dir) {
                    $pie_filename = $tmp_dir . "pie_$form_id_$question_id.png";
                    generatePieChart($pie_data, $pie_labels, $pie_filename);
                    if (file_exists($pie_filename)) {
                        $pdf->Image($pie_filename, 15, $pdf->GetY(), 80, 60, 'PNG', '', 'T', false, 300, '', false, false, 1);
                        $pdf->Ln(65);
                    }
                } else {
                    $pdf->SetFont('helvetica', 'I', 10);
                    $pdf->Write(0, "Pie chart unavailable due to temporary directory issues.", '', false, 'L', true);
                    $pdf->Ln(10);
                }

                // Add to line graph data
                foreach ($question['answers'] as $answer => $count) {
                    if (!isset($line_graph_data[$answer])) {
                        $line_graph_data[$answer] = [];
                        $line_graph_labels[] = $answer;
                    }
                    $percentage = $question['total_count'] > 0 ? round(($count / $question['total_count']) * 100, 2) : 0;
                    $line_graph_data[$answer][] = $percentage;
                }
            } else {
                // Non-single-choice answers as numbered list
                $html = '<ol style="margin: 5px; padding-left: 20px;">';
                foreach ($question['answers'] as $index => $answer) {
                    $html .= '<li style="color: #646464; font-size: 10pt;">' . htmlspecialchars($answer) . '</li>';
                }
                $html .= '</ol>';
                $pdf->writeHTML($html, true, false, true, false, '');
            }
            $pdf->Ln(5);
        }

        // Generate line graph (if tmp_dir is available)
        if (!empty($line_graph_data)) {
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->Cell(0, 10, "Answer Trends Across Single-Choice Questions", 1, 1, 'L');
            if ($tmp_dir) {
                $line_filename = $tmp_dir . "line_$form_id.png";
                $line_data = array_values(reset($line_graph_data));
                generateLineGraph($line_data, array_keys($question['answers']), $line_filename);
                if (file_exists($line_filename)) {
                    $pdf->Image($line_filename, 15, $pdf->GetY(), 100, 60, 'PNG', '', 'T', false, 300, '', false, false, 1);
                    $pdf->Ln(65);
                }
            } else {
                $pdf->SetFont('helvetica', 'I', 10);
                $pdf->Write(0, "Line graph unavailable due to temporary directory issues.", '', false, 'L', true);
                $pdf->Ln(10);
            }
        }
        $pdf->Ln(10);
    }

    // Clean up temporary files (if tmp_dir exists)
    if ($tmp_dir) {
        foreach (glob($tmp_dir . "*.png") as $file) {
            unlink($file);
        }
    }

    ob_end_clean();
    $pdf->Output("report_$user_id.pdf", 'D');
    exit;
}

ob_end_clean();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/dashboard.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
    <div class="container">
        <h2><?php echo ucfirst($role); ?> Dashboard</h2>
       
        <?php if ($error_message): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>

        <?php if ($role == 'admin'): ?>
            <div class="mb-3">
                <ul class="nav nav-pills">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="registerMenu" data-bs-toggle="dropdown" aria-expanded="false">Register</a>
                        <ul class="dropdown-menu" aria-labelledby="registerMenu">
                            <li><a class="dropdown-item" href="student_register.php">Register Student</a></li>
                            <li><a class="dropdown-item" href="staff_register.php">Register Staff</a></li>
                        </ul>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="manageMenu" data-bs-toggle="dropdown" aria-expanded="false">Manage</a>
                        <ul class="dropdown-menu" aria-labelledby="manageMenu">
                            <li><a class="dropdown-item" href="manage_roles.php">Manage Roles</a></li>
                            <li><a class="dropdown-item" href="user_manage.php">Manage Users</a></li>
                            <li><a class="dropdown-item" href="class_manage.php">Manage Classes</a></li>
                            <li><a class="dropdown-item" href="program_manage.php">Manage Programs</a></li>
                            <li><a class="dropdown-item" href="manage_evaluation_forms.php">Manage Forms</a></li>
                        </ul>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="form_create.php">Create Evaluation Form</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="assign_staff_class_program.php">Assign Staff to Classes/Program</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="reports.php">View Reports</a>
                    </li>
                    <li class="nav-item">
                        <a href="logout.php" class="btn btn-secondary mb-3">Logout</a>
                    </li>
                </ul>
            </div>

            <h3>System Overview</h3>
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Total Students</h5>
                            <p class="card-text"><?php echo $total_students; ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Total Staff</h5>
                            <p class="card-text"><?php echo $total_staff; ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Total Programs</h5>
                            <p class="card-text"><?php echo $total_programs; ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <h3>Evaluation Submission Status (Last 30 Days)</h3>
            <?php if (empty($error_message)): ?>
                <canvas id="evaluationChart" width="400" height="200"></canvas>
                <script>
                    const ctx = document.getElementById('evaluationChart').getContext('2d');
                    const evaluationChart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: <?php echo json_encode($dates); ?>,
                            datasets: [
                                {
                                    label: 'Submitted Evaluations',
                                    data: <?php echo json_encode($submitted_counts); ?>,
                                    borderColor: 'rgba(75, 192, 192, 1)',
                                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                    fill: true,
                                    tension: 0.4
                                },
                                {
                                    label: 'Unsubmitted Evaluations',
                                    data: <?php echo json_encode($unsubmitted_counts); ?>,
                                    borderColor: 'rgba(255, 99, 132, 1)',
                                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                    fill: true,
                                    tension: 0.4
                                }
                            ]
                        },
                        options: {
                            responsive: true,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: 'Number of Evaluations'
                                    }
                                },
                                x: {
                                    title: {
                                        display: true,
                                        text: 'Date'
                                    }
                                }
                            },
                            plugins: {
                                legend: {
                                    display: true,
                                    position: 'top'
                                }
                            }
                        }
                    });
                </script>
            <?php else: ?>
                <p>Evaluation data unavailable due to database error.</p>
            <?php endif; ?>

        <?php elseif ($role == 'student'): ?>
            <div class="mb-3">
                <a href="logout.php" class="btn btn-secondary mb-3">Logout</a>
            </div>
            <h3>Assigned Staff for Your Classes/Programs</h3>
            <?php if (empty($staff)): ?>
                <p>No staff assigned to your classes/programs.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Staff Name</th>
                            <th>Class</th>
                            <th>Program</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($staff as $s): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name']); ?></td>
                                <td><?php echo htmlspecialchars($s['class_name']); ?></td>
                                <td><?php echo htmlspecialchars($s['program_name']); ?></td>
                                <td><a href="evaluation.php?staff_id=<?php echo $s['id']; ?>" class="btn btn-primary">Evaluate</a></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

        <?php elseif ($role == 'staff'): ?>
            <div class="mb-3">
                <a href="logout.php" class="btn btn-secondary mb-3">Logout</a>
            </div>
            <h3>Your Evaluation Results</h3>
            <?php if (empty($results)): ?>
                <p>No results available.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Form</th>
                            <th>Question</th>
                            <th>Answer</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($results as $r): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($r['title']); ?></td>
                                <td><?php echo htmlspecialchars($r['question_text']); ?></td>
                                <td><?php echo htmlspecialchars($r['answer']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

            <h3>Detailed Evaluation Report</h3>
            <?php if ($report_error): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($report_error); ?></div>
            <?php elseif ($grouped_results): ?>
                <?php foreach ($grouped_results as $form_id => $form): ?>
                    <h4><?php echo htmlspecialchars($form['title']); ?></h4>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Question</th>
                                <th>Answer</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($form['questions'] as $question): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($question['question_text']); ?></td>
                                    <td>
                                        <?php if ($question['question_type'] === 'single_choice'): ?>
                                            <?php
                                            $answer_text = [];
                                            foreach ($question['answers'] as $answer => $count) {
                                                $percentage = $question['total_count'] > 0 ? round(($count / $question['total_count']) * 100, 2) : 0;
                                                $answer_text[] = "$answer: $percentage%";
                                            }
                                            echo htmlspecialchars(implode(', ', $answer_text));
                                            ?>
                                        <?php else: ?>
                                            <ol>
                                                <?php foreach ($question['answers'] as $answer): ?>
                                                    <li><?php echo htmlspecialchars($answer); ?></li>
                                                <?php endforeach; ?>
                                            </ol>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endforeach; ?>
                <a href="?export=1" class="btn btn-primary">Export PDF</a>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</body>
</html>