<?php
                 if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

include 'koneksi.php';
                    if (isset($_SESSION['admin_id'])) {
                        // Jika admin sudah login, redirect ke halaman home.php
                        header("Location: dashboard");
                        exit();
                      }
                 
                      function getUserIpAddr()
                      {
                        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                          // IP dari internet share
                          return $_SERVER['HTTP_CLIENT_IP'];
                        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                          // IP dari proxy
                          return $_SERVER['HTTP_X_FORWARDED_FOR'];
                        } else {
                          // IP dari remote address
                          return $_SERVER['REMOTE_ADDR'];
                        }
                      }

                      if (!isset($_SESSION['login_attempts'])) {
                        $_SESSION['login_attempts'] = 0;
                      }

                      // Cek jika sudah ada 3 kesalahan login
                      if ($_SESSION['login_attempts'] >= 3) {
                        file_put_contents('log.txt', getUserIpAddr() . " - " . $_SERVER['HTTP_USER_AGENT'] . " - Blocked - " . date("Y-m-d H:i:s") . "\n", FILE_APPEND);
                        header("Location: https://www.google.com");
                        exit();
                      }

                    
                      
                      
                      // Jika admin sudah login, tampilkan halaman admin di sini
                      ?>



                      <?php
                    //   error_reporting(0);
                      if (isset($_POST['login'])) {
                        // Ambil data dari form
                        $username = $_POST['username'];
                        $password = $_POST['password'];

                        // Verifikasi captcha
                        if ($_POST['captcha'] != $_SESSION['captcha']) {
                          $error_message = "Kode captcha salah.";
                          $_SESSION['login_attempts']++;
                        } else {
                          // Koneksi ke database (gunakan kode koneksi.php yang telah Anda buat)
                          require_once('koneksi.php');

                          // Query untuk mencari admin dengan username yang sesuai
                          $query = "SELECT * FROM ngadmin WHERE username = :username";
                          $stmt = $pdo->prepare($query);
                          $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                          $stmt->execute();
                          $admin = $stmt->fetch();

                          // Periksa jika admin ditemukan
                          if ($admin && password_verify($password, $admin['password'])) {
                            // Login berhasil, simpan informasi admin dalam sesi
                            $_SESSION['admin_id'] = $admin['id'];
                            $_SESSION['admin_username'] = $admin['username'];
                            // Reset login attempts
                            $_SESSION['login_attempts'] = 0;

                            // Redirect ke halaman admin
                            header("Location: dashboard");
                            exit();
                          } else {
                            // Login gagal, tampilkan pesan kesalahan
                            $error_message = "Username atau password salah.";
                            $_SESSION['login_attempts']++;
                            file_put_contents('log.txt', getUserIpAddr() . " - " . $_SERVER['HTTP_USER_AGENT'] . " - Failed Login - " . date("Y-m-d H:i:s") . "\n", FILE_APPEND);
                          }
                        }
                      }
                      ?>
<!DOCTYPE html>
<html lang="en" dir="ltr" data-bs-theme="light" data-color-theme="Blue_Theme" data-layout="vertical">

<head>
  <!-- Required meta tags -->
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Favicon icon-->
  <link rel="shortcut icon" type="image/png" href="assets/images/logos/logo.png" />

  <!-- Core Css -->
  <link rel="stylesheet" href="assets/css/styles.css" />

  <title>Master Admin</title>
<style>
    .captcha-group {
      display: flex;
      justify-content: center;
      align-items: center;
      /* Menyelaraskan item di tengah secara vertikal */
    }
</style>
</head>

<body>
  <!-- Preloader -->
  <div class="preloader">
    <img src="assets/images/logos/logo.png" alt="loader" class="lds-ripple img-fluid" />
  </div>
  <div id="main-wrapper" class="auth-customizer-none">
    <div class="position-relative overflow-hidden radial-gradient min-vh-100 w-100">
      <div class="position-relative z-index-5">
        <div class="row">
          <div class="col-xl-5 col-xxl-4">
            <div class="authentication-login min-vh-100 bg-body row justify-content-center">
            <div class="col-12 d-flex justify-content-center">
                <a href="index" class="text-nowrap logo-img d-flex align-items-center gap-2 px-4 py-9 w-100 justify-content-center text-center">
                    <b class="logo-icon d-flex justify-content-center">
                        <img src="assets/images/logos/logo.png" alt="homepage" class="light-logo ps-2 img-fluid" style="width: 10vw; max-width: 1200px; min-width: 100px;" />
                    </b>
                    <span class="logo-text d-flex justify-content-center">
                        <img src="assets/images/logos/logo.png" alt="homepage" class="dark-logo ps-2 img-fluid" style="width: 10vw; max-width: 1200px; min-width: 100px;" />
                    </span>
                </a>
            </div>

              <div class="auth-max-width col-sm-8 col-md-6 col-xl-7 px-4">
                <h2 class="mb-1 fs-7 fw-bolder">Welcome to KOMANDAN</h2>
                <p class="mb-7">Dahsboard Admin</p>
                
                
                <form class="theme-form" method="POST">
    
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" name="username" id="username" placeholder="User Name" required>
                    </div>

                    <div class="mb-4">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" name="password" id="password" placeholder="Password" required>
                    </div>

                    <!-- CAPTCHA -->
                    <div class="mb-3">
                        <div id="captchaText" style="display: none;"><?php include('captcha.php'); ?></div>
                        <div class="captcha-group text-center">
                            <canvas id="captchaCanvas" width="200" height="50"></canvas>
                            <i class="fas fa-redo" onclick="reloadCaptcha()" style="cursor: pointer; margin-left: 10px;"></i>
                        </div>
                        <input type="text" class="form-control mt-2" name="captcha" placeholder="Masukkan kode di atas" required>
                    </div>

                    <!-- Menampilkan error jika ada -->
                    <?php if (isset($error_message)) { ?>
                        <label class="form-label text-danger text-center"><?php echo $error_message; ?></label>
                    <?php } ?>

                    <div class="mb-4">
                        <button type="submit" class="btn btn-primary w-100 py-8" name="login">Sign In</button>
                    </div>
                </form>

                <script>
                    window.onload = function() {
                        drawCaptcha();
                    };

                    function drawCaptcha() {
                        var canvas = document.getElementById('captchaCanvas');
                        var ctx = canvas.getContext('2d');
                        var text = document.getElementById('captchaText').innerText;

                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        ctx.font = '24px Courier New';
                        ctx.fillStyle = 'black';
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var x = 50;
                        for (var i = 0; i < text.length; i++) {
                            var y = 25 + Math.random() * 10 - 5;
                            var angle = Math.random() * 0.5 - 0.25;
                            ctx.save();
                            ctx.translate(x, y);
                            ctx.rotate(angle);
                            ctx.fillText(text[i], 0, 0);
                            ctx.restore();
                            x += 30;
                        }
                    }

                    function reloadCaptcha() {
                        fetch('captcha').then(response => response.text()).then(text => {
                            document.getElementById('captchaText').innerText = text;
                            drawCaptcha();
                        });
                    }
                </script>

              </div>
            </div>
          </div>
          <div class="col-xl-7 col-xxl-8 d-none d-xl-block">
            <div class="d-none d-xl-flex align-items-center justify-content-center h-100">
              <img src="assets/images/backgrounds/user-login.png" alt="" class="img-fluid">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="dark-transparent sidebartoggler"></div>
  <!-- Import Js Files -->
  <script src="assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="assets/libs/simplebar/dist/simplebar.min.js"></script>
  <script src="assets/js/theme/app.init.js"></script>
  <script src="assets/js/theme/theme.js"></script>
  <script src="assets/js/theme/app.min.js"></script>
  <script src="assets/js/theme/feather.min.js"></script>

  <!-- solar icons -->
  <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.8/dist/iconify-icon.min.js"></script>

</body>

</html>