<?php
require_once('common.php'); // Ensure this file includes the config file where $pdo is defined

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

// Initialize error and message variables
$error = '';
$msg = '';

// Check if the form is submitted
if (isset($_POST['submit'])) {
    // CSRF Protection: Verify the CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = 'Invalid request. Please try again.';
    } elseif (function_exists('captcha_verify') && !captcha_verify($_POST)) {
        $error = 'Please complete the verification and try again.';
    } else {
        // Prepare and sanitize user input
        $email = trim($_POST['email']);
        $password = trim($_POST['password']);

        // Use PDO to prepare the query to prevent SQL injection
        $query = "SELECT * FROM sm_poets WHERE email = :email AND email_confirmed = 1";

        try {
            // Prepare the statement using PDO
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($result) {
                // Verify the password using password_hash() and password_verify()
                if (password_verify($password, $result['password'])) {
                    // Prevent session fixation: issue a fresh session ID at login.
                    session_regenerate_id(true);
                    $_SESSION['poet_is_logged'] = true;
                    $_SESSION['poet_id'] = $result['id'];
                    header('Location: main.php');
                    exit;
                } else {
                    $error = 'Invalid Email or Password.';
                }
            } else {
                $error = 'Sorry! You either entered the wrong Email or Password, have not signed up, or haven\'t clicked the email validation link we sent.';
            }
        } catch (PDOException $e) {
            // Log details server-side; show the visitor a generic message.
            error_log('login.php PDOException: ' . $e->getMessage());
            $error = 'A temporary error occurred. Please try again.';
        }
    }
}

// Handle login required or logout actions
if (isset($_GET['loginrequired'])) {
    $error = 'You need to be logged in to access that page.';
}

if (isset($_GET['logout'])) {
    session_destroy();
    $msg = 'You have successfully logged out!';
}

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

// Include header and menu
include_once('header.php');
include_once('menu.php');
?>

<div class="container">
    <h1>Login</h1>
    <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
    <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>

    <form method="post" action="login.php">
        <!-- CSRF Token Field -->
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">

        <!-- Email Field -->
        <div class="form-group">
            <label for="email">Email Address:</label><br />
            <input id="email" value="<?= isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8') : '' ?>" name="email" type="text" />
        </div>

        <!-- Password Field -->
        <div class="form-group">
            <label for="password">Password:</label><br />
            <input id="password" value="<?= isset($_POST['password']) ? htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8') : '' ?>" name="password" type="password" />
        </div>

        <!-- Human verification (Turnstile or image captcha) -->
        <div class="form-group"><?= function_exists('captcha_widget') ? captcha_widget() : '' ?></div>

        <!-- Submit Button -->
        <input name="submit" value="Login" type="submit" class="btn" />

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

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