<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
$pdo = crm_pdo();
$page_title = 'Accept Invitation';

$token = trim((string)($_GET['token'] ?? $_POST['token'] ?? ''));
$errors = [];
$ok = '';

$stmt = $pdo->prepare("SELECT * FROM user_invites WHERE invite_token = :token AND is_used = 0 AND expires_at >= NOW() LIMIT 1");
$stmt->execute([':token' => $token]);
$invite = $stmt->fetch();

if (!$invite) {
    http_response_code(404);
    exit('Invite not found or expired.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $password = (string)($_POST['password'] ?? '');
    $password2 = (string)($_POST['password_confirm'] ?? '');

    if ($password === '') $errors[] = 'Password is required.';
    if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters.';
    if ($password !== $password2) $errors[] = 'Passwords do not match.';

    if (!$errors) {
        $username = strstr((string)$invite['email'], '@', true) ?: ('user' . time());

        $stmt = $pdo->prepare("
            INSERT INTO users (username, email, password_hash, role, employee_id, external_partner_id, customer_id, is_active)
            VALUES (:username, :email, :password_hash, :role, :employee_id, :external_partner_id, :customer_id, 1)
        ");
        $stmt->execute([
            ':username' => $username,
            ':email' => $invite['email'],
            ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
            ':role' => $invite['role'],
            ':employee_id' => $invite['employee_id'] ?: null,
            ':external_partner_id' => $invite['external_partner_id'] ?: null,
            ':customer_id' => $invite['customer_id'] ?: null,
        ]);

        $stmt = $pdo->prepare("UPDATE user_invites SET is_used = 1 WHERE id = :id");
        $stmt->execute([':id' => (int)$invite['id']]);

        $ok = 'Account created successfully.';
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title"><h1>Accept Invitation</h1><span><?php echo h($invite['email']); ?></span></div>
</div>
<div class="card">
  <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?php echo h($ok); ?></div><?php endif; ?>
  <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
  <form method="post">
    <input type="hidden" name="token" value="<?php echo h($token); ?>">
    <div class="form-grid">
      <div class="form-group"><label>Password</label><input type="password" name="password"></div>
      <div class="form-group"><label>Confirm password</label><input type="password" name="password_confirm"></div>
    </div>
    <div class="form-actions"><button class="btn btn-primary" type="submit">Create account</button></div>
  </form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
