<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    $email = trim($_POST['email'] ?? '');
    if (!$email) throw new Exception('Please provide your email.');

    $stmt = $pdo->prepare("SELECT id, fullname FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) throw new Exception('No account found with that email.');

    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

    $stmt = $pdo->prepare("UPDATE users SET reset_token = ?, reset_expires = ? WHERE email = ?");
    $stmt->execute([$token, $expires, $email]);

    $resetLink = "https://intlbmellon.com/reset-password?token=" . urlencode($token);

    $subject = "Password Reset Request - Bmellonglobal";
    $body = "
        <p>Hello {$user['fullname']},</p>
        <p>We received a request to reset your password. Click the link below to reset it:</p>
        <p><a href='$resetLink' style='padding:10px 15px;background:#007bff;color:white;text-decoration:none;border-radius:5px;'>Reset Password</a></p>
        <p>This link expires in 1 hour.</p>
        <p>If you didn't request this, please ignore this email.</p>
        <p>— Bmellonglobal Team</p>
    ";

    if (!sendMail($email, $subject, $body)) {
        throw new Exception('Failed to send email. Please try again later.');
    }

    echo json_encode(['status' => 'success', 'message' => 'Password reset link has been sent to your email.']);
    exit;

} catch (Throwable $e) {
    error_log("Forgot password error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Something went wrong. Please try again later.']);
    exit;
}
