<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();
$errors = [];
$success = false;
$category = null;

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id > 0) {
    $category = $db->get("SELECT * FROM categories WHERE id = ?", [$id]);
    if (!$category) {
        $_SESSION['flash']['danger'] = 'Category not found.';
        header('Location: categories.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name        = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $status      = trim($_POST['status'] ?? 'active');

    if ($name === '') {
        $errors[] = 'Name is required.';
    }
    if ($description === '') {
        $errors[] = 'Description is required.';
    }
    if (!in_array($status, ['active','inactive'], true)) {
        $errors[] = 'Invalid status.';
    }

    // Check name uniqueness
    $existing = $db->get("SELECT id FROM categories WHERE name = ? AND id != ?", [$name, $id]);
    if ($existing) {
        $errors[] = 'Category name already exists.';
    }

    if (empty($errors)) {
        try {
            $categoryData = [
                'name' => $name,
                'description' => $description,
                'status' => $status,
                'updated_at' => formatDate(),
            ];

            if ($id > 0) {
                $db->update('categories', $categoryData, 'id = ?', [$id]);
                $_SESSION['flash']['success'] = 'Category updated successfully.';
            } else {
                $categoryData['created_at'] = formatDate();
                $db->insert('categories', $categoryData);
                $_SESSION['flash']['success'] = 'Category created successfully.';
            }
            header('Location: categories.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (!$category && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $category = [
        'name' => '',
        'description' => '',
        'status' => 'active',
    ];
}

$pageTitle = $id > 0 ? 'Edit Category' : 'Add Category';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
    <p class="text-muted mb-0"><?php echo $id > 0 ? 'Update category details' : 'Create a new category'; ?></p>
  </div>
  <div>
    <a href="categories.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Categories
    </a>
  </div>
</div>

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

<div class="card">
  <div class="card-body">
    <form method="post" action="">
      <div class="mb-3">
        <label for="name" class="form-label">Name</label>
        <input type="text" name="name" id="name" class="form-control" required value="<?php echo htmlspecialchars($_POST['name'] ?? ($category['name'] ?? '')); ?>">
      </div>

      <div class="mb-3">
        <label for="description" class="form-label">Description</label>
        <textarea name="description" id="description" class="form-control" rows="6" required><?php echo htmlspecialchars($_POST['description'] ?? ($category['description'] ?? '')); ?></textarea>
      </div>

      <div class="mb-3">
        <label for="status" class="form-label">Status</label>
        <select name="status" id="status" class="form-select" required>
          <?php foreach (['active','inactive'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo (($_POST['status'] ?? ($category['status'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="categories.php" class="btn btn-outline-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-save me-2"></i><?php echo $id > 0 ? 'Update' : 'Create'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

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