<?php
header('Content-Type: application/json');

$tokenFilePath = '../../database/sellers/sellers_registration_data.json';
$input = json_decode(file_get_contents('php://input'), true);
$token = isset($input['token']) ? $input['token'] : '';

if (!$token) {
    echo json_encode(['success' => false, 'message' => 'Missing token']);
    exit;
}

if (!file_exists($tokenFilePath)) {
    echo json_encode(['success' => false, 'message' => 'Data file not found']);
    exit;
}

$users = json_decode(file_get_contents($tokenFilePath), true);
$found = false;
$currentTime = time();

foreach ($users as &$user) {
    if (isset($user['temporary_token_id']) && $user['temporary_token_id'] === $token) {
        // Optional: Check expiry (within 5 seconds)
        if (isset($user['token_created_at']) && ($currentTime - $user['token_created_at']) > 5) {
            echo json_encode(['success' => false, 'message' => 'Token expired']);
            exit;
        }

        // Return email and password (for autofill only, NOT for production)
        echo json_encode([
            'success' => true,
            'email' => $user['email'],
            'password' => $user['password'] // In production: don't return passwords
        ]);
        $found = true;

        // Optionally, clear token so it can't be reused
        $user['temporary_token_id'] = '';
        $user['token_created_at'] = '';
        break;
    }
}

if (!$found) {
    echo json_encode(['success' => false, 'message' => 'Token not found']);
} else {
    // Save changes (remove token from file)
    file_put_contents($tokenFilePath, json_encode($users, JSON_PRETTY_PRINT));
}
?>