<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
session_start();
require '../includes/config.php';
require '../vendor/tcpdf/tcpdf.php';

// Debug log
$debug_log = __DIR__ . '/debug.log';
file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] reports.php executed\n", FILE_APPEND);

// Access control: Admin only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Unauthorized access\n", FILE_APPEND);
    ob_end_clean();
    header('Location: dashboard.php');
    exit;
}

// Directory for temporary files (not needed for graphs anymore, but kept for potential future use)
$tmp_dir = __DIR__ . '/tmp/';
$fallback_tmp_dir = '/tmp/appraisal_tmp/';

// Ensure a writable temporary directory
$selected_tmp_dir = $tmp_dir;
if (!is_dir($tmp_dir) && !@mkdir($tmp_dir, 0755, true)) {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Failed to create tmp_dir: $tmp_dir\n", FILE_APPEND);
    $selected_tmp_dir = $fallback_tmp_dir;
}
if (!is_dir($selected_tmp_dir) && !@mkdir($selected_tmp_dir, 0755, true)) {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Failed to create fallback_tmp_dir: $fallback_tmp_dir\n", FILE_APPEND);
}
if (!is_dir($selected_tmp_dir) || !is_writable($selected_tmp_dir)) {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Cannot write to tmp_dir: $selected_tmp_dir\n", FILE_APPEND);
    ob_end_clean();
    die("Error: Cannot create or write to temporary directory '$tmp_dir' or fallback '$fallback_tmp_dir'. Please check permissions.");
}
$tmp_dir = $selected_tmp_dir;
file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Using tmp_dir: $tmp_dir\n", FILE_APPEND);

// Get staff for dropdown
$staff = mysqli_fetch_all(mysqli_query($conn, "SELECT id, first_name, last_name FROM users WHERE role = 'staff' AND is_deleted = 0"), MYSQLI_ASSOC);
file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Fetched " . count($staff) . " staff members\n", FILE_APPEND);

$grouped_results = [];
$staff_id = $_GET['staff_id'] ?? '';
$error = '';

if ($staff_id) {
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Processing staff_id: $staff_id\n", FILE_APPEND);
    $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) {
        $error = "Query preparation failed (non-single_choice): " . mysqli_error($conn);
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Non-single-choice query failed: " . mysqli_error($conn) . "\n", FILE_APPEND);
    } else {
        mysqli_stmt_bind_param($stmt, 's', $staff_id);
        if (!mysqli_stmt_execute($stmt)) {
            $error = "Query execution failed (non-single_choice): " . mysqli_error($conn);
            file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Non-single-choice query execution failed: " . mysqli_error($conn) . "\n", FILE_APPEND);
        } else {
            $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'];
            }
            file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Fetched " . count($non_single_choice) . " non-single-choice responses\n", FILE_APPEND);
        }
        mysqli_stmt_close($stmt);
    }

    $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) {
        $error = "Query preparation failed (single_choice): " . mysqli_error($conn);
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Single-choice query failed: " . mysqli_error($conn) . "\n", FILE_APPEND);
    } else {
        mysqli_stmt_bind_param($stmt, 'ss', $staff_id, $staff_id);
        if (!mysqli_stmt_execute($stmt)) {
            $error = "Query execution failed (single_choice): " . mysqli_error($conn);
            file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Single-choice query execution failed: " . mysqli_error($conn) . "\n", FILE_APPEND);
        } else {
            $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'];
            }
            file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Fetched " . count($raw_results) . " single-choice responses\n", FILE_APPEND);
        }
        mysqli_stmt_close($stmt);
    }

    if (empty($grouped_results)) {
        $error = "No responses found for Staff ID: $staff_id";
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] No responses for staff_id: $staff_id\n", FILE_APPEND);
    }
}

if (isset($_GET['export']) && $staff_id) {
    $output = ob_get_contents();
    $output_length = strlen($output);
    if ($output_length > 0) {
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Unexpected output before PDF: $output\n", FILE_APPEND);
        ob_end_clean();
        die("Unexpected output before PDF (length: $output_length): '" . htmlspecialchars($output) . "'");
    }

    ob_start();
    $pdf = new TCPDF();
    $pdf->SetMargins(15, 25, 15);
    $pdf->SetAutoPageBreak(true, 15);
    $pdf->SetFont('helvetica', '', 12);
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] PDF initialized\n", FILE_APPEND);

    // Set header
    $pdf->setHeaderData('', 0, "Evaluation Report", "Staff ID: $staff_id", array(0, 38, 77), array(255, 255, 255));
    $pdf->setHeaderFont(array('helvetica', '', 10));
    $pdf->setHeaderMargin(10);

    // Set footer
    $pdf->setFooterData(array(0, 38, 77));
    $pdf->setFooterFont(array('helvetica', '', 8));
    $pdf->setFooterMargin(10);

    // Add cover page
    $pdf->AddPage();
    $pdf->SetFont('helvetica', 'B', 24);
    $pdf->SetTextColor(0, 38, 77); // Dark blue
    $pdf->Cell(0, 20, "Evaluation Report", 0, 1, 'C');
    $pdf->SetFont('helvetica', '', 16);
    $pdf->Cell(0, 10, "Staff ID: $staff_id", 0, 1, 'C');
    $pdf->SetFont('helvetica', 'I', 12);
    $pdf->Cell(0, 10, "Generated on: " . date('F j, Y'), 0, 1, 'C');
    $pdf->SetFont('helvetica', 'I', 10);
    $pdf->SetTextColor(139, 0, 0); // Red
    $pdf->Cell(0, 10, "DEBUG: No Graphs 2025-05-11", 0, 1, 'C');
    $pdf->Ln(20);
    $pdf->SetFillColor(139, 0, 0); // Red
    $pdf->Rect(15, $pdf->GetY(), 180, 0.5, 'F'); // Red horizontal line
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Cover page added\n", FILE_APPEND);

    // Add watermark
    $pdf->SetFont('helvetica', 'I', 40);
    $pdf->SetTextColor(139, 0, 0, 10); // Light red (10% opacity)
    $pdf->StartTransform();
    $pdf->Rotate(45, 100, 150);
    $pdf->Write(0, 'Confidential', '', 0, 'C', true, 0, false, false, 0);
    $pdf->StopTransform();
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Watermark added\n", FILE_APPEND);

    // Start content page
    $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);
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Letterhead added\n", FILE_APPEND);
    } else {
        $pdf->SetY(25);
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Letterhead not found\n", FILE_APPEND);
    }

    foreach ($grouped_results as $form_id => $form) {
        // Form title with rounded rectangle
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(0, 38, 77); // Dark blue
        $pdf->SetFillColor(255, 255, 255); // White
        $pdf->SetDrawColor(139, 0, 0); // Red
        $pdf->RoundedRect(15, $pdf->GetY(), 180, 12, 3, '1111', 'FD');
        $pdf->SetXY(20, $pdf->GetY() + 2);
        $pdf->Cell(0, 10, $form['title'], 0, 1, 'L');
        $pdf->Ln(8);
        file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Form title added: {$form['title']}\n", FILE_APPEND);

        foreach ($form['questions'] as $question_id => $question) {
            // Question text
            $pdf->SetFont('helvetica', 'B', 14);
            $pdf->SetTextColor(0, 38, 77); // Dark blue
            $pdf->MultiCell(0, 8, $question['question_text'], 'B', 'L', false, 1, '', '', true, 0, false, true, 8, 'T');
            $pdf->SetFont('helvetica', '', 12);
            $pdf->SetTextColor(64, 64, 64); // Dark gray
            file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Question added: {$question['question_text']}\n", FILE_APPEND);

            if ($question['question_type'] === 'single_choice') {
                $answer_text = [];
                foreach ($question['answers'] as $answer => $count) {
                    $percentage = $question['total_count'] > 0 ? round(($count / $question['total_count']) * 100, 2) : 0;
                    $answer_text[] = htmlspecialchars("$answer: $percentage%");
                }
                // Render answers as HTML with red bullet points
                $html = '<ul style="margin: 5px; padding-left: 20px;">';
                foreach ($answer_text as $text) {
                    $html .= '<li style="color: #404040; font-size: 10pt; list-style-type: disc; color: #8B0000;">' . $text . '</li>';
                }
                $html .= '</ul>';
                $pdf->writeHTML($html, true, false, true, false, '');
                file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Single-choice answers added\n", FILE_APPEND);
            } 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: #404040; font-size: 10pt;">' . htmlspecialchars($answer) . '</li>';
                }
                $html .= '</ol>';
                $pdf->writeHTML($html, true, false, true, false, '');
                file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] Text answers added\n", FILE_APPEND);
            }
            $pdf->Ln(8);
        }
        $pdf->Ln(10);
    }

    ob_end_clean();
    $pdf->Output("report_$staff_id.pdf", 'D');
    file_put_contents($debug_log, "[" . date('Y-m-d H:i:s') . "] PDF output generated\n", FILE_APPEND);
    exit;
}

ob_end_clean();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reports</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/register.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Evaluation Reports</h2>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="GET">
            <div class="form-group">
                <label>Select Staff</label>
                <select name="staff_id" class="form-control" required>
                    <option value="">-- Select Staff --</option>
                    <?php foreach ($staff as $s): ?>
                        <option value="<?php echo $s['id']; ?>" <?php if ($staff_id == $s['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">View Report</button>
        </form>

        <?php if ($grouped_results): ?>
            <h3>Report for Staff ID: <?php echo htmlspecialchars($staff_id); ?></h3>
            <?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="?staff_id=<?php echo htmlspecialchars($staff_id); ?>&export=1" class="btn btn-primary">Export PDF</a>
        <?php endif; ?>
        <a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>