<?php
include __DIR__ . '/../includes/header.php';

// Ensure only admins can access this page
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'] ?? 'You do not have permission to access this page', 'danger');
    redirectTo(getCleanUrl('index'));
    exit;
}

// --- Ticket Category Management ---
$ticketCategories = [];
$categoryFormErrors = [];
$categoryFormSuccess = '';

// Fetch all ticket categories
try {
    $stmt = $pdo->query("SELECT * FROM ticket_categories ORDER BY name ASC");
    $ticketCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_FETCH_ERROR'] ?? "Error fetching ticket categories: %s", $e->getMessage());
}

// Handle Add Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_ticket_category'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $categoryFormErrors[] = $lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.';
    } else {
        $newCategoryName = sanitizeInput($_POST['category_name'] ?? '');
        $newCategoryIcon = sanitizeInput($_POST['category_icon'] ?? '');
        if (empty($newCategoryName)) {
            $categoryFormErrors[] = $lang_alerts['ALERT_TICKET_CATS_NAME_EMPTY'] ?? "Category name cannot be empty.";
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO ticket_categories (name, icon) VALUES (?, ?)");
                $stmt->execute([$newCategoryName, $newCategoryIcon ?: null]);
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATS_ADDED_SUCCESS'] ?? 'Ticket category added successfully.', 'success');
                redirectTo(getCleanUrl('admin/tickets_categories'));
                exit;
            } catch (PDOException $e) {
                if ($e->errorInfo[1] == 1062) {
                    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_ALREADY_EXISTS'] ?? "Category '%s' already exists.", $newCategoryName);
                } else {
                    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_ADD_ERROR'] ?? "Error adding category: %s", $e->getMessage());
                }
            }
        }
    }
}

// Handle Edit Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_ticket_category'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $categoryFormErrors[] = $lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.';
    } else {
        $categoryId = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
        $updatedCategoryName = sanitizeInput($_POST['category_name'] ?? '');
        $updatedCategoryIcon = sanitizeInput($_POST['category_icon'] ?? '');
        if (!$categoryId) {
            $categoryFormErrors[] = $lang_alerts['ALERT_TICKET_CATS_INVALID_ID'] ?? "Invalid category ID.";
        } elseif (empty($updatedCategoryName)) {
            $categoryFormErrors[] = $lang_alerts['ALERT_TICKET_CATS_NAME_EMPTY_EDIT'] ?? "Category name cannot be empty for editing.";
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE ticket_categories SET name = ?, icon = ? WHERE id = ?");
                $stmt->execute([$updatedCategoryName, $updatedCategoryIcon ?: null, $categoryId]);
                if ($stmt->rowCount() > 0) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATS_UPDATED_SUCCESS'] ?? 'Ticket category updated successfully.', 'success');
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATS_UPDATE_NO_CHANGE'] ?? 'Category not updated or no change was made.', 'warning');
                }
                redirectTo(getCleanUrl('admin/tickets_categories'));
                exit;
            } catch (PDOException $e) {
                if ($e->errorInfo[1] == 1062) {
                    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_EDIT_ALREADY_EXISTS'] ?? "Another category with name '%s' already exists.", $updatedCategoryName);
                } else {
                    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_UPDATE_ERROR'] ?? "Error updating category: %s", $e->getMessage());
                }
            }
        }
    }
}

// Handle Delete Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_ticket_category'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $categoryFormErrors[] = $lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.';
    } else {
        $categoryId = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
        if (!$categoryId) {
            $categoryFormErrors[] = $lang_alerts['ALERT_TICKET_CATS_INVALID_ID_DELETE'] ?? "Invalid category ID for deletion.";
        } else {
            try {
                // Check if category is in use
                $stmtCheckUsage = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE category_id = ?");
                $stmtCheckUsage->execute([$categoryId]);
                $usageCount = $stmtCheckUsage->fetchColumn();

                if ($usageCount > 0) {
                    $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_DELETE_IN_USE'] ?? "Cannot delete category: It is currently assigned to %d ticket(s). Reassign tickets before deleting.", $usageCount);
                } else {
                    // Allow deletion of any category if not in use
                    $stmt = $pdo->prepare("DELETE FROM ticket_categories WHERE id = ?");
                    $stmt->execute([$categoryId]);
                    if ($stmt->rowCount() > 0) {
                         $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATS_DELETED_SUCCESS'] ?? 'Ticket category deleted successfully.', 'success');
                    } else {
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_CATS_DELETE_NOT_EXIST'] ?? 'Category not deleted or does not exist.', 'warning');
                    }
                    redirectTo(getCleanUrl('admin/tickets_categories')); // Redirect to this page
                    exit;
                }
            } catch (PDOException $e) {
                $categoryFormErrors[] = sprintf($lang_alerts['ALERT_TICKET_CATS_DELETE_ERROR'] ?? "Error deleting category: %s", $e->getMessage());
            }
        }
    }
}

// Parse Bootstrap Icons version from BOOTSTRAP_ICONS URL
$bootstrapIconsVersion = '1.11.1'; // fallback to a known working version
if (defined('BOOTSTRAP_ICONS')) {
    // Match @version after 'bootstrap-icons@', then stop at next / or ? or end
    if (preg_match('#bootstrap-icons@([\d.]+)#', BOOTSTRAP_ICONS, $matches)) {
        $bootstrapIconsVersion = $matches[1];
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h4><?php echo $lang_admin['ADMIN_TICKET_CATS_PAGE_TITLE'] ?? 'Manage Ticket Categories'; ?></h4>
   <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
        <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD'] ?? 'Back to Dashboard'; ?>
    </a>
</div>

<?php
// Display alerts from session (could be from this page's processing or other pages)
if (isset($_SESSION['alert'])) {
    echo $_SESSION['alert'];
    unset($_SESSION['alert']); // Clear after displaying
}
?>

<?php if (!empty($categoryFormErrors)): ?>
    <div class="alert alert-danger">
        <?php foreach ($categoryFormErrors as $error): ?>
            <p class="mb-1"><?php echo htmlspecialchars($error); ?></p>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<!-- Add Category Form -->
<link rel="stylesheet" href="<?php echo BOOTSTRAP_ICONS; ?>">
<style>
.icon-preview { font-size: 1.5rem; vertical-align: middle; }
.icon-picker-modal .icon-list { max-height: 350px; overflow-y: auto; }
.icon-picker-modal .icon-item { cursor: pointer; padding: 0.5rem; border-radius: 0.25rem; display: inline-block; width: 90px; text-align: center; }
.icon-picker-modal .icon-item:hover { background: #f0f0f0; }
</style>

<div class="card mb-4">
    <div class="card-header"><?php echo $lang_admin['ADMIN_TICKET_CATS_ADD_FORM_TITLE'] ?? 'Add New Category'; ?></div>
    <div class="card-body">
        <form action="<?php echo getCleanUrl('admin/tickets_categories'); ?>" method="post">
            <?php echo get_csrf_input_field(); ?>
            <div class="mb-3 row align-items-center">
                <div class="col-auto">
                    <label for="category_icon_add" class="form-label mb-0">Icon</label>
                </div>
                <div class="col-auto">
                    <span id="icon-preview-add" class="icon-preview"></span>
                </div>
                <div class="col">
                    <input type="text" class="form-control" id="category_icon_add" name="category_icon" placeholder="e.g. info-square" autocomplete="off" />
                </div>
                <div class="col-auto">
                    <button type="button" class="btn btn-outline-secondary" id="icon-picker-btn-add">Select</button>
                    <button type="button" class="btn btn-outline-danger ms-1" id="icon-clear-btn-add">Clear</button>
                </div>
            </div>
            <div class="mb-3">
                <label for="category_name_add" class="form-label"><?php echo $lang_admin['ADMIN_TICKET_CATS_LBL_CATEGORY_NAME'] ?? 'Category Name'; ?></label>
                <input type="text" class="form-control" id="category_name_add" name="category_name" required />
            </div>
            <button type="submit" name="add_ticket_category" class="btn btn-primary"><?php echo $lang_admin['ADMIN_TICKET_CATS_BTN_ADD_CATEGORY'] ?? 'Add Category'; ?></button>
        </form>
    </div>
</div>

<!-- Icon Picker Modal -->
<div class="modal fade icon-picker-modal" id="iconPickerModal" tabindex="-1" aria-labelledby="iconPickerModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="iconPickerModalLabel">Select an Icon</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <input type="text" class="form-control mb-3" id="icon-search-input" placeholder="Search icons...">
        <div class="icon-list d-flex flex-wrap gap-2" id="icon-list"></div>
      </div>
    </div>
  </div>
</div>

<!-- List Categories -->
<h5><?php echo $lang_admin['ADMIN_TICKET_CATS_LIST_TITLE'] ?? 'Existing Categories'; ?></h5>
<?php if (empty($ticketCategories)): ?>
    <p><?php echo $lang_admin['ADMIN_TICKET_CATS_NO_CATEGORIES_FOUND'] ?? 'No ticket categories found.'; ?></p>
<?php else: ?>
    <ul class="list-group">
        <?php foreach ($ticketCategories as $category): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
                <form action="<?php echo getCleanUrl('admin/tickets_categories'); ?>" method="post" class="d-inline-flex align-items-center flex-grow-1 me-2">
                    <?php echo get_csrf_input_field(); ?>
                    <input type="hidden" name="category_id" value="<?php echo $category['id']; ?>" />
                    <span class="icon-preview me-2"><?php if (!empty($category['icon'])): ?><i class="bi bi-<?php echo htmlspecialchars($category['icon']); ?>"></i><?php endif; ?></span>
                    <input type="text" class="form-control me-2" name="category_icon" value="<?php echo htmlspecialchars($category['icon'] ?? ''); ?>" placeholder="e.g. info-square" autocomplete="off" id="category_icon_edit_<?php echo $category['id']; ?>" />
                    <button type="button" class="btn btn-outline-secondary btn-sm me-1 icon-picker-btn-edit" data-target="category_icon_edit_<?php echo $category['id']; ?>">Select</button>
                    <button type="button" class="btn btn-outline-danger btn-sm me-2 icon-clear-btn-edit" data-target="category_icon_edit_<?php echo $category['id']; ?>">Clear</button>
                    <input type="text" class="form-control me-2" name="category_name" value="<?php echo htmlspecialchars($category['name']); ?>" />
                    <button type="submit" name="edit_ticket_category" class="btn btn-sm btn-primary me-2"><?php echo $lang_admin['ADMIN_TICKET_CATS_BTN_UPDATE'] ?? 'Update'; ?></button>
                </form>
                <form action="<?php echo getCleanUrl('admin/tickets_categories'); ?>" method="post" class="d-inline" onsubmit="return confirm('<?php echo addslashes($lang_admin['ADMIN_TICKET_CATS_JS_CONFIRM_DELETE'] ?? 'Are you sure you want to delete this category? This cannot be undone if not in use.'); ?>');">
                    <?php echo get_csrf_input_field(); ?>
                    <input type="hidden" name="category_id" value="<?php echo $category['id']; ?>" />
                    <button type="submit" name="delete_ticket_category" class="btn btn-sm btn-danger"><?php echo $lang_admin['ADMIN_TICKET_CATS_BTN_DELETE'] ?? 'Delete'; ?></button>
                </form>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

<script>
// Pass the version from PHP to JS
const BOOTSTRAP_ICONS_VERSION = <?php echo json_encode($bootstrapIconsVersion); ?>;
const BASE_URL = <?php echo json_encode(rtrim(defined('BASE_URL') ? BASE_URL : '', '/')); ?>;

let allBootstrapIcons = [];
let iconListLoaded = false;

function renderIconList(filter = '') {
  const iconList = document.getElementById('icon-list');
  iconList.innerHTML = '';
  const icons = allBootstrapIcons.filter(icon => icon.includes(filter.toLowerCase()));
  if (icons.length === 0) {
    iconList.innerHTML = `<div class='text-muted'>No icons found.</div>`;
    return;
  }
  icons.forEach(icon => {
    const div = document.createElement('div');
    div.className = 'icon-item';
    div.innerHTML = `<i class=\"bi bi-${icon}\" style=\"font-size: 1.5rem;\"></i><div class=\"small mt-1\">${icon}</div>`;
    div.onclick = function() {
      if (window.iconPickerTargetInput) {
        window.iconPickerTargetInput.value = icon;
        // Update preview if available
        const preview = window.iconPickerTargetInput.closest('form').querySelector('.icon-preview');
        if (preview) preview.innerHTML = `<i class='bi bi-${icon}'></i>`;
      }
      var modal = bootstrap.Modal.getInstance(document.getElementById('iconPickerModal'));
      modal.hide();
    };
    iconList.appendChild(div);
  });
}

function loadAllIconsAndRender(filter = '') {
  if (iconListLoaded) {
    renderIconList(filter);
    return;
  }
  // Always use BASE_URL as prefix for the fetch path
  const jsonUrl = BASE_URL + '/includes/css/bootstrap-icons.json';
  fetch(jsonUrl)
    .then(response => {
      if (!response.ok) throw new Error('Could not load local icon list.');
      return response.json();
    })
    .then(data => {
      allBootstrapIcons = Object.keys(data);
      iconListLoaded = true;
      renderIconList(filter);
    })
    .catch(err => {
      document.getElementById('icon-list').innerHTML = `<div class='text-danger'>Could not load icon list from includes/css/bootstrap-icons.json.</div>`;
    });
}

document.getElementById('icon-picker-btn-add').onclick = function() {
  window.iconPickerTargetInput = document.getElementById('category_icon_add');
  loadAllIconsAndRender();
  document.getElementById('icon-search-input').value = '';
  new bootstrap.Modal(document.getElementById('iconPickerModal')).show();
};
document.getElementById('icon-clear-btn-add').onclick = function() {
  document.getElementById('category_icon_add').value = '';
  document.getElementById('icon-preview-add').innerHTML = '';
};
document.getElementById('category_icon_add').addEventListener('input', function() {
  const val = this.value.trim();
  document.getElementById('icon-preview-add').innerHTML = val ? `<i class='bi bi-${val}'></i>` : '';
});
document.getElementById('icon-search-input').addEventListener('input', function() {
  loadAllIconsAndRender(this.value);
});
document.querySelectorAll('.icon-picker-btn-edit').forEach(function(btn) {
  btn.onclick = function() {
    const targetId = btn.getAttribute('data-target');
    window.iconPickerTargetInput = document.getElementById(targetId);
    loadAllIconsAndRender();
    document.getElementById('icon-search-input').value = '';
    new bootstrap.Modal(document.getElementById('iconPickerModal')).show();
  };
});
document.querySelectorAll('.icon-clear-btn-edit').forEach(function(btn) {
  btn.onclick = function() {
    const targetId = btn.getAttribute('data-target');
    const input = document.getElementById(targetId);
    if (input) input.value = '';
    // Update preview
    const preview = btn.closest('form').querySelector('.icon-preview');
    if (preview) preview.innerHTML = '';
  };
});
document.querySelectorAll('input[name^="category_icon"]').forEach(function(input) {
  input.addEventListener('input', function() {
    const preview = input.closest('form').querySelector('.icon-preview');
    preview.innerHTML = input.value.trim() ? `<i class='bi bi-${input.value.trim()}'></i>` : '';
  });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?> 