<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$sections = settings_role_permission_sections();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $roleName = trim((string) ($_POST['role_name'] ?? ''));
    $description = trim((string) ($_POST['description'] ?? ''));
    $permissions = $_POST['permissions'] ?? [];

    if ($roleName === '') {
        $errors[] = 'Role name is required.';
    }

    if (!$errors) {
        if (settings_add_role($conn, $orgId, $roleName, $description, $permissions)) {
            settings_set_flash('success', 'Role created successfully.');
            header('Location: roles.php');
            exit();
        }

        $errors[] = 'Unable to save this role. The role name may already exist.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>New Role | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <style>
    .role-grid{display:grid;grid-template-columns:180px minmax(300px,450px);gap:24px 12px;align-items:start;}
    .role-grid textarea{height:106px;padding:12px;resize:vertical;}
    .permission-section{margin-top:18px;border:1px solid var(--border);border-radius:14px;background:#fff;overflow:hidden;box-shadow:0 10px 22px rgba(15,23,42,0.05);}
    .permission-head{display:flex;align-items:center;justify-content:space-between;padding:18px 22px;border-bottom:1px solid var(--border);}
    .permission-head h3{margin:0;font-size:18px;}
    .permission-toggle{width:52px;height:28px;border-radius:999px;background:#3b82f6;position:relative;}
    .permission-toggle::after{content:"";position:absolute;top:3px;right:3px;width:22px;height:22px;border-radius:50%;background:#fff;}
    .permission-table{width:100%;border-collapse:collapse;}
    .permission-table th,.permission-table td{padding:14px 18px;border-top:1px solid #edf1f7;text-align:center;}
    .permission-table th:first-child,.permission-table td:first-child{text-align:left;padding-left:30px;}
    .permission-table th{font-size:12px;text-transform:uppercase;color:#334155;font-weight:700;}
    .permission-table td:first-child{font-size:15px;color:#111827;width:30%;}
    .check-cell input,.perm-list input{width:20px;height:20px;accent-color:#3b82f6;}
    .perm-list{padding:16px 30px 8px;display:grid;gap:14px;}
    .perm-list label{display:flex;align-items:flex-start;gap:12px;font-size:15px;color:#111827;}
    .perm-checklist{padding:16px 24px 8px;display:grid;grid-template-columns:1fr;gap:12px;}
    .perm-checklist label{display:flex;align-items:flex-start;gap:12px;font-size:15px;color:#111827;}
    .bottom-actions{display:flex;align-items:center;gap:14px;margin-top:20px;}
    .cancel-btn{padding:10px 18px;border:1px solid #d1d5db;border-radius:8px;color:#374151;text-decoration:none;background:#fff;font-weight:600;}
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-user-tag'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('roles'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1>New Role</h1>
        <div class="toolbar-actions">
          <a class="settings-close" href="roles.php" style="padding:8px 12px;">x</a>
        </div>
      </div>

      <div class="profile-card">
        <?php if ($errors): ?>
          <div class="alert-err">
            <div class="alert-err-title">Please fix the following:</div>
            <ul>
              <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <form method="post">
          <div class="role-grid">
            <label for="role_name">Role Name<span class="req">*</span></label>
            <input id="role_name" name="role_name" type="text" value="<?php echo htmlspecialchars((string) ($_POST['role_name'] ?? '')); ?>" required>

            <label for="description">Description</label>
            <textarea id="description" name="description" placeholder="Max 500 Characters"><?php echo htmlspecialchars((string) ($_POST['description'] ?? '')); ?></textarea>
          </div>

          <div style="margin-top:32px;">
            <h2 style="font-size:18px;margin-bottom:6px;">Permission Categories</h2>
            <div class="muted" style="font-size:15px;">Choose what this role can access or manage.</div>
          </div>

          <?php foreach ($sections as $sectionIndex => $section): ?>
            <div class="permission-section">
              <div class="permission-head">
                <h3><?php echo htmlspecialchars((string) $section['title']); ?></h3>
                <?php if (!empty($section['toggle'])): ?>
                  <span class="permission-toggle" aria-hidden="true"></span>
                <?php endif; ?>
              </div>

              <?php if (!empty($section['rows']) && !empty($section['columns'])): ?>
                <table class="permission-table">
                  <thead>
                    <tr>
                      <th></th>
                      <?php foreach ($section['columns'] as $column): ?>
                        <th><?php echo htmlspecialchars($column); ?></th>
                      <?php endforeach; ?>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($section['rows'] as $rowIndex => $row): ?>
                      <tr>
                        <td><?php echo htmlspecialchars($row); ?></td>
                        <?php foreach ($section['columns'] as $column): ?>
                          <?php
                            $permissionKey = strtolower(preg_replace('/[^a-z0-9]+/', '_', $section['title'] . '_' . $row . '_' . $column));
                            $checked = isset($_POST['permissions'][$permissionKey]) ? 'checked' : 'checked';
                          ?>
                          <td class="check-cell">
                            <input type="checkbox" name="permissions[<?php echo htmlspecialchars($permissionKey); ?>]" value="1" <?php echo $checked; ?>>
                          </td>
                        <?php endforeach; ?>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              <?php endif; ?>

              <?php if (!empty($section['notes'])): ?>
                <div class="perm-list">
                  <?php foreach ($section['notes'] as $note): ?>
                    <?php $noteKey = strtolower(preg_replace('/[^a-z0-9]+/', '_', $section['title'] . '_' . $note)); ?>
                    <label>
                      <input type="checkbox" name="permissions[<?php echo htmlspecialchars($noteKey); ?>]" value="1" checked>
                      <span><?php echo htmlspecialchars($note); ?></span>
                    </label>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>

              <?php if (!empty($section['checklist'])): ?>
                <div class="perm-checklist">
                  <?php foreach ($section['checklist'] as $item): ?>
                    <?php $itemKey = strtolower(preg_replace('/[^a-z0-9]+/', '_', $section['title'] . '_' . $item)); ?>
                    <label>
                      <input type="checkbox" name="permissions[<?php echo htmlspecialchars($itemKey); ?>]" value="1" checked>
                      <span><?php echo htmlspecialchars($item); ?></span>
                    </label>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>

          <div class="bottom-actions">
            <button class="save-btn" type="submit">Save</button>
            <a class="cancel-btn" href="roles.php">Cancel</a>
          </div>
        </form>
      </div>
    </section>
  </main>
</body>
</html>
