<?php
define('_FEXEC', 1);
require('includes/application_top.php');

// JSON + no-cache headers
header('Content-Type: application/json; charset=' . CHARSET);
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

// 1) Method guard
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['ok' => false, 'msg' => 'Method not allowed']); exit;
}

// 2) CSRF (accept POST field or X-CSRF-Token header)
$postedToken = $_POST['csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
if (empty($_SESSION['csrf_manual_reset']) || !hash_equals($_SESSION['csrf_manual_reset'], $postedToken)) {
  http_response_code(403);
  echo json_encode(['ok' => false, 'msg' => 'CSRF failed']); exit;
}

// 3) Validate input
$email = trim($_POST['email'] ?? '');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'msg' => 'Invalid email']); exit;
}

// 4) Config defaults
if (!defined('FILENAME_PASSWORD_RESET')) {
  define('FILENAME_PASSWORD_RESET', 'password_reset.php'); // adjust if needed
}
$throttleSeconds = 60; // prevent rapid resends per customer

// 5) Find customer
$qry = tep_db_query("
  SELECT customers_id, customers_firstname, customers_lastname, customers_timestamp
  FROM " . TABLE_CUSTOMERS . "
  WHERE customers_email_address = '" . tep_db_input($email) . "'
  LIMIT 1
");
$row = tep_db_fetch_array($qry);
if (!$row) {
  http_response_code(404);
  echo json_encode(['ok' => false, 'msg' => 'Customer not found']); exit;
}

// 6) Throttle resend
$now  = time();
$last = (int)($row['customers_timestamp'] ?? 0);
if ($last && ($now - $last) < $throttleSeconds) {
  http_response_code(429);
  echo json_encode(['ok' => false, 'msg' => 'Please wait a moment before resending']); exit;
}

// 7) Generate fresh token + save
try {
  $token = bin2hex(random_bytes(20)); // 40 chars
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok' => false, 'msg' => 'Token generation failed']); exit;
}

tep_db_query("UPDATE " . TABLE_CUSTOMERS . "
  SET customers_token = '" . tep_db_input($token) . "',
      customers_timestamp = " . (int)$now . "
  WHERE customers_id = " . (int)$row['customers_id'] . " LIMIT 1");

// 8) Build reset link (SSL)
$reset_link = tep_catalog_href_link(
  'password_reset.php',
  'email=' . urlencode($email) . '&token=' . urlencode($token),
  'SSL'
);

// 9) Send email
$name    = trim(($row['customers_firstname'] ?? '') . ' ' . ($row['customers_lastname'] ?? ''));
$subject = defined('MANUAL_RESET_EMAIL_SUBJECT') ? MANUAL_RESET_EMAIL_SUBJECT : 'Password Reset Instructions';
$body    = sprintf(
  "A password reset was requested.\n\nTo reset your password, click the link below:\n\n%s\n\nIf you did not request this, you can ignore this email.",
  $reset_link
);
tep_mail($name ?: $email, $email, $subject, $body, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);

// 10) (Optional) Audit log
/*
@tep_db_query("INSERT INTO admin_password_reset_log (admin_user, customers_id, action, meta, created_at)
  VALUES ('" . tep_db_input($_SESSION['admin']['username'] ?? 'unknown') . "',
          " . (int)$row['customers_id'] . ",
          'SEND_RESET',
          '" . tep_db_input(json_encode(['email'=>$email])) . "',
          NOW())");
*/

// 11) Done
echo json_encode(['ok' => true, 'msg' => 'Reset email sent', 'ts' => $now]);
