<?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_LOGIN'] ?? 'Magic Link Login';
?>

<?php
// If user is already logged in, redirect them from this page
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;
}

$errors = [];
$success_message = '';

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token first
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $errors[] = $lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.';
    } else {
        // Use centralized email validation function
        $email_validation = validateEmail($_POST['email'] ?? '');
        if (!$email_validation['valid']) {
            $errors[] = $email_validation['errors'][0] ?? $lang_alerts['ALERT_ERROR_INVALID_EMAIL_ADDRESS'] ?? "Please enter a valid email address.";
        } else {
            $email = $email_validation['sanitized'];
            // Check rate limiting for magic link requests
            $rate_limit_check = checkRateLimit('magic_link', $email, 5, 3); // 5 minutes window, 3 attempts max
            if (!$rate_limit_check['allowed']) {
                $errors[] = $rate_limit_check['message'];
            } else {
                // Record this attempt for rate limiting
                recordSubmissionAttempt('magic_link', $email);
                
                try {
                    if (defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION) {
                        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_email_verified = 1");
                    } else {
                        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
                    }
                    $stmt->execute([$email]);
                    $user = $stmt->fetch();

                    if ($user) {
                        // Generate secure magic link token
                        $magic_token = bin2hex(random_bytes(32));
                        
                        // Calculate expiry time (30 minutes from now)
                        $expires_timestamp = time() + 1800; // 30 minutes
                        
                        // Create a DateTime object in current timezone, then convert to UTC for storage
                        try {
                            $dt = new DateTime("@{$expires_timestamp}");
                            $dt->setTimezone(new DateTimeZone('UTC'));
                            $expires_at_utc = $dt->format('Y-m-d H:i:s');
                        } catch (Exception $e) {
                            error_log("DateTime object creation failed for magic link expiry: " . $e->getMessage());
                            $expires_at_utc = date('Y-m-d H:i:s', $expires_timestamp);
                        }

                        // Store the magic link token
                        $stmt_update = $pdo->prepare("UPDATE users SET magic_link_token = ?, magic_link_expires_at = ? WHERE id = ?");
                        $stmt_update->execute([$magic_token, $expires_at_utc, $user['id']]);

                        // Create the magic link
                        $magic_link = getCleanUrl('magic_verify.php', ['token' => $magic_token]);
                        
                        // Send magic link email
                        $email_subject = sprintf($lang_frontend['EMAIL_SUBJECT_MAGIC_LOGIN_LINK'] ?? "%s - Your Magic Login Link", SITE_NAME);
                        $email_message = "
                            <p>" . sprintf($lang_frontend['EMAIL_GREETING'] ?? 'Hello %s,', htmlspecialchars($user['name'])) . "</p>
                            <p>" . sprintf($lang_frontend['EMAIL_TEXT_MAGIC_LINK_REQUESTED'] ?? 'You requested a magic login link for your account at %s.', SITE_NAME) . "</p>
                            <p>" . ($lang_frontend['EMAIL_TEXT_MAGIC_LINK_CLICK_BUTTON'] ?? 'Click the button below to login securely without a password:') . "</p>
                            <p style='margin: 20px 0;'>
                                <a href='" . $magic_link . "' style='background-color: #007bff; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;'>" . sprintf($lang_frontend['EMAIL_BUTTON_LOGIN_TO_SITE'] ?? 'Login to %s', SITE_NAME) . "</a>
                            </p>
                            <p>" . ($lang_frontend['EMAIL_TEXT_MAGIC_LINK_COPY_PASTE'] ?? 'Or copy and paste this link into your browser:') . "</p>
                            <p><a href='" . $magic_link . "'>" . $magic_link . "</a></p>
                            <p><strong>" . ($lang_frontend['EMAIL_TEXT_MAGIC_LINK_EXPIRY_NOTE'] ?? 'Important: This link will expire in 30 minutes and can only be used once.') . "</strong></p>
                            <p>" . ($lang_frontend['EMAIL_TEXT_MAGIC_LINK_IGNORE_IF_NOT_YOU'] ?? 'If you did not request this login link, please ignore this email and ensure your account is secure.') . "</p>
                            <p>" . ($lang_frontend['EMAIL_CLOSING_BEST_REGARDS'] ?? 'Best regards,') . "<br>" . sprintf($lang_frontend['EMAIL_SIGN_OFF_TEAM'] ?? 'The %s Team', SITE_NAME) . "</p>
                        ";

                        if (send_system_email($user['email'], $email_subject, $email_message)) {
                            $success_message = $lang_alerts['ALERT_SUCCESS_MAGIC_LINK_SENT'] ?? "A magic login link has been sent to your email address. Please check your inbox and click the link to login. The link will expire in 30 minutes.";
                        } else {
                            $errors[] = $lang_alerts['ALERT_ERROR_MAGIC_LINK_SEND_FAILED'] ?? "Could not send the magic login link. Please contact support or try the regular login.";
                            error_log("Failed to send magic link email to: " . $email);
                        }
                    } else {
                        // Don't reveal whether email exists or not (prevents user enumeration)
                        $success_message = $lang_alerts['ALERT_INFO_MAGIC_LINK_SENT_IF_EXISTS'] ?? "If an active account exists for that email address, a magic login link has been sent. Please check your inbox.";
                    }
                } catch (PDOException $e) {
                    error_log("Magic link request error: " . $e->getMessage());
                    $errors[] = $lang_alerts['ALERT_ERROR_PROCESSING_REQUEST'] ?? "An error occurred while processing your request. Please try again.";
                }
            }
        }
    }
}
?>
<?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-primary text-white">
                <h4 class="mb-0"><?php echo $lang_frontend['MAGIC_LOGIN_HEADING'] ?? 'Magic Link Login'; ?></h4>
            </div>
            <div class="card-body">
                <?php
                if (!empty($errors)) {
                    foreach ($errors as $error) {
                        echo displayAlert($error, 'danger');
                    }
                }
                if (!empty($success_message)) {
                    echo displayAlert($success_message, 'success');
                }
                ?>

                <?php if (empty($success_message)): ?>
                    <p><?php echo $lang_frontend['MAGIC_LOGIN_INSTRUCTION_P1'] ?? "Enter your email address and we'll send you a secure login link. No password required!"; ?></p>
                    
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> 
                        <?php echo $lang_frontend['MAGIC_LOGIN_HOW_IT_WORKS'] ?? "<strong>How it works:</strong> We'll send a secure link to your email that allows you to login instantly. The link expires in 30 minutes for your security."; ?>
                    </div>

                    <form action="<?php echo getCleanUrl('magic_login'); ?>" method="post">
                        <?php echo get_csrf_input_field(); ?>
                        <div class="mb-3">
                            <label for="email" class="form-label"><?php echo $lang_frontend['FORM_LABEL_YOUR_EMAIL_ADDRESS'] ?? 'Your Email Address'; ?></label>
                            <input type="email" class="form-control" id="email" name="email" required 
                                   value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>"
                                   placeholder="<?php echo $lang_frontend['FORM_PLACEHOLDER_ENTER_REGISTERED_EMAIL'] ?? 'Enter your registered email address'; ?>">
                        </div>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-envelope"></i> <?php echo $lang_frontend['MAGIC_LOGIN_BUTTON_SEND_LINK'] ?? 'Send Magic Login Link'; ?>
                            </button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
            <div class="card-footer text-center">
                <a href="<?php echo getCleanUrl('login'); ?>" class="text-muted">
                    <i class="bi bi-arrow-left"></i> <?php echo $lang_frontend['MAGIC_LOGIN_LINK_BACK_TO_REGULAR'] ?? 'Back to regular login'; ?>
                </a>
            </div>
        </div>
    </div>
</div>

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