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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string)($_POST['email'] ?? ''));
    if ($email === '') {
        $errors[] = 'Email is required.';
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email AND is_active = 1 LIMIT 1");
        $stmt->execute([':email' => $email]);
        $userId = (int)$stmt->fetchColumn();

        if ($userId > 0) {
            $token = bin2hex(random_bytes(24));
            $expires = date('Y-m-d H:i:s', strtotime('+2 hours'));
            $stmt = $pdo->prepare("
                UPDATE users
                SET reset_token = :token,
                    reset_token_expires_at = :expires
                WHERE id = :id
            ");
            $stmt->execute([
                ':token' => $token,
                ':expires' => $expires,
                ':id' => $userId,
            ]);

            $ok = 'Reset link created: /public/auth/create_password.php?token=' . $token;
        } else {
            $ok = 'If the email exists, a reset link is ready.';
        }
    }
}
?>
<?php include __DIR__ . '/../includes/header.php'; ?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Reset password</h1>
    <span>Create reset link</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);white-space:pre-wrap"><?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">
    <div class="form-grid">
      <div class="form-group" style="grid-column:1/-1">
        <label>Email</label>
        <input type="email" name="email" placeholder="user@example.com">
      </div>
    </div>
    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Create reset link</button>
    </div>
  </form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
