<?php
// Start session
session_start();

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

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

// Get IT user data
$it_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM it_users WHERE id = ?");
$stmt->bind_param("i", $it_id);
$stmt->execute();
$it_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $feedback_id = $_POST['feedback_id'];
    $feedback_type = $_POST['feedback_type']; // 'admin' or 'borrower'
    $response_text = $_POST['response_text'];
    $status = $_POST['status'];
    
    // Validate input
    if (empty($feedback_id) || empty($feedback_type) || empty($response_text) || empty($status)) {
        $error_message = "Semua field wajib diisi.";
    } else {
        // Determine which table to update
        $table_name = $feedback_type . '_feedback';
        
        // Update feedback with response
        $stmt = $conn->prepare("
            UPDATE {$table_name} 
            SET response_text = ?, 
                response_date = NOW(), 
                status = ?, 
                reviewed_by = ?,
                review_date = NOW()
            WHERE id = ?
        ");
        $stmt->bind_param("ssii", $response_text, $status, $it_id, $feedback_id);
        
        if ($stmt->execute()) {
            $success_message = "Respons berhasil dikirim.";
            
            // Log activity
            $user_type = $feedback_type === 'admin' ? 'Admin' : 'borrower';
            log_activity($conn, $it_id, 'it', 'Feedback Response', "IT user responded to {$user_type} feedback ID: {$feedback_id}");
        } else {
            $error_message = "Gagal mengirim respons. Silakan coba lagi." . $conn->error;
        }
        
        $stmt->close();
    }
}

// Get admin feedback sorted by newest first
$admin_stmt = $conn->prepare("
    SELECT af.*, au.username as admin_username, au.email as admin_email
    FROM admin_feedback af
    JOIN admin_users au ON af.admin_id = au.id
    ORDER BY af.submission_date DESC
");
$admin_stmt->execute();
$admin_feedback = $admin_stmt->get_result();
$admin_stmt->close();

// Get borrower feedback sorted by newest first
$borrower_stmt = $conn->prepare("
    SELECT bf.*, bu.username as borrower_username, bu.email as borrower_email, bu.lokasi_posisi
    FROM borrower_feedback bf
    JOIN borrower_users bu ON bf.borrower_id = bu.id
    ORDER BY bf.submission_date DESC
");
$borrower_stmt->execute();
$borrower_feedback = $borrower_stmt->get_result();
$borrower_stmt->close();

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

// Log activity
log_activity($conn, $it_id, 'it', 'Feedback Review', 'IT user accessed feedback review page');

// Include header
include '../template_it/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 Review Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Review dan Tanggapan Feedback Sistem</h2>
        
        <p class="mb-4 text-gray-600">Halaman ini memungkinkan Anda untuk melihat semua feedback, memberikan tanggapan, dan mengubah status.</p>
        
        <?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; ?>
        
        <!-- Tabs -->
        <div class="mb-6 border-b border-gray-200">
            <ul class="flex flex-wrap -mb-px" id="tabs" role="tablist">
                <li class="mr-2" role="presentation">
                    <button class="inline-block py-2 px-4 text-blue-600 border-b-2 border-blue-600 rounded-t-lg active" id="admin-tab" data-tab="admin" type="button" role="tab" aria-selected="true">
                        Feedback Admin
                    </button>
                </li>
                <li class="mr-2" role="presentation">
                    <button class="inline-block py-2 px-4 text-gray-500 hover:text-gray-600 hover:border-gray-300 rounded-t-lg" id="borrower-tab" data-tab="borrower" type="button" role="tab" aria-selected="false">
                        Feedback borrower
                    </button>
                </li>
            </ul>
        </div>
        
        <!-- Admin Feedback Tab Content -->
        <div id="admin-content" class="tab-content block">
            <h3 class="text-xl font-semibold text-gray-800 mb-4">Feedback dari Admin</h3>
            
            <?php if ($admin_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-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Admin</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rating</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Feedback</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php while ($row = $admin_feedback->fetch_assoc()): ?>
                                <tr class="<?php echo $row['status'] === 'pending' ? 'bg-yellow-50' : ''; ?>">
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="ml-2">
                                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['admin_username']); ?></div>
                                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($row['admin_email']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('d M Y, H:i', strtotime($row['submission_date'])); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="text-yellow-500">
                                            <?php echo str_repeat('★', $row['rating']) . str_repeat('☆', 5 - $row['rating']); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 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 text-sm text-blue-600"><strong>Saran:</strong> <?php echo htmlspecialchars($row['suggestion']); ?></p>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($row['response_text'])): ?>
                                            <div class="mt-2 p-2 bg-gray-100 rounded">
                                                <p class="text-sm text-gray-700"><strong>Respons:</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-4 py-3 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">
                                                Sudah Direview
                                            </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>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                                        <button class="text-blue-600 hover:text-blue-900 respond-btn" 
                                                data-id="<?php echo $row['id']; ?>" 
                                                data-type="admin"
                                                data-feedback="<?php echo htmlspecialchars($row['feedback_text']); ?>"
                                                data-suggestion="<?php echo htmlspecialchars($row['suggestion']); ?>"
                                                data-response="<?php echo htmlspecialchars($row['response_text']); ?>"
                                                data-status="<?php echo $row['status']; ?>">
                                            <?php echo empty($row['response_text']) ? 'Tanggapi' : 'Edit Tanggapan'; ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center py-4 text-gray-500">
                    <p>Belum ada feedback dari admin.</p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Borrower Feedback Tab Content -->
        <div id="borrower-content" class="tab-content hidden">
            <h3 class="text-xl font-semibold text-gray-800 mb-4">Feedback dari borrower</h3>
            
            <?php if ($borrower_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-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">borrower</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rating</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Feedback</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php while ($row = $borrower_feedback->fetch_assoc()): ?>
                                <tr class="<?php echo $row['status'] === 'pending' ? 'bg-yellow-50' : ''; ?>">
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="ml-2">
                                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['borrower_username']); ?></div>
                                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($row['borrower_email']); ?></div>
                                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($row['lokasi_posisi']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('d M Y, H:i', strtotime($row['submission_date'])); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="text-yellow-500">
                                            <?php echo str_repeat('★', $row['rating']) . str_repeat('☆', 5 - $row['rating']); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 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 text-sm text-blue-600"><strong>Saran:</strong> <?php echo htmlspecialchars($row['suggestion']); ?></p>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($row['response_text'])): ?>
                                            <div class="mt-2 p-2 bg-gray-100 rounded">
                                                <p class="text-sm text-gray-700"><strong>Respons:</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-4 py-3 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">
                                                Sudah Direview
                                            </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>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                                        <button class="text-blue-600 hover:text-blue-900 respond-btn" 
                                                data-id="<?php echo $row['id']; ?>" 
                                                data-type="borrower"
                                                data-feedback="<?php echo htmlspecialchars($row['feedback_text']); ?>"
                                                data-suggestion="<?php echo htmlspecialchars($row['suggestion']); ?>"
                                                data-response="<?php echo htmlspecialchars($row['response_text']); ?>"
                                                data-status="<?php echo $row['status']; ?>">
                                            <?php echo empty($row['response_text']) ? 'Tanggapi' : 'Edit Tanggapan'; ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center py-4 text-gray-500">
                    <p>Belum ada feedback dari borrower.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Response Modal -->
    <div id="responseModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl p-6 m-4 max-w-xl w-full">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800">Tanggapi Feedback</h3>
                <button id="closeModal" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="responseForm" method="POST" action="">
                <input type="hidden" id="feedback_id" name="feedback_id" value="">
                <input type="hidden" id="feedback_type" name="feedback_type" value="">
                
                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">Feedback:</label>
                    <div id="feedback_display" class="p-3 bg-gray-100 rounded text-gray-700 mb-2"></div>
                    
                    <div id="suggestion_container" class="hidden">
                        <label class="block text-gray-700 font-medium mb-2">Saran:</label>
                        <div id="suggestion_display" class="p-3 bg-gray-100 rounded text-gray-700 mb-2"></div>
                    </div>
                </div>
                
                <div class="mb-4">
                    <label for="response_text" class="block text-gray-700 font-medium mb-2">Respons Anda:</label>
                    <textarea name="response_text" id="response_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" required></textarea>
                </div>
                
                <div class="mb-4">
                    <label for="status" class="block text-gray-700 font-medium mb-2">Status:</label>
                    <select name="status" id="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        <option value="reviewed">Sudah Direview</option>
                        <option value="implemented">Sudah Diimplementasi</option>
                    </select>
                </div>
                
                <div class="mt-6 flex justify-end">
                    <button type="button" id="cancelResponse" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 mr-2">
                        Batal
                    </button>
                    <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">
                        Kirim Respons
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<!-- JavaScript for tabs and modal -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tab switching
    const tabs = document.querySelectorAll('[data-tab]');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // Hide all tab content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.add('hidden');
            });
            
            // Show selected tab content
            document.getElementById(this.dataset.tab + '-content').classList.remove('hidden');
            
            // Update active tab styling
            tabs.forEach(t => {
                t.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600');
                t.classList.add('text-gray-500');
            });
            this.classList.add('text-blue-600', 'border-b-2', 'border-blue-600');
            this.classList.remove('text-gray-500');
        });
    });
    
    // Modal handling
    const modal = document.getElementById('responseModal');
    const responseForm = document.getElementById('responseForm');
    const feedbackDisplay = document.getElementById('feedback_display');
    const suggestionContainer = document.getElementById('suggestion_container');
    const suggestionDisplay = document.getElementById('suggestion_display');
    const responseTextarea = document.getElementById('response_text');
    const statusSelect = document.getElementById('status');
    const feedbackIdInput = document.getElementById('feedback_id');
    const feedbackTypeInput = document.getElementById('feedback_type');
    
    // Open modal when clicking respond button
    document.querySelectorAll('.respond-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            feedbackIdInput.value = this.dataset.id;
            feedbackTypeInput.value = this.dataset.type;
            feedbackDisplay.textContent = this.dataset.feedback;
            
            if (this.dataset.suggestion) {
                suggestionDisplay.textContent = this.dataset.suggestion;
                suggestionContainer.classList.remove('hidden');
            } else {
                suggestionContainer.classList.add('hidden');
            }
            
            responseTextarea.value = this.dataset.response || '';
            statusSelect.value = this.dataset.status !== 'pending' ? this.dataset.status : 'reviewed';
            
            modal.classList.remove('hidden');
        });
    });
    
    // Close modal
    document.getElementById('closeModal').addEventListener('click', function() {
        modal.classList.add('hidden');
    });
    
    document.getElementById('cancelResponse').addEventListener('click', function() {
        modal.classList.add('hidden');
    });
    
    // Close modal when clicking outside
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.classList.add('hidden');
        }
    });
});
</script>

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