<?php
session_start();
include('../../config/koneksi.php');

$username_user = htmlspecialchars($_POST['username_user']);
$password_user_raw = htmlspecialchars($_POST['password_user']);
$password_user = md5($password_user_raw);

// Validasi input kosong
if (empty($username_user) && empty($password_user_raw)) {
  $_SESSION['login_error'] = "Username dan password harus diisi";
  header('Location: ../login');
  exit;
} elseif (empty($username_user)) {
  $_SESSION['login_error'] = "Silakan masukkan username";
  header('Location: ../login');
  exit;
} elseif (empty($password_user_raw)) {
  $_SESSION['login_error'] = "Silakan masukkan password";
  header('Location: ../login');
  exit;
}

// Cek apakah username ada
$query = "SELECT * FROM user WHERE username_user = '$username_user'";
$hasil = mysqli_query($db, $query);
$data_user = mysqli_fetch_assoc($hasil);

if ($data_user) {
  // Username ditemukan
  if ($data_user['password_user'] === $password_user) {
    // Login berhasil
    $_SESSION['user'] = $data_user;
    header('Location: ../dasbor');
    exit;
  } else {
    // Password salah
    $_SESSION['login_error'] = "Password salah";
    header('Location: ../login');
    exit;
  }
} else {
  // Username tidak ditemukan
  $query_check = "SELECT * FROM user WHERE password_user = '$password_user'";
  $result_check = mysqli_query($db, $query_check);
  $user_by_password = mysqli_fetch_assoc($result_check);

  if ($user_by_password) {
    $_SESSION['login_error'] = "Username salah";
  } else {
    $_SESSION['login_error'] = "Username dan password tidak terdaftar";
  }

  header('Location: ../login');
  exit;
}
