<?php
/**
 * login.php — Portal login page
 */
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/csrf.php';

// Already logged in? Go to dashboard.
if (is_logged_in()) {
    header('Location: pages/dashboard.php');
    exit;
}

$timeout  = isset($_GET['timeout']);
$error    = '';
$username = '';

// ── Throttle constants ────────────────────────────────────────────────────────
define('LOGIN_MAX_ATTEMPTS', 5);    // max failures before lockout
define('LOGIN_WINDOW_SECS',  900);  // 15-minute rolling window

/**
 * Return the number of failed login attempts for $ip in the last window.
 * Fails OPEN on DB error (login page stays usable) but logs clearly so the
 * problem is visible in cPanel error logs immediately.
 */
function login_attempt_count(string $ip): int {
    try {
        $stmt = db()->prepare(
            'SELECT COUNT(*) FROM login_attempts
              WHERE ip_address = ?
                AND attempted_at >= DATE_SUB(NOW(), INTERVAL ? SECOND)'
        );
        $stmt->execute([$ip, LOGIN_WINDOW_SECS]);
        return (int) $stmt->fetchColumn();
    } catch (Throwable $e) {
        // Log prominently — this appears in cPanel error log under Metrics → Errors
        error_log(
            '[CES Portal] WARNING: login throttle check FAILED — brute-force protection is inactive. ' .
            'Ensure the login_attempts table exists (run install/schema.sql). Error: ' . $e->getMessage()
        );
        return 0; // fail open: login page still works, but throttling is off
    }
}

/**
 * Record one failed attempt for $ip.
 * Opportunistically cleans up old rows 1-in-10 requests to keep the table lean.
 */
function login_attempt_record(string $ip): void {
    try {
        db()->prepare(
            'INSERT INTO login_attempts (ip_address) VALUES (?)'
        )->execute([$ip]);

        // 10% chance: prune rows older than the window to keep the table small
        if (random_int(1, 10) === 1) {
            db()->prepare(
                'DELETE FROM login_attempts
                  WHERE attempted_at < DATE_SUB(NOW(), INTERVAL ? SECOND)'
            )->execute([LOGIN_WINDOW_SECS]);
        }
    } catch (Throwable $e) {
        // Log clearly — failure to record means throttling under-counts
        error_log(
            '[CES Portal] WARNING: login throttle write FAILED — failed attempts may not be counted. ' .
            'Ensure the login_attempts table exists (run install/schema.sql). Error: ' . $e->getMessage()
        );
    }
}

/**
 * Clear failed attempts for $ip on a successful login.
 */
function login_attempt_clear(string $ip): void {
    try {
        db()->prepare(
            'DELETE FROM login_attempts WHERE ip_address = ?'
        )->execute([$ip]);
    } catch (Throwable $e) {
        // Non-fatal; log for visibility
        error_log('[CES Portal] WARNING: login throttle clear FAILED. Error: ' . $e->getMessage());
    }
}

// ── Handle POST ───────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $client_ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $username  = trim($_POST['username'] ?? '');
    $password  = $_POST['password'] ?? '';

    // Check throttle BEFORE processing credentials
    if (login_attempt_count($client_ip) >= LOGIN_MAX_ATTEMPTS) {
        $error = 'Too many failed login attempts. Please wait 15 minutes and try again.';
    } elseif ($username === '' || $password === '') {
        $error = 'Please enter both username and password.';
    } else {
        $stmt = db()->prepare(
            'SELECT id, name, email, username, password_hash, role, agency_id, active
               FROM users
              WHERE username = ?
              LIMIT 1'
        );
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            login_attempt_record($client_ip);  // count this failure
            $error = 'Invalid username or password.';
        } elseif (!$user['active']) {
            // Don't record as a throttle event — valid user, just deactivated
            $error = 'Your account has been deactivated. Contact the administrator.';
        } else {
            login_attempt_clear($client_ip);   // reset on success

            login_user($user);

            // Log the login
            require_once __DIR__ . '/includes/audit.php';
            audit_log('user.login', 'User logged in', $user['id'], 'user');

            header('Location: pages/dashboard.php');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign In — <?= e(APP_NAME) ?></title>
    <link rel="shortcut icon" type="image/x-icon" href="<?= base_url('assets/img/favicon.png') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/vendor/css/bootstrap.css') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/vendor/css/fontawesome.css') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/css/custom.css') ?>">
</head>
<body class="auth-cover-bg-color">

<div class="auth-main">
    <div class="auth-sidebar">

        <!-- Left panel — branding / illustration -->
        <div class="d-none d-xl-flex auth-cover-sidebar flex-column justify-content-between"
             style="background: linear-gradient(135deg, #3b5de7 0%, #45cafc 100%); min-height:100vh; padding:3rem 2.5rem;">

            <div>
                <img src="<?= base_url('assets/img/logo_white.png') ?>" alt="<?= e(APP_NAME) ?>" style="max-height:50px;">
            </div>

            <div class="text-white text-center">
                <img src="<?= base_url('assets/img/svg/signupIllustration.svg') ?>"
                     alt="training illustration" style="max-width:360px;width:100%;" class="mb-4">
                <h3 class="fw-bold mb-2">PCA Certification Training</h3>
                <p class="mb-0 opacity-75">Manage learners, track progress,<br>and issue certificates — all in one place.</p>
            </div>

            <div>
                <img src="<?= base_url('assets/img/svg/signupBottom.svg') ?>" alt="" style="width:100%;">
            </div>
        </div>

        <!-- Right panel — login form -->
        <div class="auth-cover-content d-flex align-items-center justify-content-center">
            <div class="w-100" style="max-width:420px; padding:2rem;">

                <!-- Mobile-only logo -->
                <div class="d-xl-none text-center mb-4">
                    <img src="<?= base_url('assets/img/logo_dark.png') ?>" alt="<?= e(APP_NAME) ?>" style="max-height:44px;">
                </div>

                <h2 class="fw-bold mb-1">Welcome back</h2>
                <p class="text-muted mb-4">Sign in to <?= e(APP_NAME) ?></p>

                <?php if ($timeout): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    Your session timed out due to inactivity. Please sign in again.
                    <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                </div>
                <?php endif; ?>

                <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= e($error) ?>
                    <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                </div>
                <?php endif; ?>

                <form method="POST" action="login.php" novalidate>
                    <?= csrf_field() ?>

                    <div class="form-group mb-3">
                        <label for="username" class="form-label fw-semibold">Username</label>
                        <input type="text" id="username" name="username"
                               class="form-control form-control-lg"
                               value="<?= e($username) ?>"
                               placeholder="your.username"
                               required autofocus autocomplete="username">
                    </div>

                    <div class="form-group mb-4">
                        <label for="password" class="form-label fw-semibold">Password</label>
                        <div class="input-group">
                            <input type="password" id="password" name="password"
                                   class="form-control form-control-lg"
                                   placeholder="••••••••"
                                   required autocomplete="current-password">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-outline-secondary" id="togglePw"
                                        title="Show/hide password">
                                    <i class="feather-eye" id="pwIcon"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-lg w-100">
                        Sign In
                    </button>
                </form>

                <p class="text-center text-muted mt-4 mb-0" style="font-size:.85rem;">
                    <?= e(APP_NAME) ?> &copy; <?= date('Y') ?><br>
                    Contact your administrator if you need access.
                </p>

            </div>
        </div><!-- /.auth-cover-content -->

    </div><!-- /.auth-sidebar -->
</div><!-- /.auth-main -->

<script src="<?= base_url('assets/vendor/js/jquery.min.js') ?>"></script>
<script src="<?= base_url('assets/vendor/js/popper.js') ?>"></script>
<script src="<?= base_url('assets/vendor/js/bootstrap.min.js') ?>"></script>
<script src="<?= base_url('assets/vendor/js/feather.min.js') ?>"></script>
<script>
    feather.replace();

    // Toggle password visibility
    document.getElementById('togglePw').addEventListener('click', function () {
        var pw   = document.getElementById('password');
        var icon = document.getElementById('pwIcon');
        if (pw.type === 'password') {
            pw.type = 'text';
            icon.setAttribute('data-feather', 'eye-off');
        } else {
            pw.type = 'password';
            icon.setAttribute('data-feather', 'eye');
        }
        feather.replace();
    });
</script>
</body>
</html>
