<!DOCTYPE html>
<html lang="en">

<head>
    <title>Login | Radiologi</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="shortcut icon" type="image/png" href="<?= base_url('assets_/assets/img/logo-mini.png') ?>">
    <style media="screen">
        *,
        *:before,
        *:after {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            /* Mempertahankan warna background asli Anda */
            background-color: rgba(53, 134, 64, 0.64);
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            font-family: 'Poppins', sans-serif;
        }

        .background {
            width: 430px;
            height: 600px;
            position: absolute;
            transform: translate(-50%, -50%);
            left: 50%;
            top: 50%;
        }

        .background .shape {
            height: 220px;
            width: 220px;
            position: absolute;
            border-radius: 50%;
            filter: blur(8px);
            /* Menambah blur pada ornamen di belakang */
        }

        .shape:first-child {
            background: linear-gradient(#1845ad, #23a2f6);
            left: -90px;
            top: -90px;
        }

        .shape:last-child {
            background: linear-gradient(to right, #ff512f, #f09819);
            right: -40px;
            bottom: -50px;
        }

        form {
            height: auto;
            min-height: 520px;
            width: 420px;
            /* Efek Glassmorphism yang lebih elegan */
            background-color: rgba(255, 255, 255, 0.15);
            position: absolute;
            transform: translate(-50%, -50%);
            top: 50%;
            left: 50%;
            border-radius: 16px;
            backdrop-filter: blur(15px);
            -webkit-backdrop-filter: blur(15px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-top: 1px solid rgba(255, 255, 255, 0.5);
            border-left: 1px solid rgba(255, 255, 255, 0.5);
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15);
            padding: 45px 40px;
        }

        form * {
            color: #ffffff;
            letter-spacing: 0.5px;
            outline: none;
            border: none;
        }

        .logo-container {
            text-align: center;
            margin-bottom: 25px;
        }

        .logo-container img {
            width: 90px;
            height: auto;
            filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.2));
        }

        form h3 {
            font-size: 28px;
            font-weight: 600;
            text-align: center;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        /* Container Input dengan Ikon */
        .input-group {
            position: relative;
            margin-top: 20px;
        }

        .input-group i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.7);
            font-size: 16px;
            transition: 0.3s ease;
        }

        input {
            display: block;
            height: 52px;
            width: 100%;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 0 15px 0 45px;
            /* Spasi untuk ikon di kiri */
            font-size: 14px;
            font-weight: 400;
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.3s ease;
        }

        input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        /* Efek Fokus Input */
        input:focus {
            background-color: rgba(255, 255, 255, 0.2);
            border-left: 4px solid #ffffff;
            padding-left: 42px;
            /* Penyesuaian agar teks tidak bergeser */
        }

        input:focus+i,
        .input-group input:focus~i {
            color: #ffffff;
        }

        /* Styling Captcha */
        .captcha-container {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            align-items: center;
        }

        #captcha-code {
            background: rgba(0, 0, 0, 0.2);
            padding: 12px;
            border-radius: 8px;
            font-weight: 600;
            letter-spacing: 8px;
            font-size: 18px;
            user-select: none;
            width: 100%;
            text-align: center;
            color: #fff;
            border: 1px dashed rgba(255, 255, 255, 0.4);
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        #refresh-captcha {
            width: 52px;
            height: 52px;
            margin: 0;
            background-color: rgba(255, 255, 255, 0.15);
            color: #fff;
            border-radius: 8px;
            transition: 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: pointer;
        }

        #refresh-captcha:hover {
            background-color: rgba(255, 255, 255, 0.3);
            transform: rotate(90deg);
        }

        /* Grup Tombol Bawah (Sejajar ke samping) */
        .button-group {
            display: flex;
            gap: 12px;
            margin-top: 30px;
        }

        button {
            padding: 14px 0;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        #submit-btn {
            width: 65%;
            /* Tombol masuk lebih lebar */
            background-color: #ffffff;
            color: #080710;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        #submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }

        #submit-btn:disabled {
            background-color: rgba(255, 255, 255, 0.5);
            color: #333;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-kembali {
            width: 35%;
            /* Tombol kembali lebih kecil (Ghost button) */
            background-color: transparent;
            color: #ffffff;
            border: 1px solid rgba(255, 255, 255, 0.5);
        }

        .btn-kembali:hover {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: #ffffff;
        }

        .container.copyright {
            text-align: center;
            padding: 15px 0;
            margin-top: auto;
            font-size: 13px;
            color: rgba(255, 255, 255, 0.8);
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }

        /* Pesan Error Flashdata */
        .alert-error {
            background-color: rgba(255, 59, 48, 0.2);
            border-left: 3px solid #ff3b30;
            color: #fff;
            padding: 10px;
            border-radius: 4px;
            font-size: 13px;
            margin-bottom: 15px;
            text-align: center;
        }

        @media (max-width: 480px) {
            .background {
                width: 280px;
                height: 400px;
            }

            form {
                width: 90%;
                padding: 35px 25px;
                min-height: 480px;
            }

            form h3 {
                font-size: 24px;
            }

            input {
                height: 48px;
                font-size: 13px;
            }

            .button-group {
                flex-direction: column;
                gap: 10px;
            }

            /* Susun tombol ke bawah di HP */
            #submit-btn,
            .btn-kembali {
                width: 100%;
            }
        }
    </style>
</head>

<body>
    <div class="background">
        <div class="shape"></div>
        <div class="shape"></div>
    </div>
    <form id="loginForm" action="<?php echo base_url('login/radiologi/auth'); ?>" method="POST">
        <div class="logo-container">
            <img src="<?= base_url('assets_/assets/img/logo-mini2.png') ?>" alt="Logo">
        </div>
        <h3>Login Here</h3>

        <?php if ($this->session->flashdata('login_error')): ?>
            <div class="alert-error">
                <i class="fas fa-exclamation-circle mr-1"></i> <?php echo $this->session->flashdata('login_error'); ?>
            </div>
        <?php endif; ?>

        <div class="input-group">
            <i class="fas fa-user"></i>
            <input type="text" name="kd_user" id="kd_user" placeholder="Username" onkeyup="myFunction()" autocomplete="off" />
        </div>

        <div class="input-group">
            <i class="fas fa-lock"></i>
            <input type="password" name="password" id="password" placeholder="Password" onkeyup="myFunction()" />
        </div>

        <div class="captcha-container">
            <div id="captcha-code"></div>
            <button type="button" id="refresh-captcha" title="Perbarui Captcha"><i class="fas fa-sync-alt"></i></button>
        </div>

        <div class="input-group" style="margin-top: 10px;">
            <i class="fas fa-shield-alt"></i>
            <input type="text" id="captcha-input" placeholder="Masukkan Captcha di atas" autocomplete="off" style="text-transform: uppercase;" />
        </div>

        <div class="button-group">
            <button type="submit" id="submit-btn">Masuk</button>
            <button type="button" class="btn-kembali" onclick="window.history.back();">Kembali</button>
        </div>
    </form>

    <div class="container copyright text-center mt-1">
        <p>© <span>Copyright</span> <strong class="px-1 sitename">By IT Support RSU ANANDA Purwokerto</strong><br><span>All Rights Reserved 2024</span></p>
    </div>

    <script>
        function myFunction() {
            var userField = document.getElementById("kd_user");
            userField.value = userField.value.toUpperCase();
            var passwordField = document.getElementById("password");
            passwordField.value = passwordField.value.toUpperCase();
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function() {
            // --- 1. LOGIKA CAPTCHA ---
            function generateCaptcha() {
                let chars = "0123456789";
                let captchaLength = 5;
                let captchaText = "";
                for (let i = 0; i < captchaLength; i++) {
                    captchaText += chars[Math.floor(Math.random() * chars.length)];
                }
                $('#captcha-code').text(captchaText);
                $('#captcha-input').val('');
            }
            generateCaptcha();
            $('#refresh-captcha').click(generateCaptcha);

            // --- 2. LOGIKA RATE LIMITING (BRUTE FORCE PROTECTION) ---
            let failedAttempts = localStorage.getItem('loginRadiologiAttempts') ? parseInt(localStorage.getItem('loginRadiologiAttempts')) : 0;
            let lockUntil = localStorage.getItem('loginRadiologiLock') ? parseInt(localStorage.getItem('loginRadiologiLock')) : 0;

            function checkRateLimit() {
                let now = new Date().getTime();
                if (lockUntil > now) {
                    let remaining = Math.ceil((lockUntil - now) / 1000);
                    $('#submit-btn').prop('disabled', true).html(`<i class="fas fa-lock"></i> Terkunci (${remaining}s)`);
                    setTimeout(checkRateLimit, 1000);
                    return true;
                } else {
                    $('#submit-btn').prop('disabled', false).html('Masuk');
                    if (lockUntil !== 0 && lockUntil < now) {
                        localStorage.removeItem('loginRadiologiAttempts');
                        localStorage.removeItem('loginRadiologiLock');
                        failedAttempts = 0;
                        lockUntil = 0;
                    }
                    return false;
                }
            }
            checkRateLimit();

            // --- 3. AJAX SUBMIT DENGAN PERLINDUNGAN ERROR ---
            $('#loginForm').on('submit', function(e) {
                e.preventDefault();

                if (checkRateLimit()) return false;

                var kd_user = $('#kd_user').val();
                var password = $('#password').val();
                var captchaInput = $('#captcha-input').val().toUpperCase();
                var captchaCode = $('#captcha-code').text();

                // Validasi Kosong
                if (kd_user === "" || password === "" || captchaInput === "") {
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Silakan isi username, password, dan Captcha terlebih dahulu!',
                        confirmButtonColor: '#358640'
                    });
                    return false;
                }

                // Validasi Captcha
                if (captchaInput !== captchaCode) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Captcha Salah',
                        text: 'Kode Captcha tidak sesuai. Silakan coba lagi.',
                        confirmButtonColor: '#358640'
                    });
                    generateCaptcha();
                    $('#captcha-input').val(''); // Kosongkan inputan
                    return false;
                }

                // Validasi Akun yang Diblokir
                if (kd_user === "DIREKTUR" || kd_user === "MANAJER") {
                    Swal.fire({
                        icon: 'error',
                        title: 'Akses Ditolak',
                        text: 'Akun Direksi/Manajemen tidak dapat digunakan di portal ini.',
                        confirmButtonColor: '#358640'
                    });
                    generateCaptcha(); // Refresh captcha
                    $('#captcha-input').val('');
                    return false; // Langsung hentikan proses
                }

                // Enkripsi Password menggunakan Base64 (Sesuai permintaan)
                var encodedPassword = btoa(password);

                var formData = $(this).serializeArray();
                for (var i = 0; i < formData.length; i++) {
                    if (formData[i].name === 'password') {
                        formData[i].value = encodedPassword;
                    }
                }

                // Tampilkan loading
                let btn = $('#submit-btn');
                btn.html('<i class="fas fa-spinner fa-spin"></i> Memproses...').prop('disabled', true);

                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        btn.html('Masuk').prop('disabled', false);

                        try {
                            // Mencoba membaca respon dari server
                            var jsonResponse = JSON.parse(response);

                            if (jsonResponse.status === 'error') {
                                failedAttempts++;
                                localStorage.setItem('loginRadiologiAttempts', failedAttempts);

                                if (failedAttempts >= 3) {
                                    let lockTime = new Date().getTime() + 30000;
                                    localStorage.setItem('loginRadiologiLock', lockTime);
                                    checkRateLimit();
                                    Swal.fire({
                                        icon: 'warning',
                                        title: 'Terlalu Banyak Percobaan',
                                        text: 'Anda salah login 3 kali. Silakan tunggu 30 detik untuk keamanan.',
                                        confirmButtonColor: '#358640'
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Gagal',
                                        text: jsonResponse.message,
                                        confirmButtonColor: '#358640'
                                    });
                                }
                                generateCaptcha();
                                $('#captcha-input').val('');
                            } else {
                                // Sukses Login
                                localStorage.removeItem('loginRadiologiAttempts');
                                localStorage.removeItem('loginRadiologiLock');
                                window.location.href = jsonResponse.redirect;
                            }
                        } catch (e) {
                            // JIKA JSON GAGAL DIBACA (Mencegah Stuck)
                            console.error("Respons server tidak dapat diparse:", response);
                            Swal.fire({
                                icon: 'error',
                                title: 'Kesalahan Sistem',
                                text: 'Terjadi kendala saat membaca data dari server. Silakan hubungi IT.',
                                confirmButtonColor: '#358640'
                            });
                            generateCaptcha();
                            $('#captcha-input').val('');
                        }
                    },
                    error: function(xhr, status, error) {
                        btn.html('Masuk').prop('disabled', false);
                        Swal.fire({
                            icon: 'error',
                            title: 'Koneksi Gagal',
                            text: 'Gagal terhubung ke server. Periksa koneksi internet Anda.',
                            confirmButtonColor: '#358640'
                        });
                        generateCaptcha();
                        $('#captcha-input').val('');
                    }
                });
            });
        });
    </script>
</body>

</html>