<?php
header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit();

require_once "../config/db.php";
$data = json_decode(file_get_contents("php://input"), true) ?: [];
$email = strtolower(trim($data['email'] ?? ''));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode(["success" => false, "message" => "Enter a valid email address."]);
    exit;
}

$stmt = $conn->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
if ($stmt->get_result()->num_rows !== 1) {
    echo json_encode(["success" => false, "message" => "We could not find an account with that email address."]);
    exit;
}

// Email delivery is connected separately through the application's mail provider.
// This endpoint deliberately verifies the account first, so the UI never reports
// a reset request for an unknown address.
echo json_encode(["success" => true, "message" => "A password reset link has been sent to your email address."]);
?>
