<?php
require_once '../config/config.php';
requireRole('secretariat');

$pageTitle = 'Evaluation Results - Admin - PSAU GAD';
$db = getDB();

// Get form_id from URL
$formId = isset($_GET['form_id']) ? (int)$_GET['form_id'] : 0;

if (!$formId) {
    header('Location: evaluation-management.php');
    exit;
}

// Get form details
$stmt = $db->prepare("
    SELECT ef.*, a.title as activity_title, a.activity_date
    FROM evaluation_forms ef
    JOIN activities a ON ef.activity_id = a.activity_id
    WHERE ef.form_id = ?
");
$stmt->execute([$formId]);
$form = $stmt->fetch();

if (!$form) {
    header('Location: evaluation-management.php');
    exit;
}

// Get all questions
$stmt = $db->prepare("
    SELECT * FROM evaluation_questions 
    WHERE form_id = ? 
    ORDER BY order_num ASC
");
$stmt->execute([$formId]);
$questions = $stmt->fetchAll();

// Get all responses with user info
$stmt = $db->prepare("
    SELECT 
        er.*,
        u.first_name,
        u.last_name,
        u.email,
        u.department
    FROM evaluation_responses er
    JOIN users u ON er.user_id = u.user_id
    WHERE er.form_id = ?
    ORDER BY er.submitted_at DESC
");
$stmt->execute([$formId]);
$responses = $stmt->fetchAll();

// Calculate statistics for each question
$questionStats = [];
foreach ($questions as $question) {
    $questionId = $question['question_id'];
    
    // Get all answers for this question
    $stmt = $db->prepare("
        SELECT ea.answer_text
        FROM evaluation_answers ea
        JOIN evaluation_responses er ON ea.response_id = er.response_id
        WHERE ea.question_id = ? AND er.form_id = ?
    ");
    $stmt->execute([$questionId, $formId]);
    $answers = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $stats = [
        'total_responses' => count($answers),
        'answers' => $answers
    ];
    
    // Calculate rating statistics
    if ($question['question_type'] === 'rating') {
        $numericAnswers = array_map('intval', array_filter($answers, 'is_numeric'));
        if (!empty($numericAnswers)) {
            $stats['average'] = round(array_sum($numericAnswers) / count($numericAnswers), 2);
            $stats['distribution'] = array_count_values($numericAnswers);
        }
    }
    
    // Calculate yes/no statistics
    if ($question['question_type'] === 'yes_no') {
        $stats['distribution'] = array_count_values($answers);
    }
    
    $questionStats[$questionId] = $stats;
}

// Export to Excel
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="evaluation_results_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header row
    $headers = ['Response ID', 'Name', 'Email', 'Department', 'Submitted At'];
    foreach ($questions as $question) {
        $headers[] = substr($question['question_text'], 0, 50);
    }
    fputcsv($output, $headers);
    
    // Data rows
    foreach ($responses as $response) {
        $row = [
            $response['response_id'],
            $response['first_name'] . ' ' . $response['last_name'],
            $response['email'],
            $response['department'],
            date('Y-m-d H:i', strtotime($response['submitted_at']))
        ];
        
        foreach ($questions as $question) {
            $stmt = $db->prepare("
                SELECT answer_text 
                FROM evaluation_answers 
                WHERE response_id = ? AND question_id = ?
            ");
            $stmt->execute([$response['response_id'], $question['question_id']]);
            $answer = $stmt->fetchColumn();
            $row[] = $answer ?: 'N/A';
        }
        
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;
}

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-4">
                <div class="flex items-center">
                    <a href="evaluation-management.php" class="text-secretariat hover:text-secretariat-dark mr-4">
                        <i class="fas fa-arrow-left text-xl"></i>
                    </a>
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900 mb-2">
                            <i class="fas fa-chart-bar text-secretariat mr-2"></i>Evaluation Results
                        </h1>
                        <p class="text-gray-600">
                            <?php echo htmlspecialchars($form['title']); ?> - 
                            <?php echo htmlspecialchars($form['activity_title']); ?>
                        </p>
                    </div>
                </div>
                <a href="?form_id=<?php echo $formId; ?>&export=excel" 
                   class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition font-semibold">
                    <i class="fas fa-file-excel mr-2"></i>Export to Excel
                </a>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-secretariat">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Total Responses</p>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo count($responses); ?></h3>
                    </div>
                    <div class="bg-blue-100 p-4 rounded-full">
                        <i class="fas fa-users text-secretariat text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Questions</p>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo count($questions); ?></h3>
                    </div>
                    <div class="bg-green-100 p-4 rounded-full">
                        <i class="fas fa-question-circle text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Response Rate</p>
                        <?php
                        // Calculate response rate
                        $stmt = $db->prepare("
                            SELECT COUNT(*) 
                            FROM activity_attendance aa
                            JOIN activity_registrations ar ON aa.registration_id = ar.registration_id
                            JOIN activities a ON ar.activity_id = a.activity_id
                            WHERE a.activity_id = ? AND aa.status IN ('present', 'late')
                        ");
                        $stmt->execute([$form['activity_id']]);
                        $totalAttendees = $stmt->fetchColumn();
                        $responseRate = $totalAttendees > 0 ? round((count($responses) / $totalAttendees) * 100) : 0;
                        ?>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $responseRate; ?>%</h3>
                    </div>
                    <div class="bg-yellow-100 p-4 rounded-full">
                        <i class="fas fa-percentage text-yellow-600 text-2xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm font-semibold">Avg Rating</p>
                        <?php
                        // Calculate overall average rating
                        $ratingQuestions = array_filter($questions, fn($q) => $q['question_type'] === 'rating');
                        $totalAvg = 0;
                        $count = 0;
                        foreach ($ratingQuestions as $q) {
                            if (isset($questionStats[$q['question_id']]['average'])) {
                                $totalAvg += $questionStats[$q['question_id']]['average'];
                                $count++;
                            }
                        }
                        $overallAvg = $count > 0 ? round($totalAvg / $count, 1) : 0;
                        ?>
                        <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $overallAvg; ?>/5</h3>
                    </div>
                    <div class="bg-purple-100 p-4 rounded-full">
                        <i class="fas fa-star text-purple-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Question Analysis -->
        <div class="space-y-6">
            <?php foreach ($questions as $index => $question): ?>
                <?php $stats = $questionStats[$question['question_id']]; ?>
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <div class="mb-4">
                        <h3 class="text-lg font-bold text-gray-900 mb-2">
                            <?php echo $index + 1; ?>. <?php echo htmlspecialchars($question['question_text']); ?>
                        </h3>
                        <span class="text-sm text-gray-500">
                            <?php 
                            $typeLabels = [
                                'rating' => '⭐ Rating',
                                'yes_no' => '✓ Yes/No',
                                'text' => '📝 Text Response'
                            ];
                            echo $typeLabels[$question['question_type']];
                            ?> • <?php echo $stats['total_responses']; ?> responses
                        </span>
                    </div>
                    
                    <?php if ($question['question_type'] === 'rating' && isset($stats['average'])): ?>
                        <!-- Rating Statistics -->
                        <div class="mb-4">
                            <div class="flex items-center mb-3">
                                <span class="text-3xl font-bold text-yellow-500 mr-3"><?php echo $stats['average']; ?></span>
                                <div class="flex">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star text-2xl <?php echo $i <= round($stats['average']) ? 'text-yellow-400' : 'text-gray-300'; ?>"></i>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            
                            <!-- Distribution Bars -->
                            <div class="space-y-2">
                                <?php for ($rating = 5; $rating >= 1; $rating--): ?>
                                    <?php 
                                    $count = $stats['distribution'][$rating] ?? 0;
                                    $percentage = $stats['total_responses'] > 0 ? ($count / $stats['total_responses']) * 100 : 0;
                                    ?>
                                    <div class="flex items-center">
                                        <span class="w-12 text-sm text-gray-600"><?php echo $rating; ?> ⭐</span>
                                        <div class="flex-1 bg-gray-200 rounded-full h-6 mx-3">
                                            <div class="bg-yellow-400 h-6 rounded-full flex items-center justify-end pr-2" 
                                                 style="width: <?php echo $percentage; ?>%">
                                                <?php if ($count > 0): ?>
                                                    <span class="text-xs font-semibold text-gray-700"><?php echo $count; ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <span class="w-16 text-sm text-gray-600 text-right"><?php echo round($percentage); ?>%</span>
                                    </div>
                                <?php endfor; ?>
                            </div>
                        </div>
                        
                    <?php elseif ($question['question_type'] === 'yes_no' && isset($stats['distribution'])): ?>
                        <!-- Yes/No Statistics -->
                        <div class="grid grid-cols-2 gap-4">
                            <?php 
                            $yesCount = $stats['distribution']['Yes'] ?? 0;
                            $noCount = $stats['distribution']['No'] ?? 0;
                            $yesPercentage = $stats['total_responses'] > 0 ? ($yesCount / $stats['total_responses']) * 100 : 0;
                            $noPercentage = $stats['total_responses'] > 0 ? ($noCount / $stats['total_responses']) * 100 : 0;
                            ?>
                            <div class="bg-green-50 border-2 border-green-500 rounded-lg p-4 text-center">
                                <div class="text-4xl font-bold text-green-600 mb-2"><?php echo $yesCount; ?></div>
                                <div class="text-sm text-gray-600 mb-2">Yes (<?php echo round($yesPercentage); ?>%)</div>
                                <div class="w-full bg-gray-200 rounded-full h-2">
                                    <div class="bg-green-500 h-2 rounded-full" style="width: <?php echo $yesPercentage; ?>%"></div>
                                </div>
                            </div>
                            <div class="bg-red-50 border-2 border-red-500 rounded-lg p-4 text-center">
                                <div class="text-4xl font-bold text-red-600 mb-2"><?php echo $noCount; ?></div>
                                <div class="text-sm text-gray-600 mb-2">No (<?php echo round($noPercentage); ?>%)</div>
                                <div class="w-full bg-gray-200 rounded-full h-2">
                                    <div class="bg-red-500 h-2 rounded-full" style="width: <?php echo $noPercentage; ?>%"></div>
                                </div>
                            </div>
                        </div>
                        
                    <?php elseif ($question['question_type'] === 'text'): ?>
                        <!-- Text Responses -->
                        <div class="space-y-3 max-h-96 overflow-y-auto">
                            <?php foreach ($stats['answers'] as $answer): ?>
                                <?php if (!empty($answer)): ?>
                                    <div class="bg-gray-50 border-l-4 border-secretariat p-4 rounded">
                                        <p class="text-gray-700"><?php echo nl2br(htmlspecialchars($answer)); ?></p>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                            <?php if (empty(array_filter($stats['answers']))): ?>
                                <p class="text-gray-500 italic">No responses yet</p>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

