<?php
// public/product_categories.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "Product Categories - IMS";

function post_str(string $k): string { return trim((string)($_POST[$k] ?? '')); }
function post_int(string $k): int { return (int)($_POST[$k] ?? 0); }

$error = '';
$success = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Add
    if ($action === 'add') {
        $name = post_str('name');
        if ($name === '') {
            $error = "Category name is required.";
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO product_categories (name) VALUES (:name)");
                $stmt->execute([':name' => $name]);
                $success = "Category added.";
            } catch (PDOException $e) {
                $error = "Error adding category: " . $e->getMessage();
            }
        }
    }

    // Edit
    if ($action === 'edit') {
        $id = post_int('id');
        $name = post_str('name');

        if ($id <= 0 || $name === '') {
            $error = "Invalid category data.";
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE product_categories SET name = :name WHERE id = :id LIMIT 1");
                $stmt->execute([':name' => $name, ':id' => $id]);
                $success = "Category updated.";
            } catch (PDOException $e) {
                $error = "Error updating category: " . $e->getMessage();
            }
        }
    }

    // Delete
    if ($action === 'delete') {
        $id = post_int('id');
        if ($id <= 0) {
            $error = "Invalid category ID.";
        } else {
            try {
                // products.category_id has ON DELETE SET NULL, so safe
                $stmt = $pdo->prepare("DELETE FROM product_categories WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $id]);
                $success = "Category deleted (products in this category are now 'None').";
            } catch (PDOException $e) {
                $error = "Error deleting category: " . $e->getMessage();
            }
        }
    }
}

// Edit mode via GET
$edit_id = (int)($_GET['edit'] ?? 0);
$edit = null;

if ($edit_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM product_categories WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $edit_id]);
    $edit = $stmt->fetch();
    if (!$edit) {
        $error = "Category not found.";
        $edit_id = 0;
    }
}

// List
$cats = $pdo->query("SELECT * FROM product_categories ORDER BY name ASC")->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h4 class="mb-0">Product Categories</h4>
  </div>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <!-- Add/Edit -->
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3"><?= $edit_id > 0 ? 'Edit Category' : 'Add Category' ?></h5>

          <form method="POST">
            <input type="hidden" name="action" value="<?= $edit_id > 0 ? 'edit' : 'add' ?>">
            <?php if ($edit_id > 0): ?>
              <input type="hidden" name="id" value="<?= (int)$edit['id'] ?>">
            <?php endif; ?>

            <div class="mb-3">
              <label class="form-label">Category Name *</label>
              <input class="form-control" name="name" required
                     value="<?= htmlspecialchars($edit['name'] ?? '') ?>">
            </div>

            <button class="btn btn-primary w-100" type="submit">
              <?= $edit_id > 0 ? 'Save Changes' : 'Add Category' ?>
            </button>

            <?php if ($edit_id > 0): ?>
              <a class="btn btn-outline-secondary w-100 mt-2" href="product_categories.php">Cancel</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>

    <!-- List -->
    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Category List</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Name</th>
                  <th style="width:160px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$cats): ?>
                  <tr><td colspan="2" class="text-muted">No categories yet.</td></tr>
                <?php else: ?>
                  <?php foreach ($cats as $c): ?>
                    <tr>
                      <td><?= htmlspecialchars($c['name']) ?></td>
                      <td class="text-end">
                        <a class="btn btn-outline-primary btn-sm" href="product_categories.php?edit=<?= (int)$c['id'] ?>">Edit</a>

                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this category?');">
                          <input type="hidden" name="action" value="delete">
                          <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                          <button class="btn btn-outline-danger btn-sm" type="submit">Delete</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

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

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
