<?php
// admin/feedback-detail.php - AJAX endpoint for modal content
require_once '../config/config.php';
require_login();

$feedback_id = $_GET['id'] ?? 0;

if (!$feedback_id) {
    echo '<div class="text-center py-8 text-red-600"><i class="fas fa-exclamation-triangle text-4xl mb-4"></i><p>Invalid feedback ID</p></div>';
    exit;
}

$stmt = $pdo->prepare("
    SELECT 
        f.id as feedback_id,
        f.training_id,
        f.student_name,
        f.email,
        f.job_role,
        f.company_name,
        f.ratings_json,
        f.question_json,
        f.submitted_at,
        t.course_name,
        t.instructor_name,
        t.client_name,
        t.course_date,
        t.course_venue
    FROM tm_feedback f
    LEFT JOIN tm_training t ON f.training_id = t.id
    WHERE f.id = ?
");
$stmt->execute([$feedback_id]);
$feedback = $stmt->fetch();

if (!$feedback) {
    echo '<div class="text-center py-8 text-red-600"><i class="fas fa-exclamation-triangle text-4xl mb-4"></i><p>Feedback not found</p></div>';
    exit;
}

$ratings = json_decode($feedback->ratings_json, true);
$questions = json_decode($feedback->question_json, true);

// Define rating categories to match form structure
$rating_categories = [
    'Instructor Evaluation' => [
        'color' => 'from-blue-500 to-blue-600',
        'questions' => [
            'instructor_knowledge' => 'Instructor\'s knowledge of the subject matter',
            'instructor_response' => 'Instructor\'s response to questions',
            'instructor_relevance' => 'Instructor\'s ability to provide real world examples',
            'instructor_delivery' => 'Instructor\'s presentation skills',
            'instructor_overall' => 'Instructor\'s overall performance'
        ]
    ],
    'Training Content' => [
        'color' => 'from-purple-500 to-purple-600',
        'questions' => [
            'content_clarity' => 'Clarity of the training content',
            'content_flow' => 'Flow of the training content',
            'content_depth' => 'Depth of the training content',
            'content_effectiveness' => 'Effectiveness of the exercises in knowledge/skills learned',
            'content_relevance' => 'Relevance of the exercises to real world situations',
            'content_time' => 'Time dedicated to discussions and practices'
        ]
    ],
    'Learning Effectiveness' => [
        'color' => 'from-green-500 to-green-600',
        'questions' => [
            'learning_gained' => 'Knowledge and skills gained from this training',
            'learning_impact' => 'Impact of this training on your productivity related to the subject',
            'overall_rating' => 'How do you rate the training overall?'
        ]
    ]
];

// Objective checkboxes
$objective_questions = [
    'objective_solve' => 'Solve a particular problem',
    'objective_prepare_deploy' => 'Prepare for a new product deployment or software upgrade',
    'objective_cert' => 'Prepare for certification exam',
    'objective_build' => 'Build new skills and knowledge'
];

// Open-ended questions
$open_ended_questions = [
    'open_suggestions' => 'Suggestions for improving the course or Overall Training Experience?',
    'open_future_topics' => 'Are there any additional training topics or courses you would be interested in attending in the future?',
    'open_objectives_others' => 'Others (Please specify)'
];

// Calculate average rating from numeric values only
$rating_values = [];
foreach ($rating_categories as $categoryData) {
    foreach ($categoryData['questions'] as $key => $label) {
        if (isset($ratings[$key]) && is_numeric($ratings[$key])) {
            $rating_values[] = $ratings[$key];
        }
    }
}
$avg_rating = !empty($rating_values) ? array_sum($rating_values) / count($rating_values) : 0;

// Helper function for rating color
function getRatingColor($rating) {
    if ($rating >= 4.5) return 'bg-green-500';
    if ($rating >= 3.5) return 'bg-blue-500';
    if ($rating >= 2.5) return 'bg-yellow-500';
    return 'bg-red-500';
}
?>

<!-- Overall Score Card -->
<div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg p-6 mb-6">
    <div class="text-center">
        <p class="text-sm uppercase tracking-wide opacity-90 mb-2">Overall Satisfaction Score</p>
        <div class="text-6xl font-bold mb-2"><?php echo number_format($avg_rating, 1); ?></div>
        <div class="text-2xl mb-2">
            <?php 
            for ($i = 1; $i <= 5; $i++) {
                echo $i <= round($avg_rating) ? '★' : '☆';
            }
            ?>
        </div>
        <p class="text-sm opacity-90">Based on <?php echo count($rating_values); ?> rating criteria</p>
    </div>
</div>

<!-- Participant Information -->
<div class="bg-gray-50 rounded-lg p-6 mb-6">
    <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
        <i class="fas fa-user-circle text-blue-600 mr-2"></i> Participant Information
    </h3>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
            <p class="text-sm text-gray-600 mb-1">Name</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->student_name); ?></p>
        </div>
        <?php if ($feedback->email): ?>
        <div>
            <p class="text-sm text-gray-600 mb-1">Email</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->email); ?></p>
        </div>
        <?php endif; ?>
        <div>
            <p class="text-sm text-gray-600 mb-1">Job Role</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->job_role); ?></p>
        </div>
        <?php if ($feedback->company_name): ?>
        <div>
            <p class="text-sm text-gray-600 mb-1">Company</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->company_name); ?></p>
        </div>
        <?php endif; ?>
        <div>
            <p class="text-sm text-gray-600 mb-1">Submitted On</p>
            <p class="font-semibold text-gray-900"><?php echo date('F d, Y \a\t h:i A', strtotime($feedback->submitted_at)); ?></p>
        </div>
    </div>
</div>

<!-- Training Information -->
<div class="bg-gray-50 rounded-lg p-6 mb-6">
    <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
        <i class="fas fa-chalkboard-teacher text-blue-600 mr-2"></i> Training Information
    </h3>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
            <p class="text-sm text-gray-600 mb-1">Course Name</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->course_name); ?></p>
        </div>
        <div>
            <p class="text-sm text-gray-600 mb-1">Instructor</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->instructor_name); ?></p>
        </div>
        <div>
            <p class="text-sm text-gray-600 mb-1">Client</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->client_name); ?></p>
        </div>
        <div>
            <p class="text-sm text-gray-600 mb-1">Training Date</p>
            <p class="font-semibold text-gray-900"><?php echo date('F d, Y', strtotime($feedback->course_date)); ?></p>
        </div>
        <div>
            <p class="text-sm text-gray-600 mb-1">Venue</p>
            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($feedback->course_venue); ?></p>
        </div>
    </div>
</div>

<!-- Detailed Ratings by Category -->
<?php foreach ($rating_categories as $categoryName => $categoryData): ?>
    <?php
    // Calculate category average
    $categoryValues = [];
    foreach ($categoryData['questions'] as $key => $label) {
        if (isset($ratings[$key]) && is_numeric($ratings[$key])) {
            $categoryValues[] = $ratings[$key];
        }
    }
    $categoryAvg = !empty($categoryValues) ? array_sum($categoryValues) / count($categoryValues) : 0;
    ?>
    
    <div class="bg-white rounded-lg border border-gray-200 overflow-hidden mb-6">
        <!-- Category Header -->
        <div class="bg-gradient-to-r <?php echo $categoryData['color']; ?> text-white p-4">
            <div class="flex justify-between items-center">
                <h3 class="text-lg font-bold"><?php echo $categoryName; ?></h3>
                <div class="flex items-center">
                    <span class="text-xl mr-2">
                        <?php 
                        for ($i = 1; $i <= 5; $i++) {
                            echo $i <= round($categoryAvg) ? '★' : '☆';
                        }
                        ?>
                    </span>
                    <span class="font-bold text-xl"><?php echo number_format($categoryAvg, 1); ?>/5</span>
                </div>
            </div>
        </div>
        
        <!-- Questions -->
        <div class="p-4 space-y-4">
            <?php foreach ($categoryData['questions'] as $key => $label): ?>
                <?php if (isset($ratings[$key]) && is_numeric($ratings[$key])): ?>
                    <?php $value = $ratings[$key]; ?>
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-sm font-medium text-gray-700"><?php echo htmlspecialchars($label); ?></span>
                            <div class="flex items-center">
                                <span class="text-yellow-500 mr-2">
                                    <?php 
                                    for ($i = 1; $i <= 5; $i++) {
                                        echo $i <= $value ? '★' : '☆';
                                    }
                                    ?>
                                </span>
                                <span class="text-sm font-bold text-gray-900"><?php echo $value; ?>/5</span>
                            </div>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-2">
                            <div class="<?php echo getRatingColor($value); ?> h-2 rounded-full transition-all duration-500" 
                                 style="width: <?php echo ($value / 5 * 100); ?>%"></div>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    </div>
<?php endforeach; ?>

<!-- Pre-Training Objectives -->
<?php
$selectedObjectives = [];
foreach ($objective_questions as $key => $label) {
    if (isset($ratings[$key]) && $ratings[$key] == '1') {
        $selectedObjectives[] = $label;
    }
}
?>

<?php if (!empty($selectedObjectives) || (!empty($ratings['open_objectives_others']) && $ratings['open_objectives_others'] !== 'N/A')): ?>
<div class="bg-white rounded-lg border border-gray-200 p-6 mb-6">
    <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
        <i class="fas fa-bullseye text-blue-600 mr-2"></i> Pre-Training Objectives
    </h3>
    <div class="space-y-2">
        <?php foreach ($selectedObjectives as $objective): ?>
            <div class="flex items-start">
                <i class="fas fa-check-circle text-green-500 mr-2 mt-1"></i>
                <span class="text-gray-700"><?php echo htmlspecialchars($objective); ?></span>
            </div>
        <?php endforeach; ?>
        
        <?php if (!empty($ratings['open_objectives_others']) && $ratings['open_objectives_others'] !== 'N/A'): ?>
            <div class="flex items-start">
                <i class="fas fa-check-circle text-green-500 mr-2 mt-1"></i>
                <span class="text-gray-700">Others: <?php echo htmlspecialchars($ratings['open_objectives_others']); ?></span>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- Open-ended Feedback -->
<?php
$textResponses = [];
foreach ($open_ended_questions as $key => $label) {
    if ($key === 'open_objectives_others') continue; // Already shown above
    if (isset($ratings[$key]) && !empty(trim($ratings[$key])) && $ratings[$key] !== 'N/A') {
        $textResponses[$key] = ['label' => $label, 'answer' => $ratings[$key]];
    }
}
?>

<?php if (!empty($textResponses)): ?>
<div class="bg-white rounded-lg border border-gray-200 p-6 mb-6">
    <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center">
        <i class="fas fa-comments text-blue-600 mr-2"></i> Additional Feedback & Suggestions
    </h3>
    <div class="space-y-4">
        <?php foreach ($textResponses as $data): ?>
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-sm font-semibold text-gray-700 mb-2"><?php echo htmlspecialchars($data['label']); ?></p>
                <p class="text-gray-900 whitespace-pre-wrap"><?php echo htmlspecialchars($data['answer']); ?></p>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Action Buttons -->
<div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
    <button onclick="closeModal()" class="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition">
        <i class="fas fa-times mr-2"></i>Close
    </button>
    <button onclick="downloadFeedbackPDF(<?php echo $feedback_id; ?>)" class="px-6 py-2 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 transition">
        <i class="fas fa-file-pdf mr-2"></i>Download PDF
    </button>
</div>