<?php
require_once __DIR__ . '/app/bootstrap.php';

if (current_user()) {
    redirect('dashboard.php');
}

if ((string)($_GET['session'] ?? '') === 'expired' && empty($_SESSION['session_expiry_notice_queued'])) {
    queue_session_expired_notice();
}

$authPage = true;
$pageTitle = 'Prijava';
$pageSubtitle = 'Pristup internom sistemu za zahteve';
$error = '';
$submittedEmail = is_scalar($_POST['email'] ?? '') ? mb_substr(strtolower(trim((string)$_POST['email'])), 0, 190) : '';

if (is_post()) {
    validate_csrf();

    $email = $submittedEmail;
    $password = is_scalar($_POST['password'] ?? '') ? (string)$_POST['password'] : '';
    $clientIp = request_client_ip();

    try {
        $rateLimitState = login_rate_limit_state($email, $clientIp);
    } catch (Throwable $e) {
        security_log_event('login_rate_limit_storage_unavailable');
        auth_audit_event('AUTH_LOCAL_FAILED', null, 'local', ['reason' => 'rate_limit_storage_unavailable']);
        http_response_code(503);
        $rateLimitState = null;
        $error = 'Prijava trenutno nije dostupna. Pokušajte ponovo kasnije.';
    }

    if ($rateLimitState && (bool)$rateLimitState['blocked']) {
        http_response_code(429);
        header('Retry-After: ' . (int)$rateLimitState['retry_after']);
        security_log_event('login_rate_limited', [
            'account_scope' => (bool)$rateLimitState['account_blocked'],
            'ip_scope' => (bool)$rateLimitState['ip_blocked'],
            'email_hash_prefix' => substr((string)$rateLimitState['email_hash'], 0, 12),
            'ip_hash_prefix' => substr((string)$rateLimitState['ip_hash'], 0, 12),
        ]);
        auth_audit_event('AUTH_LOCAL_FAILED', null, 'local', ['reason' => 'rate_limited']);
        $error = 'Previše neuspešnih pokušaja. Sačekajte nekoliko minuta i pokušajte ponovo.';
    } elseif ($rateLimitState) {
        login_rate_limit_apply_delay($rateLimitState);

        $loginUser = false;
        if (mb_strlen($email) <= 190 && filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $stmt = db()->prepare('SELECT id, name, email, password_hash, is_system_admin, is_active, must_change_password FROM users WHERE email = ? LIMIT 1');
            $stmt->execute([$email]);
            $loginUser = $stmt->fetch();
        }
        // Ista password provera se izvršava i za nepostojeći/neaktivan nalog kako vreme odgovora ne bi odavalo stanje naloga.
        $dummyHash = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
        $passwordValid = password_verify($password, $loginUser ? (string)$loginUser['password_hash'] : $dummyHash);

        if ($loginUser && (int)$loginUser['is_active'] === 1 && $passwordValid) {
            try {
                login_rate_limit_record($email, $clientIp, true);
            } catch (Throwable $e) {
                security_log_event('login_rate_limit_success_record_failed');
                auth_audit_event('AUTH_LOCAL_FAILED', (int)$loginUser['id'], 'local', ['reason' => 'rate_limit_storage_unavailable']);
                http_response_code(503);
                $error = 'Prijava trenutno nije dostupna. Pokušajte ponovo kasnije.';
                $loginUser = false;
            }
        }

        if ($loginUser && (int)$loginUser['is_active'] === 1 && $passwordValid) {
            $sessionUser = establish_authenticated_session((int)$loginUser['id'], 'local');
            auth_audit_event('AUTH_LOCAL_SUCCESS', (int)$loginUser['id'], 'local');
            if ((int)($sessionUser['must_change_password'] ?? 0) === 1) {
                flash('warning', 'Administrator je zahtevao da promenite privremenu lozinku pre pristupa sistemu.');
                redirect('password_change_required.php');
            }
            flash('success', 'Uspešno ste se prijavili.');
            redirect('dashboard.php');
        }

        if ($error === '') {
            try {
                login_rate_limit_record($email, $clientIp, false);
                security_log_event('login_failed', [
                    'email_hash_prefix' => substr(login_rate_limit_hash('email', $email), 0, 12),
                    'ip_hash_prefix' => substr(login_rate_limit_hash('ip', $clientIp), 0, 12),
                ]);
                auth_audit_event('AUTH_LOCAL_FAILED', $loginUser ? (int)$loginUser['id'] : null, 'local', [
                    'reason' => $loginUser && (int)$loginUser['is_active'] !== 1 ? 'disabled_user' : 'invalid_credentials',
                ]);
                $error = 'Neispravna email adresa, lozinka ili je nalog deaktiviran.';
            } catch (Throwable $e) {
                security_log_event('login_rate_limit_failure_record_failed');
                auth_audit_event('AUTH_LOCAL_FAILED', $loginUser ? (int)$loginUser['id'] : null, 'local', ['reason' => 'rate_limit_storage_unavailable']);
                http_response_code(503);
                $error = 'Prijava trenutno nije dostupna. Pokušajte ponovo kasnije.';
            }
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<form method="post" class="card login-card form-card" autocomplete="on" novalidate>
    <?= csrf_field() ?>
    <span class="badge login-badge">Bezbedan pristup</span>
    <h2>Prijava na sistem</h2>
    <p class="muted">Unesite službenu email adresu i lozinku za pristup internom portalu za zahteve.</p>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= e($error) ?></div>
    <?php endif; ?>

    <label>Email adresa
        <input type="email" name="email" required maxlength="190" autofocus autocomplete="username" value="<?= e($submittedEmail) ?>" placeholder="ime.prezime@sos-decijasela.rs">
    </label>

    <label>Lozinka
        <div class="polje-lozinka">
            <input id="lozinka" type="password" name="password" required autocomplete="current-password" placeholder="••••••••">
            <button class="button button-light password-eye" type="button" data-toggle-password="lozinka" aria-label="Prikaži lozinku" title="Prikaži lozinku">👁</button>
        </div>
    </label>

    <button class="button button-primary login-submit" type="submit"><span>Prijavi se</span><span aria-hidden="true">→</span></button>

    <div class="login-divider" role="separator" aria-label="ili"><span>ili</span></div>

    <a class="button button-light login-microsoft" href="<?= e(url('auth/entra/login')) ?>">
        <span class="microsoft-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
        <span>Prijavi se Microsoft 365 nalogom</span>
    </a>

    <?php if (defined('ALLOW_PUBLIC_REGISTRATION') && ALLOW_PUBLIC_REGISTRATION): ?>
        <p class="muted small">Nemate nalog? <a href="<?= e(url('register.php')) ?>">Registrujte se</a></p>
    <?php endif; ?>

</form>
<?php require_once __DIR__ . '/app/footer.php'; ?>
