<?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');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) redirect('list.php');

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

// Load user (scoped to company)
$sel = db()->prepare("
  SELECT u.id, u.name, u.email, u.role_id, r.name AS role_name
  FROM users u
  JOIN roles r ON r.id = u.role_id
  WHERE u.id = :id AND u.company_id = :cid
  LIMIT 1
");
$sel->execute([':id'=>$id, ':cid'=>$companyId]);
$user = $sel->fetch();
if (!$user) redirect('list.php');

$errors = [];

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[] = 'New password must be at least 8 characters.';
    if ($pass !== $pass2) $errors[] = 'Passwords do not match.';

    // unique email per company (exclude current)
    if (!$errors) {
      $chk = db()->prepare("SELECT 1 FROM users WHERE company_id = :cid AND email = :email AND id <> :id LIMIT 1");
      $chk->execute([':cid'=>$companyId, ':email'=>$email, ':id'=>$id]);
      if ($chk->fetch()) $errors[] = 'Email already exists for this company.';
    }

    if (!$errors) {
      if ($pass !== '') {
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        $upd = db()->prepare("
          UPDATE users SET name=:name, email=:email, role_id=:role_id, password_hash=:hash
          WHERE id=:id AND company_id=:cid
        ");
        $upd->execute([
          ':name'=>$name, ':email'=>$email, ':role_id'=>$role_id, ':hash'=>$hash,
          ':id'=>$id, ':cid'=>$companyId
        ]);
        audit_log('user.update', 'user', $id, ['fields'=>['name','email','role_id','password_hash']]);
      } else {
        $upd = db()->prepare("
          UPDATE users SET name=:name, email=:email, role_id=:role_id
          WHERE id=:id AND company_id=:cid
        ");
        $upd->execute([
          ':name'=>$name, ':email'=>$email, ':role_id'=>$role_id,
          ':id'=>$id, ':cid'=>$companyId
        ]);
        audit_log('user.update', 'user', $id, ['fields'=>['name','email','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">Edit 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'] ?? $user['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'] ?? $user['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'] ?? $user['role_id']))?'selected':'' ?>>
                <?= e($r['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">New Password (optional)</label>
          <input type="password" name="password" class="form-control" placeholder="Leave blank to keep current">
          <div class="form-text">Min 8 characters.</div>
        </div>
        <div class="col-md-6">
          <label class="form-label">Confirm New Password</label>
          <input type="password" name="password2" class="form-control" placeholder="Leave blank to keep current">
        </div>
      </div>
      <div class="mt-3">
        <button class="btn btn-dark">Save Changes</button>
      </div>
    </form>
  </div>
</div>
<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
