<?php
session_start();
require_once 'db/config.php';

// Check if user is authenticated (e.g., is an HR manager)
if (!isset($_SESSION['user_id'])) {
    // In a real app, you would also check for roles/permissions
    header('HTTP/1.1 403 Forbidden');
    exit('Access denied.');
}

// Get user_id from query string
$userId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
if (!$userId) {
    exit('Invalid user ID.');
}

$pdo = db();

// 1. Generate a secure, random token
$token = bin2hex(random_bytes(32));

// 2. Set an expiration date (e.g., 7 days from now)
$expiresAt = new DateTime();
$expiresAt->modify('+7 days');
$expiresAtFormatted = $expiresAt->format('Y-m-d H:i:s');

// 3. Update the user's record in the database
$stmt = $pdo->prepare("UPDATE users SET magic_token = ?, magic_token_expires_at = ? WHERE id = ?");
$success = $stmt->execute([$token, $expiresAtFormatted, $userId]);

// 4. Display the generated link
if ($success) {
    // Construct the full URL. In a real environment, use a config for the base URL.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $magicLink = "{$protocol}://{$host}/employee_welcome.php?token={$token}";

    echo "<h2>Magic Link Generated Successfully!</h2>";
    echo "<p>You can share this link with the new employee or click the button below to open it directly. It is valid for 7 days.</p>";
    echo "<a href='{$magicLink}' target='_blank' style='display: inline-block; margin-top: 10px; background-color: #2563eb; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold;'>Open Employee View in New Tab</a>";
    echo "<p style='margin-top: 20px; font-size: 0.9em; color: #555;'>Or, manually copy the link:</p>";
    echo "<input type='text' value='{$magicLink}' readonly style='width: 100%; padding: 8px; margin-top: 5px;' onclick='this.select();'>";
} else {
    echo "<h2>Error</h2>";
    echo "<p>Could not generate the magic link. Please try again.</p>";
}
