<?php
// admin/feedback-reports.php - Professional Feedback Dashboard with PDF Export
require_once '../config/config.php';
require_login();

// Get filter parameters
$training_filter = $_GET['training_id'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build query with filters
$query = "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 1=1";

$params = [];

if ($training_filter !== 'all') {
    $query .= " AND f.training_id = ?";
    $params[] = $training_filter;
}

if ($date_from) {
    $query .= " AND DATE(f.submitted_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $query .= " AND DATE(f.submitted_at) <= ?";
    $params[] = $date_to;
}

$query .= " ORDER BY f.submitted_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$feedback_list = $stmt->fetchAll();

// Get all trainings for filter dropdown
$trainings = $pdo->query("SELECT id, course_name, course_date FROM tm_training ORDER BY course_date DESC")->fetchAll();

// Calculate statistics
$total_responses = count($feedback_list);
$avg_ratings = [];
if ($total_responses > 0) {
    foreach ($feedback_list as $feedback) {
        $ratings = json_decode($feedback->ratings_json, true);
        foreach ($ratings as $key => $value) {
            if (is_numeric($value)) {
                if (!isset($avg_ratings[$key])) {
                    $avg_ratings[$key] = ['sum' => 0, 'count' => 0];
                }
                $avg_ratings[$key]['sum'] += $value;
                $avg_ratings[$key]['count']++;
            }
        }
    }
}

$flash = get_flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Feedback Reports - <?php echo APP_NAME; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
        
        body { font-family: 'Inter', sans-serif; }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            transition: transform 0.3s ease;
        }
        .stat-card:hover { transform: translateY(-5px); }
        .stat-card.primary { background: linear-gradient(135deg, #004B75 0%, #006b9b 100%); }
        .stat-card.success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .stat-card.warning { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .stat-card.info { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.6);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: #fefefe;
            padding: 0;
            border-radius: 16px;
            max-width: 900px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .rating-stars {
            color: #ffc107;
            font-size: 18px;
        }
        
        .feedback-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .pdf-generating {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        
        @media print {
            .no-print { display: none !important; }
            body { background: white; }
            .page-break { page-break-before: always; }
        }
    </style>
</head>
<body class="bg-gray-50">
    <?php include 'includes/nav.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex justify-between items-center mb-4">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-chart-line text-blue-600 mr-2"></i>Training Feedback Analytics
                    </h1>
                    <p class="text-gray-600">Comprehensive feedback reports and performance insights</p>
                </div>
                <div class="flex gap-3">
                    <a href="trainings.php" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition">
                        <i class="fas fa-arrow-left mr-2"></i>Back to Trainings
                    </a>
                    <button onclick="exportAllToExcel()" class="px-4 py-2 bg-green-600 text-white rounded-lg font-medium hover:bg-green-700 transition">
                        <i class="fas fa-file-excel mr-2"></i>Export Excel
                    </button>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="stat-card primary rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div class="bg-white/20 rounded-full p-3">
                        <i class="fas fa-comments text-2xl"></i>
                    </div>
                </div>
                <p class="text-white/80 text-sm font-medium mb-1">Total Responses</p>
                <p class="text-4xl font-bold"><?php echo $total_responses; ?></p>
            </div>

            <div class="stat-card success rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div class="bg-white/20 rounded-full p-3">
                        <i class="fas fa-star text-2xl"></i>
                    </div>
                </div>
                <p class="text-white/80 text-sm font-medium mb-1">Average Rating</p>
                <p class="text-4xl font-bold">
                    <?php 
                    if (!empty($avg_ratings)) {
                        $overall_avg = 0;
                        $count = 0;
                        foreach ($avg_ratings as $data) {
                            $overall_avg += $data['sum'] / $data['count'];
                            $count++;
                        }
                        echo $count > 0 ? number_format($overall_avg / $count, 1) : 'N/A';
                    } else {
                        echo 'N/A';
                    }
                    ?>
                </p>
            </div>

            <div class="stat-card warning rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div class="bg-white/20 rounded-full p-3">
                        <i class="fas fa-chalkboard-teacher text-2xl"></i>
                    </div>
                </div>
                <p class="text-white/80 text-sm font-medium mb-1">Trainings Evaluated</p>
                <p class="text-4xl font-bold"><?php echo count(array_unique(array_column($feedback_list, 'training_id'))); ?></p>
            </div>

            <div class="stat-card info rounded-xl shadow-lg p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                    <div class="bg-white/20 rounded-full p-3">
                        <i class="fas fa-calendar-check text-2xl"></i>
                    </div>
                </div>
                <p class="text-white/80 text-sm font-medium mb-1">Latest Response</p>
                <p class="text-2xl font-bold">
                    <?php 
                    if (!empty($feedback_list)) {
                        echo date('M d, Y', strtotime($feedback_list[0]->submitted_at));
                    } else {
                        echo 'No data';
                    }
                    ?>
                </p>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Training Session</label>
                    <select name="training_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="all">All Trainings</option>
                        <?php foreach ($trainings as $t): ?>
                            <option value="<?php echo $t->id; ?>" <?php echo $training_filter == $t->id ? 'selected' : ''; ?>>
                                <?php echo escape($t->course_name); ?> - <?php echo date('M d, Y', strtotime($t->course_date)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">From Date</label>
                    <input type="date" name="date_from" value="<?php echo $date_from; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">To Date</label>
                    <input type="date" name="date_to" value="<?php echo $date_to; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                <div class="flex items-end">
                    <button type="submit" class="w-full px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                </div>
            </form>
        </div>

        <!-- Feedback List -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-list text-blue-600 mr-2"></i>Feedback Submissions
                </h2>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Participant</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Training</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Client</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Submitted</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Overall Rating</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($feedback_list as $feedback): 
                            $ratings = json_decode($feedback->ratings_json, true);
                            $rating_values = array_filter($ratings, 'is_numeric');
                            $avg_rating = !empty($rating_values) ? array_sum($rating_values) / count($rating_values) : 0;
                        ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4">
                                <div class="font-medium text-gray-900"><?php echo escape($feedback->student_name); ?></div>
                                <div class="text-sm text-gray-500"><?php echo escape($feedback->job_role); ?></div>
                                <?php if ($feedback->email): ?>
                                <div class="text-xs text-gray-400"><?php echo escape($feedback->email); ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <div class="font-medium text-gray-900"><?php echo escape($feedback->course_name); ?></div>
                                <div class="text-sm text-gray-500">Instructor: <?php echo escape($feedback->instructor_name); ?></div>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-900">
                                <?php echo escape($feedback->client_name); ?>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500">
                                <?php echo date('M d, Y', strtotime($feedback->submitted_at)); ?><br>
                                <?php echo date('h:i A', strtotime($feedback->submitted_at)); ?>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center">
                                    <span class="rating-stars mr-2">
                                        <?php 
                                        for ($i = 1; $i <= 5; $i++) {
                                            echo $i <= round($avg_rating) ? '★' : '☆';
                                        }
                                        ?>
                                    </span>
                                    <span class="text-sm font-semibold text-gray-700"><?php echo number_format($avg_rating, 1); ?></span>
                                </div>
                            </td>
                            <td class="px-6 py-4 text-sm font-medium space-x-3">
                                <button onclick="viewFeedback(<?php echo $feedback->feedback_id; ?>)" 
                                    class="text-blue-600 hover:text-blue-900">
                                    <i class="fas fa-eye"></i> View
                                </button>
                                <button onclick="downloadFeedbackPDF(<?php echo $feedback->feedback_id; ?>)" 
                                    class="text-red-600 hover:text-red-900">
                                    <i class="fas fa-file-pdf"></i> PDF
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($feedback_list)): ?>
                        <tr>
                            <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-2"></i>
                                <p>No feedback submissions found.</p>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Feedback Detail Modal -->
    <div id="feedbackModal" class="modal">
        <div class="modal-content">
            <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white p-6 rounded-t-xl">
                <div class="flex justify-between items-center">
                    <h2 class="text-2xl font-bold">
                        <i class="fas fa-chart-bar mr-2"></i> Detailed Feedback Report
                    </h2>
                    <button onclick="closeModal()" class="text-white hover:text-gray-200 text-2xl">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <div id="modalContent" class="p-6">
                <div class="text-center py-8">
                    <i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i>
                    <p class="mt-4 text-gray-600">Loading feedback...</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        function viewFeedback(feedbackId) {
            const modal = document.getElementById('feedbackModal');
            const modalContent = document.getElementById('modalContent');
            
            modal.classList.add('active');
            document.body.style.overflow = 'hidden';
            
            // Fetch feedback details via AJAX
            fetch(`feedback-detail.php?id=${feedbackId}`)
                .then(response => response.text())
                .then(html => {
                    modalContent.innerHTML = html;
                })
                .catch(error => {
                    modalContent.innerHTML = '<div class="text-center py-8 text-red-600"><i class="fas fa-exclamation-triangle text-4xl mb-4"></i><p>Error loading feedback</p></div>';
                });
        }
        
        function closeModal() {
            const modal = document.getElementById('feedbackModal');
            modal.classList.remove('active');
            document.body.style.overflow = '';
        }
        
        async function downloadFeedbackPDF(feedbackId) {
            // Show loading
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'pdf-generating';
            loadingDiv.innerHTML = `
                <div class="bg-white rounded-xl p-8 text-center">
                    <i class="fas fa-file-pdf text-6xl text-red-500 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">Generating PDF Report</h3>
                    <p class="text-gray-600">Please wait...</p>
                </div>
            `;
            document.body.appendChild(loadingDiv);
            
            try {
                // Redirect to PDF generation endpoint
                window.location.href = `feedback-pdf.php?id=${feedbackId}`;
                
                setTimeout(() => {
                    document.body.removeChild(loadingDiv);
                }, 2000);
            } catch (error) {
                console.error('PDF Generation Error:', error);
                document.body.removeChild(loadingDiv);
            }
        }
        
        function exportAllToExcel() {
            window.location.href = 'feedback-export.php<?php echo $training_filter !== "all" ? "?training_id=$training_filter" : ""; ?>';
        }
        
        // Close modal on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });
        
        // Close modal on outside click
        document.getElementById('feedbackModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>