<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not admin - using functions from connection.php
if (!is_logged_in() || !is_user_type('admin')) {
    header("Location: ../login.php");
    exit();
}

// Get admin data
$admin_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$admin_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Process form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rating = $_POST['rating'];
    $feedback_text = $_POST['feedback_text'];
    $suggestion = $_POST['suggestion'];
    
    // Validate input
    if (empty($rating) || empty($feedback_text)) {
        $error_message = "Rating dan Feedback wajib diisi.";
    } elseif ($rating < 1 || $rating > 5) {
        $error_message = "Rating harus antara 1 dan 5.";
    } else {
        // Insert feedback into database
        $stmt = $conn->prepare("INSERT INTO admin_feedback (admin_id, rating, feedback_text, suggestion) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("iiss", $admin_id, $rating, $feedback_text, $suggestion);
        
        if ($stmt->execute()) {
            $success_message = "Terima kasih! Feedback Anda telah berhasil dikirim.";
            
            // Log activity
            log_activity($conn, $admin_id, 'admin', 'Feedback Submitted', 'Admin submitted system feedback');
        } else {
            $error_message = "Gagal mengirim feedback. Silakan coba lagi.";
        }
        
        $stmt->close();
    }
}

// Get previous feedback from this admin
$stmt = $conn->prepare("
    SELECT af.*, iu.username as reviewer_name 
    FROM admin_feedback af 
    LEFT JOIN it_users iu ON af.reviewed_by = iu.id
    WHERE af.admin_id = ? 
    ORDER BY af.submission_date DESC
");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$previous_feedback = $stmt->get_result();
$stmt->close();

// Set page title
$page_title = "Feedback Sistem";

// Log activity
log_activity($conn, $admin_id, 'admin', 'Feedback Access', 'Admin accessed feedback form');

// Include header
include '../template_admin/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Feedback Form Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Feedback Sistem Master Color Panel</h2>
        
        <p class="mb-4 text-gray-600">Silakan berikan penilaian dan masukan Anda tentang sistem ini untuk membantu kami meningkatkan layanan.</p>
        
        <!-- Add temporary notification div that's hidden by default -->
        <div id="temp-notification" class="mb-4 p-3 bg-yellow-100 text-yellow-700 rounded hidden">
            <i class="fas fa-exclamation-circle mr-2"></i>Maaf isi feedback dengan lengkap agar data dapat di review oleh IT
        </div>
        
        <?php if (!empty($success_message)): ?>
            <div class="mb-4 p-3 bg-green-100 text-green-700 rounded">
                <i class="fas fa-check-circle mr-2"></i><?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error_message)): ?>
            <div class="mb-4 p-3 bg-red-100 text-red-700 rounded">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error_message; ?>
            </div>
        <?php endif; ?>
        
        <form method="POST" action="" class="mt-6" id="feedback-form">
            <div class="mb-6">
                <label for="rating" class="block text-gray-700 font-medium mb-2">Rating</label>
                <div class="flex space-x-4">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <div class="flex items-center">
                        <input type="radio" id="rating-<?php echo $i; ?>" name="rating" value="<?php echo $i; ?>" class="mr-2">
                        <label for="rating-<?php echo $i; ?>" class="text-xl">
                            <?php echo str_repeat('★', $i) . str_repeat('☆', 5 - $i); ?>
                        </label>
                    </div>
                    <?php endfor; ?>
                </div>
            </div>
            
            <div class="mb-6">
                <label for="feedback_text" class="block text-gray-700 font-medium mb-2">Feedback</label>
                <textarea name="feedback_text" id="feedback_text" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Berikan pendapat Anda tentang sistem ini..."></textarea>
            </div>
            
            <div class="mb-6">
                <label for="suggestion" class="block text-gray-700 font-medium mb-2">Saran Perbaikan (Opsional)</label>
                <textarea name="suggestion" id="suggestion" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Berikan saran untuk peningkatan sistem..."></textarea>
            </div>
            
            <div class="mt-6">
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                    <i class="fas fa-paper-plane mr-2"></i>Kirim Feedback
                </button>
            </div>
        </form>
    </div>
    
    <!-- Previous Feedback -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-6">Riwayat Feedback Anda</h3>
        
        <?php if ($previous_feedback->num_rows > 0): ?>
            <div class="overflow-x-auto">
                <table class="min-w-full table-auto">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rating</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Feedback</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php while ($row = $previous_feedback->fetch_assoc()): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?php echo date('d M Y, H:i', strtotime($row['submission_date'])); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-yellow-500">
                                        <?php echo str_repeat('★', $row['rating']) . str_repeat('☆', 5 - $row['rating']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <p><strong>Feedback:</strong> <?php echo htmlspecialchars($row['feedback_text']); ?></p>
                                    <?php if (!empty($row['suggestion'])): ?>
                                        <p class="mt-1"><strong>Saran:</strong> <?php echo htmlspecialchars($row['suggestion']); ?></p>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($row['response_text'])): ?>
                                        <div class="mt-3 p-3 bg-blue-50 rounded border-l-4 border-blue-500">
                                            <p class="text-sm text-gray-700"><strong>Tanggapan dari IT:</strong> <?php echo htmlspecialchars($row['response_text']); ?></p>
                                            <p class="text-xs text-gray-500 mt-1">Dijawab pada <?php echo date('d M Y, H:i', strtotime($row['response_date'])); ?></p>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if ($row['status'] === 'pending'): ?>
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
                                            Menunggu Review
                                        </span>
                                    <?php elseif ($row['status'] === 'reviewed'): ?>
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                            Direview oleh <?php echo htmlspecialchars($row['reviewer_name']); ?>
                                        </span>
                                    <?php elseif ($row['status'] === 'implemented'): ?>
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                                            Sudah Diimplementasi
                                        </span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-4 text-gray-500">
                <p>Anda belum memberikan feedback sebelumnya.</p>
            </div>
        <?php endif; ?>
    </div>
</main>

<!-- Add JavaScript for form validation with temporary notification -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('feedback-form');
    const notificationDiv = document.getElementById('temp-notification');
    
    form.addEventListener('submit', function(event) {
        // Get form values
        const rating = document.querySelector('input[name="rating"]:checked');
        const feedbackText = document.getElementById('feedback_text').value.trim();
        
        // Check if rating or feedback text is empty
        if (!rating || feedbackText === '') {
            // Prevent form submission
            event.preventDefault();
            
            // Show notification
            notificationDiv.classList.remove('hidden');
            
            // Hide notification after 3 seconds
            setTimeout(function() {
                notificationDiv.classList.add('hidden');
            }, 3000);
        }
    });
});
</script>

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