<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('roles.manage');

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

/* =============================
   REQUIRE PERMISSION
============================= */

requirePermission('manage_roles');

$message = '';
$error = '';

/* =============================
   HANDLE FORM SUBMIT
============================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if ($name === '') {
        $error = "Role name is required.";
    } else {

        // Check duplicate
        $check = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
        $check->execute([$name]);

        if ($check->rowCount() > 0) {
            $error = "Role already exists.";
        } else {

            $stmt = $pdo->prepare("
                INSERT INTO roles (name, description, created_at)
                VALUES (?, ?, NOW())
            ");

            $stmt->execute([$name, $description]);

            header("Location: roles.php");
            exit;
        }
    }
}

/* =============================
   LOAD LAYOUT
============================= */

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

<div class="main-content">

  <div class="page-header">
    <h2>Add Role</h2>
    <p class="page-subtitle">
      Create a new system role with access control structure.
    </p>
  </div>

  <div class="card-form" style="max-width:600px;">

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

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

    <form method="POST">

      <label>Role Name *</label>
      <input type="text" name="name" required>

      <label>Description</label>
      <textarea name="description"
                style="width:100%;padding:10px;border-radius:8px;border:1px solid #ddd;margin-bottom:15px;"></textarea>

      <button type="submit" class="btn-primary">
        Create Role
      </button>

      <a href="roles.php" class="btn-secondary" style="margin-left:10px;">
        Cancel
      </a>

    </form>

  </div>

</div>

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