<?php
include 'includes/header.php';

// $page_title is now set after language files are loaded by header.php
// Ensure $lang_frontend, $lang_alerts, and $lang_navigation are available from header.php's centralized loader
$page_title = $lang_frontend['PAGE_TITLE_MAGIC_VERIFY'] ?? 'Magic Link Verification';
?>

<?php
// If user is already logged in, redirect them to dashboard
if (isLoggedIn()) {
    redirectTo('index');
}

// Check if magic links are enabled
if (!defined('MAGIC_LINKS') || !MAGIC_LINKS) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_MAGIC_LINKS_DISABLED'] ?? 'Magic links authentication is not enabled.', 'danger');
    redirectTo('login');
    exit;
}

$token = $_GET['token'] ?? null;
$errors = [];
$success = false;

if (!$token) {
    $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_INVALID_REQUEST_NEW'] ?? "Invalid magic link. Please request a new one.";
} else {
    try {
        // Verify the magic link token
        $stmt = $pdo->prepare("SELECT * FROM users WHERE magic_link_token = ? AND magic_link_expires_at > NOW()");
        $stmt->execute([$token]);
        $user = $stmt->fetch();

        if (!$user) {
            $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_EXPIRED_OR_INVALID'] ?? "This magic link has expired or is invalid. Please request a new one.";
        } elseif ((defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION) && !$user['is_email_verified'] && !in_array($user['role'] ?? '', ['admin', 'staff'], true)) {
            $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_EMAIL_NOT_VERIFIED'] ?? "Your email address is not verified. Please verify your email first or contact support.";
        } else {
            // Valid magic link - log the user in
            // Use transaction with row locking to prevent race condition (single-use enforcement)
            try {
                $pdo->beginTransaction();
                
                // Lock the user row and verify token is still valid (prevents concurrent use)
                $stmt_lock = $pdo->prepare("SELECT id, magic_link_token, magic_link_expires_at FROM users WHERE id = ? AND magic_link_token = ? AND magic_link_expires_at > NOW() FOR UPDATE");
                $stmt_lock->execute([$user['id'], $token]);
                $locked_user = $stmt_lock->fetch();
                
                if (!$locked_user) {
                    // Token was already used or expired between initial check and lock
                    $pdo->rollBack();
                    $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_EXPIRED_OR_INVALID'] ?? "This magic link has expired or is invalid. Please request a new one.";
                } else {
                    // Clear the magic link token atomically (single use)
                    $stmt_clear = $pdo->prepare("UPDATE users SET magic_link_token = NULL, magic_link_expires_at = NULL WHERE id = ? AND magic_link_token = ?");
                    $stmt_clear->execute([$user['id'], $token]);
                    
                    if ($stmt_clear->rowCount() === 0) {
                        // Token was cleared by another request
                        $pdo->rollBack();
                        $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_EXPIRED_OR_INVALID'] ?? "This magic link has already been used. Please request a new one.";
                    } else {
                        $pdo->commit();
                        
                        // Regenerate session ID for security AFTER token is cleared
                        // This ensures the session is tied to the new authentication state
                        session_regenerate_id(true);
                        
                        // Set session data
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['name'] = $user['name'];
                        $_SESSION['email'] = $user['email'];
                        $_SESSION['role'] = $user['role'];
                        $_SESSION['avatar'] = $user['avatar'];
                        $_SESSION['remember_me'] = false; // Magic links are short-term sessions
                        
                        // Use SessionManager to set proper session lifetime
                        SessionManager::refresh();
                        
                        // Update session state version after authentication
                        if (method_exists('SessionManager', 'updateSessionState')) {
                            SessionManager::updateSessionState();
                        }
                        
                        $success = true;
                        
                        // Set success message
                        $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_SUCCESS_MAGIC_LINK_LOGIN'] ?? 'Magic link login successful! Welcome back, %s!', htmlspecialchars($user['name'])), 'success');
                        
                        // Role-based redirects after successful login
                        if ($user['role'] === 'admin') {
                            // Admin users go to admin dashboard
                            redirectTo('admin/dashboard');
                        } elseif ($user['role'] === 'staff') {
                            // Staff users go to tickets page
                            redirectTo('tickets');
                        } else {
                            // Regular users go to account page
                            redirectTo('account');
                        }
                        exit;
                    }
                }
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                error_log("Magic link verification transaction error: " . $e->getMessage());
                $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_VERIFICATION_FAILED'] ?? "An error occurred while verifying your magic link. Please try again or use regular login.";
            }
        }
    } catch (PDOException $e) {
        error_log("Magic link verification error: " . $e->getMessage());
        $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_VERIFICATION_FAILED'] ?? "An error occurred while verifying your magic link. Please try again or use regular login.";
    }
}

// If we reach here, there was an error
?>
<?php if (defined('USE_LOGO_LOGIN') && USE_LOGO_LOGIN && defined('LOGO_LOGIN_URL') && !empty(LOGO_LOGIN_URL)): ?>
                <center><img src="<?php echo LOGO_LOGIN_URL; ?>" alt="" 
                    <?php echo (defined('LOGO_LOGIN_WIDTH') && LOGO_LOGIN_WIDTH) ? 'width="' . LOGO_LOGIN_WIDTH . '"' : ''; ?>><br><br></center>
           
<?php endif; ?>
<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-danger text-white">
                <h4 class="mb-0"><?php echo $lang_frontend['MAGIC_VERIFY_HEADING'] ?? 'Magic Link Verification'; ?></h4>
            </div>
            <div class="card-body">
                <?php
                if (!empty($errors)) {
                    foreach ($errors as $error) {
                        echo displayAlert($error, 'danger');
                    }
                }
                ?>

                <div class="text-center">
                    <i class="bi bi-exclamation-triangle-fill text-danger" style="font-size: 3rem;"></i>
                    <h5 class="mt-3"><?php echo $lang_frontend['MAGIC_VERIFY_UNABLE_TO_VERIFY_HEADING'] ?? 'Unable to Verify Magic Link'; ?></h5>
                    <p class="text-muted"><?php echo $lang_frontend['MAGIC_VERIFY_INVALID_EXPIRED_USED_TEXT'] ?? 'The magic link you clicked is either invalid, expired, or has already been used.'; ?></p>
                </div>

                <div class="d-grid gap-2">
                    <a href="<?php echo getCleanUrl('magic_login'); ?>" class="btn btn-primary">
                        <i class="bi bi-envelope"></i> <?php echo $lang_frontend['MAGIC_VERIFY_BUTTON_REQUEST_NEW'] ?? 'Request New Magic Link'; ?>
                    </a>
                    <a href="<?php echo getCleanUrl('login'); ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-person"></i> <?php echo $lang_frontend['MAGIC_VERIFY_BUTTON_USE_REGULAR_LOGIN'] ?? 'Use Regular Login'; ?>
                    </a>
                </div>

                <div class="mt-4 alert alert-info">
                    <strong><?php echo $lang_frontend['MAGIC_VERIFY_TROUBLESHOOTING_HEADING'] ?? 'Troubleshooting:'; ?></strong>
                    <ul class="mb-0 mt-2">
                        <li><?php echo $lang_frontend['MAGIC_VERIFY_TROUBLESHOOTING_ITEM_EXPIRE'] ?? 'Magic links expire after 30 minutes for security'; ?></li>
                        <li><?php echo $lang_frontend['MAGIC_VERIFY_TROUBLESHOOTING_ITEM_ONCE'] ?? 'Each magic link can only be used once'; ?></li>
                        <li><?php echo $lang_frontend['MAGIC_VERIFY_TROUBLESHOOTING_ITEM_MOST_RECENT'] ?? "Make sure you're using the most recent magic link sent to your email"; ?></li>
                        <li><?php echo $lang_frontend['MAGIC_VERIFY_TROUBLESHOOTING_ITEM_CACHE_REGULAR'] ?? 'If problems persist, try clearing your browser cache or using regular login'; ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?> 