<?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);
$roles = settings_get_roles($conn, $orgId);
$flash = settings_flash_message();
$errors = [];

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

    if ($name === '') {
        $errors[] = 'Name is required.';
    }
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Enter a valid email address.';
    }
    if ($roleName === '') {
        $errors[] = 'Please select a role.';
    }

    if (!$errors) {
        if (settings_add_user($conn, $orgId, $name, $email, $roleName)) {
            settings_set_flash('success', 'User invited successfully.');
            header('Location: users.php');
            exit();
        }

        $errors[] = 'Unable to save the user. The email may already exist.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
  <title>Invite User | 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>
    .invite-form{max-width:1140px;padding:8px 0 0;}
    .invite-grid{display:grid;grid-template-columns:180px minmax(320px,548px);gap:24px 12px;align-items:center;}
    .invite-actions{display:flex;align-items:center;gap:16px;padding-top:22px;border-top:1px solid var(--border);margin-top:36px;}
    .cancel-btn{padding:10px 18px;border:1px solid #d1d5db;border-radius:8px;color:#374151;text-decoration:none;background:#fff;font-weight:600;}
    .req-copy{margin-left:auto;color:#ef4444;font-size:14px;}
    textarea.profile-input{height:112px;padding:12px;resize:vertical;}
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-user-plus'); ?>

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

    <section class="profile-main">
      <div class="profile-head">
        <h1>Invite User</h1>
        <div class="toolbar-actions">
          <a class="config-link" href="#">Preview invitation template</a>
        </div>
      </div>

      <div class="profile-card invite-form">
        <?php if ($flash['type'] === 'success'): ?>
          <div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div>
        <?php endif; ?>
        <?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="invite-grid">
            <label for="name">Name<span class="req">*</span></label>
            <input id="name" name="name" type="text" value="<?php echo htmlspecialchars((string) ($_POST['name'] ?? '')); ?>" required>

            <label for="email">Email<span class="req">*</span></label>
            <input id="email" name="email" type="email" value="<?php echo htmlspecialchars((string) ($_POST['email'] ?? '')); ?>" required>

            <label for="role_name">Role<span class="req">*</span></label>
            <select id="role_name" name="role_name" required>
              <option value="">Select</option>
              <?php foreach ($roles as $role): ?>
                <?php $selected = ((string) ($_POST['role_name'] ?? '')) === (string) $role['role_name'] ? 'selected' : ''; ?>
                <option value="<?php echo htmlspecialchars((string) $role['role_name']); ?>" <?php echo $selected; ?>>
                  <?php echo htmlspecialchars((string) $role['role_name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="invite-actions">
            <button class="save-btn" type="submit">Invite User</button>
            <a class="cancel-btn" href="users.php">Cancel</a>
            <div class="req-copy">* indicates mandatory fields</div>
          </div>
        </form>
      </div>
    </section>
  </main>
</body>
</html>

