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

// $page_title is now set after language files are loaded by header.php
// Ensure $lang_frontend and $lang_navigation are available from header.php's centralized loader
$page_title = $lang_frontend['PAGE_TITLE_LOGIN'] ?? ($lang_navigation['NAV_LOGIN'] ?? 'Login');
?>

<?php


if (isLoggedIn()) {
    redirectTo('index');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token first
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        // Don't redirect, show error on same page
    } else {
        $email = sanitizeInput($_POST['email']);
        $password = $_POST['password'];

        if (empty($email) || empty($password)) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_FILL_ALL_FIELDS'] ?? 'Please fill in all fields', 'danger');
        } else {
            // Check if database connection is available
            if ($pdo === null) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_DB_CONNECTION'] ?? 'Database connection error. Please try again later.', 'danger');
                error_log("Login failed: PDO connection is null");
            } else {
                $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();

                if ($user && password_verify($password, $user['password'])) {
                    // Check if email validation is required and if the email is verified
                    // Admin users should be exempt from this check.
                    if (defined('FORCE_EMAIL_VALIDATION') && FORCE_EMAIL_VALIDATION && !$user['is_email_verified'] && $user['role'] !== 'admin') {
                        $_SESSION['alert'] = displayAlert(
                            sprintf($lang_alerts['ALERT_WARNING_EMAIL_NOT_VERIFIED'] ?? 'Your email address is not yet verified. Please check your email (and spam folder) for the validation link. <a href="#" id="resendValidationLink" data-email="%s">Resend validation email?</a>', htmlspecialchars($user['email'])),
                            'warning',
                            true // Pass true for is_html to render the link correctly
                        );
                        // Do not proceed with login, let the page reload with the alert.
                    } else {
                        // Check remember me option before session operations
                        $rememberMe = isset($_POST['remember']) && $_POST['remember'] == 'on';

                        // Set remember me flag in session for SessionManager
                        $_SESSION['remember_me'] = $rememberMe;

                        // Use SessionManager to refresh session with new lifetime
                        SessionManager::refresh();

                        // Set session data first
                        // IMPORTANT: Set all session data BEFORE regenerating session ID
                        // This ensures the session is properly tied to the authenticated user
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['name'] = $user['name'];
                        $_SESSION['email'] = $user['email'];
                        $_SESSION['role'] = $user['role'];
                        $_SESSION['avatar'] = $user['avatar'];
                        $_SESSION['remember_me'] = $rememberMe;

                        // Regenerate session ID AFTER setting user data to prevent session fixation
                        // This ensures the session is tied to the new authentication state
                        // Order is critical: 1) Set data, 2) Regenerate ID, 3) Update session state
                        session_regenerate_id(true);

                        // Update session state version after role change
                        if (function_exists('SessionManager::updateSessionState')) {
                            SessionManager::updateSessionState();
                        }

                        // Link any guest subscriptions to this user account
                        if (function_exists('linkGuestSubscriptions')) {
                            linkGuestSubscriptions($user['id'], $user['email'], $pdo);
                        }

                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_LOGIN'] ?? 'Login successful, welcome back!');

                        // 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');
                        }
                    }
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CREDENTIALS'] ?? 'Invalid email or password', 'danger');
                    // Don't redirect, let the page display with the 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-primary text-white">
                <h4 class="mb-0">
                    <?php echo $lang_frontend['HOME_LOGIN_ACCOUNT_TITLE'] ?? ($lang_frontend['LOGIN_HEADING'] ?? 'Login to Your Account'); ?>
                </h4>
            </div>
            <div class="card-body">
                <?php
                // Display any alerts at the top of the login form
                if (isset($_SESSION['alert'])) {
                    echo $_SESSION['alert'];
                    unset($_SESSION['alert']);
                }
                ?>
                <?php if (SITE_LOGIN_MESSAGE !== ''): ?>
                    <p><?php echo htmlspecialchars(SITE_LOGIN_MESSAGE, ENT_QUOTES, 'UTF-8'); ?></p>
                <?php endif; ?>
                <form action="<?php echo getCleanUrl('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_EMAIL'] ?? 'Email address'; ?></label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="password"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_PASSWORD'] ?? 'Password'; ?></label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="remember" name="remember">
                        <label class="form-check-label"
                            for="remember"><?php echo $lang_frontend['FORM_LABEL_REMEMBER_ME'] ?? 'Remember me'; ?></label>
                    </div>
                    <?php if ((defined('ALLOW_PASSWORD_CHANGE') && ALLOW_PASSWORD_CHANGE) || isAdmin()): ?>
                        <div class="mb-3 text-end">
                            <a
                                href="<?php echo getCleanUrl('login_reset'); ?>"><?php echo $lang_frontend['LOGIN_LINK_FORGOT_PASSWORD'] ?? 'Forgot Password?'; ?></a>
                        </div>
                    <?php endif; ?>
                    <div class="d-grid">
                        <button type="submit"
                            class="btn btn-primary btn-lg"><?php echo $lang_frontend['LOGIN_BUTTON_LOGIN'] ?? ($lang_navigation['NAV_LOGIN'] ?? 'Login'); ?></button>
                    </div>
                </form>

                <?php if (defined('MAGIC_LINKS') && MAGIC_LINKS): ?>
                    <!-- Magic Links Option -->
                    <div class="text-center my-4">
                        <div class="position-relative">
                            <hr>
                            <span
                                class="position-absolute top-50 start-50 translate-middle bg-white px-3 text-muted small"><?php echo $lang_frontend['LOGIN_TEXT_OR_SEPARATOR'] ?? 'or'; ?></span>
                        </div>
                    </div>

                    <div class="d-grid">
                        <a href="<?php echo getCleanUrl('magic_login'); ?>" class="btn btn-outline-primary">
                            <i
                                class="bi bi-envelope"></i>&nbsp;&nbsp;<?php echo $lang_frontend['LOGIN_BUTTON_MAGIC_LINK'] ?? 'Login with Magic Link'; ?>
                        </a>
                    </div>

                    <div class="alert alert-info mt-3 small">
                        <i class="bi bi-info-circle"></i>
                        <?php echo $lang_frontend['LOGIN_INFO_MAGIC_LINK'] ?? '<strong>Magic Link:</strong> Get a secure login link sent to your email. No password required!'; ?>
                    </div>
                <?php endif; ?>
            </div>
            <div class="card-footer">
                <div class="text-center">
                    <?php if (ALLOW_REGISTER) { ?>
                        <?php echo $lang_frontend['LOGIN_TEXT_NO_ACCOUNT'] ?? "Don't have an account?"; ?> <a
                            href="<?php echo getCleanUrl('register'); ?>"><?php echo $lang_frontend['LOGIN_LINK_REGISTER_HERE'] ?? 'Register here'; ?></a>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const resendLink = document.getElementById('resendValidationLink');
        if (resendLink) {
            resendLink.addEventListener('click', function (event) {
                event.preventDefault();
                const email = this.dataset.email;

                // Simple way to resend: redirect to a new script or add a POST action here.
                // For now, let's assume a page `resend_validation.php` exists or will be created.
                // This script would generate a new token and send a new email.
                // To keep it simple for this step, we will just show an alert.
                // A more complete solution would involve an AJAX request or a form submission.

                // Create a form and submit it to a new handler page/logic
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '<?php echo getCleanUrl("resend_validation.php"); ?>'; // You'll need to create this page

                const csrfTokenField = document.createElement('input');
                csrfTokenField.type = 'hidden';
                csrfTokenField.name = 'csrf_token';
                csrfTokenField.value = '<?php echo isset($_SESSION["csrf_token"]) ? $_SESSION["csrf_token"] : ""; ?>'; // Get CSRF token if available
                form.appendChild(csrfTokenField);

                const emailField = document.createElement('input');
                emailField.type = 'hidden';
                emailField.name = 'email';
                emailField.value = email;
                form.appendChild(emailField);

                document.body.appendChild(form);
                form.submit();
            });
        }
    });
</script>