<?php
declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role('Admin');

$companyId = current_user()['company_id'] ?? null;
if (!$companyId) redirect('../../public/index.php');

$errors = [];
$roles = db()->query("SELECT id, name FROM roles ORDER BY name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    $name     = trim((string)($_POST['name'] ?? ''));
    $email    = trim((string)($_POST['email'] ?? ''));
    $role_id  = (int)($_POST['role_id'] ?? 0);
    $pass     = (string)($_POST['password'] ?? '');
    $pass2    = (string)($_POST['password2'] ?? '');

    if ($name === '' || $email === '' || $role_id <= 0) $errors[] = 'Name, email and role are required.';
    if ($pass === '' || strlen($pass) < 8) $errors[] = 'Password must be at least 8 characters.';
    if ($pass !== $pass2) $errors[] = 'Passwords do not match.';

    if (!$errors) {
      // Unique email per company
      $chk = db()->prepare("SELECT 1 FROM users WHERE company_id = :cid AND email = :email LIMIT 1");
      $chk->execute([':cid' => $companyId, ':email' => $email]);
      if ($chk->fetch()) {
        $errors[] = 'Email already exists for this company.';
      } else {
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        $ins = db()->prepare("
          INSERT INTO users (company_id, name, email, password_hash, role_id, last_login)
          VALUES (:cid, :name, :email, :hash, :role_id, NULL)
        ");
        $ins->execute([
          ':cid'     => $companyId,
          ':name'    => $name,
          ':email'   => $email,
          ':hash'    => $hash,
          ':role_id' => $role_id,
        ]);
        $newId = (int)db()->lastInsertId();

        audit_log('user.create', 'user', $newId, ['name'=>$name,'email'=>$email,'role_id'=>$role_id]);
        redirect('list.php');
      }
    }
  } catch (Throwable $e) {
    $errors[] = (APP_ENV === 'dev') ? $e->getMessage() : 'Unexpected error.';
  }
}

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Add User</h1>
  <a href="list.php" class="btn btn-outline-secondary">Back</a>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <?php if ($errors): ?>
      <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.e($e).'</li>'; ?></ul></div>
    <?php endif; ?>

    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Name</label>
          <input name="name" class="form-control" required value="<?= e($_POST['name'] ?? '') ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Email</label>
          <input type="email" name="email" class="form-control" required value="<?= e($_POST['email'] ?? '') ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Role</label>
          <select name="role_id" class="form-select" required>
            <option value="">Select role</option>
            <?php foreach ($roles as $r): ?>
              <option value="<?= (int)$r['id'] ?>" <?= ((int)($r['id']) === (int)($_POST['role_id'] ?? 0))?'selected':'' ?>>
                <?= e($r['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Password</label>
          <input type="password" name="password" class="form-control" required>
          <div class="form-text">Min 8 characters.</div>
        </div>
        <div class="col-md-6">
          <label class="form-label">Confirm Password</label>
          <input type="password" name="password2" class="form-control" required>
        </div>
      </div>
      <div class="mt-3">
        <button class="btn btn-dark">Create User</button>
      </div>
    </form>
  </div>
</div>
<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
