<?php
require_once(__DIR__ . '/../common.php');

// Function to sanitize user input
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Start session securely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Ensure a CSRF token exists for the login form.
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if form is submitted
if (isset($_POST['submit'])) {
    // Validate CSRF token before processing the login.
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])) {
        $error = '&nbsp; Invalid request. Please try again. &nbsp;';
    } else {
        // Email is sanitized for the lookup; the password must stay raw for password_verify().
        $email = sanitize_input($_POST['email']);
        $password = (string)($_POST['password'] ?? '');

        // Prepare and execute the SQL query securely using PDO
        $query = "SELECT * FROM sm_editors WHERE email = :email";

        try {
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($row && password_verify($password, $row['password'])) {
                // Prevent session fixation: issue a fresh session ID at login.
                session_regenerate_id(true);
                $_SESSION['editor_is_logged'] = true;
                $_SESSION['editor_id'] = $row['id'];
                $_SESSION['editor_type'] = $row['user_type'];  // 'superadmin', 'admin', etc.

                // Redirect to the main page
                header('Location: editors-main.php');
                exit;
            } else {
                // Same message whether the email is unknown or the password is wrong.
                $error = '&nbsp; Wrong Email or Password! &nbsp;';
            }
        } catch (PDOException $e) {
            $error = '&nbsp; Database error occurred! &nbsp;';
            error_log('PDOException: ' . $e->getMessage());  // Log the error
        }
    }
}

// Handle the 'login required' scenario
if (isset($_GET['loginrequired'])) {
    $error = '&nbsp; You need to be logged in to access that page &nbsp;';
}

// Handle logout
if (isset($_GET['logout'])) {
    // Regenerate session ID and destroy session securely
    if (session_status() !== PHP_SESSION_NONE) {
        session_regenerate_id(true);
        session_destroy();
    }
    $msg = '&nbsp; You have successfully logged out! &nbsp;';
}

include_once('header.php');
?>

<!-- Main Login Form Container -->
<div class="container">
    <h1>Staff Login</h1>
    <span class="msg"><?php if (isset($msg)) { echo $msg; } ?></span>
    <span class="error"><?php if (isset($error)) { echo $error; } ?></span>

    <!-- Updated form with CSRF token for security -->
    <form method="post" action="login.php" class="form-content">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
        <p>Email<br /><input name="email" type="text" required></p>
        <p>Password<br /><input name="password" type="password" required></p>
        <input name="submit" value="Login" type="submit" class="button-primary">
    </form>

    <!-- Forgot Password Link -->
    <p><a href="forgot-password.php">Forgot Password?</a></p>
</div>

<?php
include_once('footer.php');
?>
