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

$token = trim((string)($_GET['token'] ?? $_POST['token'] ?? ''));
if ($token === '') die('Missing token.');

$stmt = $pdo->prepare("
    SELECT id, username, email, role, reset_token_expires_at
    FROM users
    WHERE reset_token = :token
    LIMIT 1
");
$stmt->execute([':token' => $token]);
$user = $stmt->fetch();
if (!$user) die('Invalid token.');
if (empty($user['reset_token_expires_at']) || strtotime((string)$user['reset_token_expires_at']) < time()) die('Token expired.');

$errors = [];
$ok = '';

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

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

    if (!$errors) {
        $stmt = $pdo->prepare("
            UPDATE users
            SET password_hash = :hash,
                reset_token = NULL,
                reset_token_expires_at = NULL,
                is_active = 1
            WHERE id = :id
        ");
        $stmt->execute([
            ':hash' => password_hash($password, PASSWORD_DEFAULT),
            ':id' => (int)$user['id'],
        ]);
        $ok = 'Password created successfully. You can now log in.';
    }
}
?>
<?php include __DIR__ . '/../includes/header.php'; ?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Create password</h1>
    <span><?php echo h($user['username']); ?></span>
  </div>
</div>

<div class="card">
  <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#bbf7d0;border-color:rgba(22,163,74,.35)"><?php echo h($ok); ?></div><?php endif; ?>
  <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

  <?php if (!$ok): ?>
  <form method="post">
    <input type="hidden" name="token" value="<?php echo h($token); ?>">
    <div class="form-grid">
      <div class="form-group">
        <label>New 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">Save password</button>
    </div>
  </form>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
