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

// Delete record
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);
    mysqli_query($con, "DELETE FROM escalation_master WHERE id=$id");
    echo "<script>alert('Escalation deleted successfully'); window.location='escalation_master_list.php';</script>";
    exit;
}

// Fetch all escalations
$query = "
    SELECT e.id, d.dept_name, e.level_no, u1.name AS user_name,
           e.time_limit_hours, u2.name AS next_user, e.status
    FROM escalation_master e
    LEFT JOIN departments d ON e.department_id = d.dept_id
    LEFT JOIN users u1 ON e.user_id = u1.user_id
    LEFT JOIN users u2 ON e.next_level_user_id = u2.user_id
    ORDER BY e.department_id, e.level_no ASC
";
$result = mysqli_query($con, $query);
?>

<div class="container mt-5">
    <h2 class="mb-4">Escalation Master List</h2>
    <a href="escalation_master.php" class="btn btn-primary mb-3">+ Add New Escalation</a>

    <table class="table table-bordered table-striped">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Department</th>
                <th>Level</th>
                <th>User</th>
                <th>Time Limit (hrs)</th>
                <th>Next Level User</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php if (mysqli_num_rows($result) > 0): ?>
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?= $row['id'] ?></td>
                <td><?= htmlspecialchars($row['dept_name']) ?></td>
                <td><?= $row['level_no'] ?></td>
                <td><?= htmlspecialchars($row['user_name']) ?></td>
                <td><?= $row['time_limit_hours'] ?></td>
                <td><?= htmlspecialchars($row['next_user'] ?? '-') ?></td>
                <td><?= $row['status'] ? 'Active' : 'Inactive' ?></td>
                <td>
                    <a href="escalation_master_edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                    <a href="escalation_master_list.php?delete_id=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this record?')">Delete</a>
                </td>
            </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="8" class="text-center">No records found</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

</body>
</html>
