<?php
require_once 'db/config.php';
include '_header.php';
include '_navbar.php';

$pdo = db();
$stmt = $pdo->query("SELECT f.*, bg.name as group_name FROM functions f LEFT JOIN bni_groups bg ON f.bni_group_id = bg.id ORDER BY f.display_order");
$functions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$group_stmt = $pdo->query("SELECT * FROM bni_groups WHERE active = 1 ORDER BY name");
$bni_groups = $group_stmt->fetchAll(PDO::FETCH_ASSOC);


?>

<div class="container-fluid">
    <div class="row">
        <?php include '_sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <h1 class="h2 pt-3 pb-2 mb-3 border-bottom"><?php echo t('functions.title', 'Functions'); ?></h1>

            <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show mt-3" function="alert">
                <?= $_SESSION['success_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

            <div class="d-flex justify-content-end mb-3">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                    <?php echo t('functions.add_new', 'Add New Function'); ?>
                </button>
            </div>

            <div class="table-responsive mt-4">
                <table class="table table-striped table-sm">
                    <thead>
                        <tr>
                            <th style="width: 30px;"></th>
                            <th><?php echo t('functions.name', 'Name'); ?></th>
                            <th><?php echo t('functions.group', 'Group'); ?></th>
                            <th><?php echo t('functions.actions', 'Actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="sortable-list">
                        <?php foreach ($functions as $function): ?>
                        <tr data-id="<?= $function['id'] ?>">
                            <td class="handle"><i class="bi bi-grip-vertical"></i></td>
                            <td><?= htmlspecialchars($function['name']) ?></td>
                            <td><?= htmlspecialchars($function['group_name']) ?></td>
                            <td>
                                <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editModal" data-id="<?= $function['id'] ?>" data-name="<?= htmlspecialchars($function['name']) ?>" data-bni_group_id="<?= $function['bni_group_id'] ?>">
                                    <?php echo t('functions.edit', 'Edit'); ?>
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal" data-id="<?= $function['id'] ?>">
                                    <?php echo t('functions.delete', 'Delete'); ?>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

        </main>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addModalLabel"><?php echo t('functions.add_title', 'Add Function'); ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="_add_function.php" method="post">
        <div class="modal-body">
            <div class="mb-3">
                <label for="addName" class="form-label"><?php echo t('functions.name', 'Name'); ?></label>
                <input type="text" class="form-control" id="addName" name="name" required>
            </div>
            <div class="mb-3">
                <label for="addBniGroup" class="form-label"><?php echo t('functions.group', 'Group'); ?></label>
                <select class="form-select" id="addBniGroup" name="bni_group_id" required>
                    <option value=""><?php echo t('functions.select_group', 'Select a group'); ?></option>
                    <?php foreach ($bni_groups as $group): ?>
                        <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo t('modal.close', 'Close'); ?></button>
          <button type="submit" name="add" class="btn btn-primary"><?php echo t('functions.add_button', 'Add'); ?></button>
        </div>
      </form>
    </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">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel"><?php echo t('functions.edit_title', 'Edit Function'); ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="_update_function.php" method="post">
        <div class="modal-body">
            <input type="hidden" id="editId" name="id">
            <div class="mb-3">
                <label for="editName" class="form-label"><?php echo t('functions.name', 'Name'); ?></label>
                <input type="text" class="form-control" id="editName" name="name" required>
            </div>
            <div class="mb-3">
                <label for="editBniGroup" class="form-label"><?php echo t('functions.group', 'Group'); ?></label>
                <select class="form-select" id="editBniGroup" name="bni_group_id" required>
                    <option value=""><?php echo t('functions.select_group', 'Select a group'); ?></option>
                    <?php foreach ($bni_groups as $group): ?>
                        <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo t('modal.close', 'Close'); ?></button>
          <button type="submit" name="edit" class="btn btn-primary"><?php echo t('modal.save_changes', 'Save changes'); ?></button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteModalLabel"><?php echo t('functions.delete_title', 'Delete Function'); ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <?php echo t('functions.delete_confirm', 'Are you sure you want to delete this function?'); ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo t('modal.cancel', 'Cancel'); ?></button>
        <a href="#" id="deleteLink" class="btn btn-danger"><?php echo t('functions.delete', 'Delete'); ?></a>
      </div>
    </div>
  </div>
</div>


<?php include '_footer.php'; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var editModal = document.getElementById('editModal');
    editModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var id = button.getAttribute('data-id');
        var name = button.getAttribute('data-name');
        var bni_group_id = button.getAttribute('data-bni_group_id');
        
        var modalTitle = editModal.querySelector('.modal-title');
        var idInput = editModal.querySelector('#editId');
        var nameInput = editModal.querySelector('#editName');
        var groupSelect = editModal.querySelector('#editBniGroup');
        
        idInput.value = id;
        nameInput.value = name;
        groupSelect.value = bni_group_id;
    });

    var deleteModal = document.getElementById('deleteModal');
    deleteModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var id = button.getAttribute('data-id');
        var deleteLink = deleteModal.querySelector('#deleteLink');
        deleteLink.href = '_delete_function.php?id=' + id;
    });

    $(function() {
        $("#sortable-list").sortable({
            handle: ".handle",
            update: function(event, ui) {
                var order = $(this).sortable('toArray', {attribute: 'data-id'});
                $.post('_update_function_order.php', { order: order });
            }
        }).disableSelection();
    });
});
</script>