<?php
// forgot_password.php: Handles password reset request for Ton Sui Mining
// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// Use explicit origin to comply with credentials=true
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'db.php';
require_once 'csrf.php';
// Safe include of mailer; if missing, we'll gracefully proceed without fatal
$mailerPath = __DIR__ . '/send_mail.php';
if (file_exists($mailerPath)) {
    require_once $mailerPath;
}

function respond($success, $message) {
    echo json_encode(['success' => $success, 'message' => $message]);
    exit;
}

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$email = trim($data['email'] ?? '');

if (!$email) {
    respond(false, 'Email is required.');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    respond(false, 'Invalid email format.');
}

try {
    // Check if user exists
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    // For security, don't reveal if the user exists or not
    if (!$user) {
        // Return success message even though no email will be sent
        // This prevents email enumeration attacks
        respond(true, 'If your email exists, you will receive a password reset link.');
    }
    
    // Generate a secure token
    $token = bin2hex(random_bytes(32)); // 64 character hex string
    
    $expires = new DateTime();
    $expires->modify('+24 hours');
    $expiresAt = $expires->format('Y-m-d H:i:s');
    
    // First, invalidate any existing tokens for this user
    $invalidateStmt = $pdo->prepare('UPDATE password_reset_tokens SET expires_at = NOW() WHERE user_id = ?');
    $invalidateStmt->execute([$user['id']]);
    
    // Insert the new token
    try {
        // Check if password_reset_tokens table exists
        $checkTableStmt = $pdo->query("SHOW TABLES LIKE 'password_reset_tokens'");
        $tableExists = $checkTableStmt->rowCount() > 0;
        
        if (!$tableExists) {
            // Create the table if it doesn't exist
            $createTableSQL = file_get_contents(__DIR__ . '/../install/password_reset_tokens.sql');
            $pdo->exec($createTableSQL);
        }
        
        // Now insert the token
        $tokenStmt = $pdo->prepare('INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)');
        $tokenStmt->execute([$user['id'], $token, $expiresAt]);
        
        // Generate reset link
        $siteUrl = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $siteUrl .= $_SERVER['HTTP_HOST'];
        
        // Point to the frontend reset page, not the API endpoint
        $resetUrl = $siteUrl . '/reset-password?token=' . urlencode($token) . '&email=' . urlencode($email);
        $htmlBody = "<h1>Password Reset Request</h1>" .
                    "<p>Hello,</p>" .
                    "<p>We received a request to reset the password for your Ton Sui Mining account.</p>" .
                    "<p><a href='$resetUrl'>Click here to reset your password</a></p>" .
                    "<p>Alternatively, you can copy and paste the following URL into your browser:</p>" .
                    "<p>$resetUrl</p>" .
                    "<p>This link will expire in 24 hours.</p>" .
                    "<p>If you did not request a password reset, please ignore this email.</p>" .
                    "<p>Regards,<br>Ton Sui Mining Team</p>";
        
        $textBody = "Password Reset Request\n\n" .
                    "Hello,\n\n" .
                    "We received a request to reset the password for your Ton Sui Mining account.\n\n" .
                    "To reset your password, please visit the following link:\n" .
                    "$resetUrl\n\n" .
                    "This link will expire in 24 hours.\n\n" .
                    "If you did not request a password reset, please ignore this email.\n\n" .
                    "Regards,\nTon Sui Mining Team";
        
        $mail_result = true;
        if (function_exists('send_mail')) {
            $mail_result = send_mail($email, 'Password Reset Request', $htmlBody, $textBody);
        } else {
            error_log('[forgot_password] send_mail.php not found; skipping email send');
        }
        
        if ($mail_result === true) {
            // Log the password reset request
            try {
                $logStmt = $pdo->prepare('INSERT INTO security_logs (event_type, user_id, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, NOW())');
                $logStmt->execute(['password_reset_request', $user['id'], $_SERVER['REMOTE_ADDR'] ?? 'unknown', $_SERVER['HTTP_USER_AGENT'] ?? 'unknown']);
            } catch (Exception $e) {
                error_log('Failed to log password reset request: ' . $e->getMessage());
            }
            
            respond(true, 'If your email exists, you will receive a password reset link.');
        } else {
            // Do not reveal failure; avoid enumeration and prevent network fatals from surfacing
            error_log('Failed to send reset email to ' . $email . ': ' . $mail_result);
            respond(true, 'If your email exists, you will receive a password reset link.');
        }
    } catch (PDOException $e) {
        error_log('Error storing reset token: ' . $e->getMessage());
        respond(false, 'An error occurred. Please try again later.');
    }
} catch (Exception $e) {
    error_log('Password reset error: ' . $e->getMessage());
    respond(false, 'An error occurred. Please try again later.');
}
