<?php
require_once '../config/database.php';
require_once '../app/helpers/mailer.php';
require_once '../app/helpers/csrf.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    $csrfToken = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    if (!validateCsrfToken($csrfToken)) {
        http_response_code(419);
        echo json_encode(['status' => 'error', 'message' => 'Invalid or missing CSRF token']);
        exit;
    }
}

$action = $_GET['action'] ?? '';

if ($action === 'forgot') {

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM password_resets WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 MINUTE) AND user_id = (SELECT id FROM users WHERE email = ?)");
    $stmt->execute([$_POST['email'] ?? '']);
    if ((int)$stmt->fetchColumn() >= 3) {
        echo json_encode(['status' => 'error', 'message' => 'Too many requests. Please wait before trying again.']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id, email, name FROM users WHERE email=? AND deleted_at IS NULL");
    $stmt->execute([$_POST['email']]);
    $user = $stmt->fetch();

    if (!$user) {
        echo json_encode(['status'=>'success','message'=>'If email exists, reset link sent']);
        exit;
    }

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

    $pdo->prepare("DELETE FROM password_resets WHERE user_id = ?")
        ->execute([$user['id']]);

    $stmt = $pdo->prepare("
        INSERT INTO password_resets (user_id, token_hash, expires_at)
        VALUES (?,?,?)
    ");
    $stmt->execute([$user['id'], $tokenHash, $expires]);

    $config = file_exists(__DIR__ . '/../config/alerts.php') ? require __DIR__ . '/../config/alerts.php' : [];
    $baseUrl = $config['app_url'] ?? '';
    $resetLink = ($baseUrl !== '' ? rtrim((string)$baseUrl, '/') . '/reset_password_page.php' : 'http://localhost/wi/reset_password_page.php') . '?token=' . urlencode($token);
    $safeName = htmlspecialchars((string)($user['name'] ?? 'User'), ENT_QUOTES, 'UTF-8');
    $safeLink = htmlspecialchars($resetLink, ENT_QUOTES, 'UTF-8');
    sendMail((string)$user['email'], 'Password reset request', "
        <div style=\"font-family:Arial,sans-serif;color:#102033;line-height:1.55;\">
            <h2>Password reset request</h2>
            <p>Hello {$safeName},</p>
            <p>Use the link below to reset your Fleet Operations password. This link expires in 1 hour.</p>
            <p><a href=\"{$safeLink}\" style=\"background:#1d4ed8;color:#fff;padding:10px 14px;text-decoration:none;border-radius:6px;\">Reset Password</a></p>
            <p style=\"color:#667085;font-size:12px;\">If you did not request this, you can ignore this message.</p>
        </div>
    ");

    echo json_encode([
        'status'=>'success',
        'message'=>'If email exists, reset link sent'
    ]);
}