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

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

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

requirePermission('manage_roles');

/* =============================
   VALIDATE ID
============================= */

if (!isset($_GET['id'])) {
    header("Location: roles.php");
    exit;
}

$roleId = (int)$_GET['id'];

/* =============================
   FETCH ROLE
============================= */

$stmt = $pdo->prepare("SELECT * FROM roles WHERE id = ?");
$stmt->execute([$roleId]);
$role = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$role) {
    die("Role not found.");
}

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

/* =============================
   HANDLE UPDATE
============================= */

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

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

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

        // Prevent duplicate (excluding current role)
        $check = $pdo->prepare("
            SELECT id FROM roles 
            WHERE name = ? AND id != ?
        ");
        $check->execute([$name, $roleId]);

        if ($check->rowCount() > 0) {
            $error = "Another role with this name already exists.";
        } else {

            // Protect Admin role name change (optional safety)
            if ($roleId === 1) {
                $name = $role['name']; // lock admin name
            }

            $update = $pdo->prepare("
                UPDATE roles
                SET name = ?, description = ?
                WHERE id = ?
            ");

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

            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>Edit Role</h2>
    <p class="page-subtitle">
      Update role information and structure.
    </p>
  </div>

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

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

    <form method="POST">

      <label>Role Name *</label>
      <input type="text"
             name="name"
             value="<?= htmlspecialchars($role['name']) ?>"
             <?= $roleId === 1 ? 'readonly' : '' ?>
             required>

      <label>Description</label>
      <textarea name="description"
                style="width:100%;padding:10px;border-radius:8px;border:1px solid #ddd;margin-bottom:15px;"><?= htmlspecialchars($role['description'] ?? '') ?></textarea>

      <button type="submit" class="btn-primary">
        Update 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'; ?>