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

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

// ---------- Add new feedback type ----------
if (isset($_POST['add'])) {
    $type_name = trim($_POST['type_name']);
    $description = trim($_POST['description']);
    $department_id = !empty($_POST['department_id']) ? intval($_POST['department_id']) : null;

    if ($department_id) {
        $stmt = $con->prepare("INSERT INTO feedback_master (type_name, description, department_id, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->bind_param("ssi", $type_name, $description, $department_id);
    } else {
        $stmt = $con->prepare("INSERT INTO feedback_master (type_name, description, created_at) VALUES (?, ?, NOW())");
        $stmt->bind_param("ss", $type_name, $description);
    }

    if ($stmt->execute()) {
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    } else {
        echo "<div class='alert alert-danger'>Error: " . htmlspecialchars($con->error) . "</div>";
    }
}

// ---------- Delete feedback type ----------
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);

    $check = $con->prepare("SELECT COUNT(*) FROM feedbacks WHERE feedback_type_id = ?");
    $check->bind_param("i", $id);
    $check->execute();
    $check->bind_result($count);
    $check->fetch();
    $check->close();

    if ($count > 0) {
        echo "<script>alert('Cannot delete. There are existing feedbacks for this type.');</script>";
    } else {
        $stmtDel = $con->prepare("DELETE FROM feedback_master WHERE feedback_type_id = ?");
        $stmtDel->bind_param("i", $id);
        $stmtDel->execute();
        header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
        exit();
    }
}

// ---------- Fetch feedback types with department ----------
$feedback_types_q = "
    SELECT f.*, d.dept_name 
    FROM feedback_master f
    LEFT JOIN departments d ON f.department_id = d.dept_id
    ORDER BY f.created_at DESC
";
$feedback_types = $con->query($feedback_types_q);

// Fetch departments for dropdown
$departments = $con->query("SELECT * FROM departments ORDER BY dept_name");
?>

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

    <!-- Add Feedback Type Form -->
    <div class="card mb-4 shadow-sm">
        <div class="card-body">
            <h5 class="card-title">Add New Grievance Type</h5>
            <form method="POST" class="row g-3">
                <div class="col-md-3">
                    <input type="text" name="type_name" class="form-control" placeholder="Feedback Type Name" required>
                </div>
                <div class="col-md-4">
                    <input type="text" name="description" class="form-control" placeholder="Description">
                </div>
                <div class="col-md-3">
                    <select name="department_id" class="form-select">
                        <option value="">-- Select Department (optional) --</option>
                        <?php while ($d = $departments->fetch_assoc()): ?>
                            <option value="<?= $d['dept_id'] ?>"><?= htmlspecialchars($d['dept_name']) ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-2 text-end">
                    <button type="submit" name="add" class="btn btn-primary">Add</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Feedback Types Table -->
    <div class="card shadow-sm">
        <div class="card-body">
            <h5 class="card-title">Grievance Types List</h5>
            <table class="table table-bordered table-striped">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th>Type Name</th>
                        <th>Description</th>
                        <th>Department</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $sn = 1;
                    while ($f = $feedback_types->fetch_assoc()): ?>
                        <tr>
                            <td><?= $sn++ ?></td>
                            <td><?= htmlspecialchars($f['type_name']) ?></td>
                            <td><?= htmlspecialchars($f['description']) ?></td>
                            <td><?= htmlspecialchars($f['dept_name'] ?? 'Not Assigned') ?></td>
                            <td>
                                <button class="btn btn-sm btn-warning editBtn"
                                    data-id="<?= $f['feedback_type_id'] ?>"
                                    data-name="<?= htmlspecialchars($f['type_name']) ?>"
                                    data-description="<?= htmlspecialchars($f['description']) ?>"
                                    data-department="<?= $f['department_id'] ?>">
                                    Edit
                                </button>
                                <a href="?delete=<?= $f['feedback_type_id'] ?>" 
                                   class="btn btn-sm btn-danger"
                                   onclick="return confirm('Delete this feedback type?')">
                                   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 Feedback Type</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="feedback_type_id" id="edit_id">
            <div class="mb-3">
                <label>Type Name</label>
                <input type="text" name="type_name" id="edit_name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Description</label>
                <input type="text" name="description" id="edit_description" class="form-control">
            </div>
            <div class="mb-3">
                <label>Department</label>
                <select name="department_id" id="edit_department" class="form-select">
                    <option value="">-- Select Department (optional) --</option>
                    <?php
                    $dept_query = $con->query("SELECT * FROM departments ORDER BY dept_name");
                    while ($d = $dept_query->fetch_assoc()):
                    ?>
                        <option value="<?= $d['dept_id'] ?>"><?= $d['dept_name'] ?></option>
                    <?php endwhile; ?>
                </select>
            </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>

<!-- Bootstrap + AJAX JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    // Edit button click → open modal
    document.querySelectorAll(".editBtn").forEach(btn => {
        btn.addEventListener("click", function () {
            document.getElementById("edit_id").value = this.dataset.id;
            document.getElementById("edit_name").value = this.dataset.name;
            document.getElementById("edit_description").value = this.dataset.description;
            document.getElementById("edit_department").value = this.dataset.department;
            const modal = new bootstrap.Modal(document.getElementById("editModal"));
            modal.show();
        });
    });

    // Submit edit form via AJAX
    document.getElementById("editForm").addEventListener("submit", function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        fetch("update_feedback_type.php", {
            method: "POST",
            body: formData
        })
        .then(res => res.text())
        .then(data => {
            alert(data);
            location.reload();
        });
    });
});
</script>

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