<?php
include "../config/koneksi.php";

// 1. Fungsi Mengambil IP Address Asli User
function get_client_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

// Sanitasi Input
function anti_injection($data){
  $filter = stripslashes(strip_tags(htmlspecialchars($data, ENT_QUOTES)));
  return $filter;
}

$username = anti_injection($_POST['username']);
$password = anti_injection(md5($_POST['password']));

$injeksi_username = mysqli_real_escape_string($konek, $username);
$injeksi_password = mysqli_real_escape_string($konek, $password);

// Tangkap IP Address dan Perangkat User
$ip_address = get_client_ip();
$user_agent = mysqli_real_escape_string($konek, $_SERVER['HTTP_USER_AGENT']);

// Validasi Alfanumerik
if (!ctype_alnum($injeksi_username) OR !ctype_alnum($injeksi_password)){
    // Catat percobaan login ilegal ke history
    $log_query = "INSERT INTO history_login (username, ip_address, user_agent, status) 
                  VALUES ('$username', '$ip_address', '$user_agent', 'Gagal')";
    mysqli_query($konek, $log_query);

    echo "Sekarang loginnya tidak bisa di injeksi lho.";
}
else{
    $query  = "SELECT * FROM users WHERE username='$username' AND password='$password' AND blokir='N'";
    $login  = mysqli_query($konek, $query);
    $ketemu = mysqli_num_rows($login);
    $r      = mysqli_fetch_array($login);

    // Apabila Username dan Password Benar
    if ($ketemu > 0){
        session_start();

        $_SESSION['namauser']    = $r['username'];
        $_SESSION['passuser']    = $r['password'];
        $_SESSION['namalengkap'] = $r['nama_lengkap'];
        $_SESSION['leveluser']   = $r['level'];
        
        $sid_lama = session_id();
        session_regenerate_id();
        $sid_baru = session_id();
        mysqli_query($konek, "UPDATE users SET id_session='$sid_baru' WHERE username='$username'");

        // 2. CATAT HISTORY LOGIN (BERHASIL)
        $log_query = "INSERT INTO history_login (username, ip_address, user_agent, status) 
                      VALUES ('$username', '$ip_address', '$user_agent', 'Berhasil')";
        mysqli_query($konek, $log_query);

        header("location:media.php?module=beranda");
    }
    else{
        // 3. CATAT HISTORY LOGIN (GAGAL)
        $log_query = "INSERT INTO history_login (username, ip_address, user_agent, status) 
                      VALUES ('$username', '$ip_address', '$user_agent', 'Gagal')";
        mysqli_query($konek, $log_query);

        echo "<link href=\"css/style_login.css\" rel=\"stylesheet\" type=\"text/css\" />";
        echo "<div id=\"login\"><h1 class=\"fail\">Login Gagal! Username & Password salah.</h1>";
        echo "<p class=\"fail\"><a href=\"index.php\">Ulangi Lagi</a></p></div>";  
    }
}
?>