<?php
require_once __DIR__ . '/vendor/autoload.php';
$page_title = 'Management Menu';
require_once('includes/load.php');

if (isset($_POST['name'])) {
  $name = $_POST['name'];
  $url = $_POST['url'];
  $icon = $_POST['icon'];
  $visible = isset($_POST['visible']) ? 1 : 0;
  $parent_id = $_POST['parent_id'] ?? NULL;
  $id = $_POST['id'] ?? NULL;

  if ($id) {
    // Update existing menu item
    $stmt = $db->prepare("UPDATE menu_items SET name=?, url=?, icon=?, visible=?, parent_id=? WHERE id=?");
    $stmt->bind_param("sssiii", $name, $url, $icon, $visible, $parent_id, $id);
  } else {
    // Insert new menu item
    $stmt = $db->prepare("INSERT INTO menu_items (name, url, icon, visible, parent_id) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssii", $name, $url, $icon, $visible, $parent_id);
  }

  if ($stmt->execute()) {
    $session->msg('s', "Menu item saved successfully!");
  } else {
    $session->msg('d', "Error saving menu item: " . $stmt->error);
  }
  redirect_to('menu_management.php'); // Redirect to BOM View page
  $stmt->close();
}

// Handle deletion of menu items
if (isset($_GET['delete'])) {
  $id = $_GET['delete'];
  $db->query("DELETE FROM menu_items WHERE id = $id");
  echo "<div class='alert alert-success'>Menu item deleted successfully!</div>";
}

// Fetch existing menu items
$result = $db->query("SELECT * FROM menu_items ORDER BY id ASC");
$menuItems = [];
while ($row = $result->fetch_assoc()) {
  $menuItems[] = $row;
}


?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>Form Add / Edit</span>
        </strong>
      </div>
      <div class="panel-body">
        <form method="POST" action="">
          <input type="hidden" name="id" id="menu_id" value="">
          <div class="form-group">
            <label for="name">Menu Name:</label>
            <input type="text" name="name" id="name" class="form-control" required>
          </div>
          <div class="form-group">
            <label for="url">URL:</label>
            <input type="text" name="url" id="url" class="form-control" required value="-">
          </div>
          <div class="form-group">
            <label for="icon">Icon Class:</label>
            <input type="text" name="icon" id="icon" class="form-control" placeholder="e.g., glyphicon glyphicon-home">
          </div>
          <div class="form-group">
            <label for="parent_id">Parent Menu Item:</label>
            <select name="parent_id" id="parent_id" class="form-control">
              <option value="">None</option>
              <?php foreach ($menuItems as $item): ?>
                <option value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="checkbox">
            <label>
              <input type="checkbox" name="visible" value="1" checked> Visible
            </label>
          </div>
          <button type="submit" class="btn btn-primary">Save Menu Item</button>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>Data Menu</span>
        </strong>
      </div>
      <div class="panel-body">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>URL</th>
              <th>Icon</th>
              <th>Visible</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($menuItems as $item): ?>
              <tr>
                <td><?php echo $item['id']; ?></td>
                <td><?php echo $item['name']; ?></td>
                <td><?php echo $item['url']; ?></td>
                <td><?php echo $item['icon']; ?></td>
                <td><?php echo $item['visible'] ? 'Yes' : 'No'; ?></td>
                <td>
                  <a href="#" class="btn btn-warning"
                    onclick="editMenuItem(<?php echo $item['id']; ?>, '<?php echo $item['name']; ?>', '<?php echo $item['url']; ?>', '<?php echo $item['icon']; ?>', <?php echo $item['parent_id']; ?>)">Edit</a>
                  <a href="?delete=<?php echo $item['id']; ?>" class="btn btn-danger"
                    onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<script>
  function editMenuItem(id, name, url, icon, parentId) {
    document.getElementById('menu_id').value = id;
    document.getElementById('name').value = name;
    document.getElementById('url').value = url;
    document.getElementById('icon').value = icon;
    document.getElementById('parent_id').value = parentId;
  }
</script>
<?php include_once('layouts/footer.php'); ?>