<?php
require_once '../core/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: forgot_password.php');
    exit();
}

$email = trim($_POST['email'] ?? '');

if (empty($email)) {
    header('Location: forgot_password.php?error=' . urlencode('Please enter your email.'));
    exit();
}

$userModel = new User();
$user = $userModel->findByEmail($email);

if ($user) {
    // Generate Token
    $token = bin2hex(random_bytes(32));
    
    // Store Token
    $db = new Database();
    // Remove old tokens for this email
    $db->query("DELETE FROM password_resets WHERE email = :email");
    $db->bind(':email', $email);
    $db->execute();

    $db->query("INSERT INTO password_resets (email, token, created_at) VALUES (:email, :token, NOW())");
    $db->bind(':email', $email);
    $db->bind(':token', $token);
    $db->execute();

    // Simulate Sending Email (In production, use PHPMailer or similar)
    // For local development, we log the link to a file.
    $resetLink = URL_ROOT . "/app/reset_password.php?token=" . $token . "&email=" . urlencode($email);
    
    $logFile = __DIR__ . '/email_log.txt';
    $logMessage = "[" . date('Y-m-d H:i:s') . "] Password Reset for $email: $resetLink" . PHP_EOL;
    file_put_contents($logFile, $logMessage, FILE_APPEND);
}

// Always redirect to success to prevent email enumeration (security best practice)
// Check app/email_log.txt for the link if testing locally
header('Location: forgot_password.php?status=sent');
exit();