<?php
include "lib/conn.php";
include "lib/all_function.php";
session_start();
header('Content-Type: application/json'); // agar respons berupa JSON

$response = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($username === '' || $password === '') {
        $response = ['status' => 'warning', 'message' => 'Username atau password tidak boleh kosong!'];
        echo json_encode($response);
        exit;
    }

    $username = mysqli_real_escape_string($conn, $username);
    $pass = md5(mysqli_real_escape_string($conn, $password));

    $query = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$pass' LIMIT 1");

    if (!$query) {
        $response = ['status' => 'error', 'message' => 'Terjadi kesalahan query database!'];
        echo json_encode($response);
        exit;
    }

    if (mysqli_num_rows($query) === 1) {
        $a = mysqli_fetch_assoc($query);

        $_SESSION['login_id']   = $a['username'];
        $_SESSION['id_user']    = $a['user_id'];
        $_SESSION['level']      = $a['level'];
        $_SESSION['login_user'] = $a['user_id'];

        // Catat log login
        $info = "IP :" . get_client_ip() . "<br> Browser : " . get_client_browser() . "<br> Sistem Operasi : " . $_SERVER['HTTP_USER_AGENT'];
        mysqli_query($conn, "UPDATE users SET last_login = NOW() WHERE user_id = '{$a['user_id']}'");
        mysqli_query($conn, "INSERT INTO tb_log(`kode`, `table`, `deskripsi`, `aksi`, `petugas`, `info`) 
                             VALUES ('','users','Pengguna melakukan login','Login','{$a['user_id']}','$info')");

        $response = ['status' => 'success', 'message' => "Selamat datang, {$a['username']}!"];
    } else {
        $response = ['status' => 'error', 'message' => 'Username atau password salah!'];
    }
} else {
    $response = ['status' => 'error', 'message' => 'Akses tidak valid!'];
}

echo json_encode($response);
exit;
?>
