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

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

// Fetch all departments for dropdown
$departments = $con->query("SELECT * FROM departments");

// Add new Admin
if (isset($_POST['add'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $department_id = $_POST['department_id'];
    $escalation_level = $_POST['escalation_level'];

    $stmt = $con->prepare("INSERT INTO users (name, email, password, role, department_id, escalation_level, created_at) 
                           VALUES (?, ?, ?, 'admin', ?, ?, NOW())");
    $stmt->bind_param("sssii", $name, $email, $password, $department_id, $escalation_level);
    $stmt->execute();
}

// Delete Admin
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $con->query("DELETE FROM users WHERE user_id=$id AND role='admin'");
}

// List all admins
$admins = $con->query("SELECT u.user_id, u.name, u.email, u.department_id, u.escalation_level, d.dept_name 
                       FROM users u 
                       LEFT JOIN departments d ON u.department_id=d.dept_id 
                       WHERE u.role='admin'");
?>

<div class="container mt-5">
    <h2 class="mb-4">Manage Users</h2>

    <!-- Add Admin Form -->
    <div class="card mb-4 shadow-sm">
        <div class="card-body">
            <h5 class="card-title">Add New User</h5>
            <form method="POST" class="row g-3">
                <div class="col-md-3">
                    <input type="text" name="name" class="form-control" placeholder="Full Name" required>
                </div>
                <div class="col-md-3">
                    <input type="email" name="email" class="form-control" placeholder="Email" required>
                </div>
                <div class="col-md-2">
                    <input type="password" name="password" class="form-control" placeholder="Password" required>
                </div>
                <div class="col-md-2">
                    <select name="department_id" class="form-select" required>
                        <option value="">Select Department</option>
                        <?php while ($d = $departments->fetch_assoc()): ?>
                            <option value="<?= $d['dept_id'] ?>"><?= $d['dept_name'] ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <input type="number" name="escalation_level" class="form-control" placeholder="Level (1,2,3)" min="1" required>
                </div>
                <div class="col-12 text-end">
                    <button type="submit" name="add" class="btn btn-primary">Add User</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Admins Table -->
    <div class="card shadow-sm">
        <div class="card-body">
            <h5 class="card-title">Users List</h5>
            <table class="table table-bordered table-striped align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Department</th>
                        <th>Level</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; while ($a = $admins->fetch_assoc()): ?>
                        <tr>
                            <td><?= $sn++ ?></td>
                            <td><?= htmlspecialchars($a['name']) ?></td>
                            <td><?= htmlspecialchars($a['email']) ?></td>
                            <td><?= $a['dept_name'] ?: 'Not Mapped' ?></td>
                            <td><?= $a['escalation_level'] ?: '-' ?></td>
                            <td>
                                <button class="btn btn-sm btn-warning editBtn"
                                    data-id="<?= $a['user_id'] ?>"
                                    data-name="<?= htmlspecialchars($a['name']) ?>"
                                    data-email="<?= htmlspecialchars($a['email']) ?>"
                                    data-department="<?= $a['department_id'] ?>"
                                    data-level="<?= $a['escalation_level'] ?>"
                                >Edit</button>
                                <a href="?delete=<?= $a['user_id'] ?>" class="btn btn-sm btn-danger"
                                    onclick="return confirm('Delete this admin?')">Delete</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="editForm">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title" id="editModalLabel">Edit User</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <input type="hidden" name="user_id" id="edit_user_id">
            <div class="mb-3">
                <label>Name</label>
                <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Email</label>
                <input type="email" name="email" id="edit_email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Department</label>
                <select name="department_id" id="edit_department" class="form-select" required>
                    <option value="">Select Department</option>
                    <?php
                    $dept_query = $con->query("SELECT * FROM departments");
                    while ($d = $dept_query->fetch_assoc()):
                    ?>
                        <option value="<?= $d['dept_id'] ?>"><?= $d['dept_name'] ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="mb-3">
                <label>Escalation Level</label>
                <input type="number" name="escalation_level" id="edit_escalation_level" class="form-control" min="1" required>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-success">Update</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {

    document.querySelectorAll('.editBtn').forEach(btn => {
        btn.addEventListener('click', function () {
            document.getElementById('edit_user_id').value = this.dataset.id;
            document.getElementById('edit_name').value = this.dataset.name;
            document.getElementById('edit_email').value = this.dataset.email;
            document.getElementById('edit_department').value = this.dataset.department;
            document.getElementById('edit_escalation_level').value = this.dataset.level;

            const modal = new bootstrap.Modal(document.getElementById('editModal'));
            modal.show();
        });
    });

    document.getElementById('editForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(this);

        fetch('update_user.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(data => {
            alert(data);
            location.reload();
        });
    });
});
</script>

<?php include("../../includes/footer.php"); ?>
