<?php
include("../../includes/auth_check.php");
include("../../includes/header.php");
include("../../config/config.php");

if ($_SESSION['role'] != 'admin') die("Access denied");

$admin_id = $_SESSION['user_id'];

// Get admin's escalation level
$levelQuery = $con->query("SELECT escalation_level FROM users WHERE user_id = $admin_id");
$adminLevel = ($levelQuery && $levelQuery->num_rows > 0)
    ? $levelQuery->fetch_assoc()['escalation_level']
    : 1; // default to level 1 if not found

// Fetch grievances that match this level
$sql = "
    SELECT f.*, u.name, ft.type_name 
    FROM feedbacks f 
    JOIN users u ON f.user_id = u.user_id 
    JOIN feedback_master ft ON f.feedback_type_id = ft.feedback_type_id 
    WHERE f.admin_id = $admin_id 
    AND f.current_level = $adminLevel
    ORDER BY f.created_at DESC
";

$result = $con->query($sql);

?>

<div class="container mt-5">
    <h2 class="mb-4">Manage Grievence</h2>
    <div class="card shadow-sm">
        <div class="card-body">
            <table class="table table-bordered table-striped align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>User</th>
                        <th>Type</th>
                        <th>Grievence</th>
                        <th>File</th>
                        <th>Status</th>
                        <th>Remarks</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= htmlspecialchars($row['type_name']) ?></td>
                            <td><?= nl2br(htmlspecialchars($row['feedback_text'])) ?></td>

                            <!-- File View Column -->
                            <td>
                                <?php if (!empty($row['file_path'])): ?>
                                    <?php
                                    $ext = strtolower(pathinfo($row['file_path'], PATHINFO_EXTENSION));
                                    $fileUrl = "../../" . htmlspecialchars($row['file_path']);
                                    ?>
                                    <?php if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])): ?>
                                        <a href="<?= $fileUrl ?>" target="_blank">
                                            <img src="<?= $fileUrl ?>" alt="Attachment" width="60" height="60" class="rounded border">
                                        </a>
                                    <?php else: ?>
                                        <a href="<?= $fileUrl ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                            View File
                                        </a>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">No file</span>
                                <?php endif; ?>
                            </td>

                            <!-- Status -->
                            <td>
                                <?php if ($row['status'] == 'pending'): ?>
                                    <span class="badge bg-warning text-dark">Pending</span>
                                <?php elseif ($row['status'] == 'accepted'): ?>
                                    <span class="badge bg-success">Accepted</span>
                                <?php elseif ($row['status'] == 'rejected'): ?>
                                    <span class="badge bg-danger">Rejected</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Unknown</span>
                                <?php endif; ?>
                            </td>

                            <!-- Remarks -->
                            <td><?= htmlspecialchars($row['remarks'] ?? '-') ?></td>

                            <!-- Action -->
                            <td>
                                <button type="button" class="btn btn-primary btn-sm"
                                    data-bs-toggle="modal"
                                    data-bs-target="#responseModal"
                                    data-feedback-id="<?= $row['feedback_id'] ?>">
                                    💬 Response
                                </button>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1" aria-labelledby="responseModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="feedback_update.php">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="responseModalLabel">Grievance Response</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="feedback_id" id="modal_feedback_id">
                    <div class="mb-3">
                        <label for="remarks" class="form-label">Remarks</label>
                        <textarea class="form-control" name="remarks" id="remarks" rows="4" placeholder="Type your response..." required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select" required>
                            <option value="accepted">Accept</option>
                            <option value="rejected">Reject</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="respond" class="btn btn-success">Submit</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var responseModal = document.getElementById('responseModal');
        responseModal.addEventListener('show.bs.modal', function(event) {
            var button = event.relatedTarget;
            var feedbackId = button.getAttribute('data-feedback-id');
            document.getElementById('modal_feedback_id').value = feedbackId;
        });
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php include("../../includes/footer.php"); ?>