<?php
session_start();
include "config/conn.php";

/* ======================
   AMBIL INPUT
   ====================== */
$username = mysqli_real_escape_string($koneksi, $_POST['username']);
$password = $_POST['password'];
$pass_md5 = md5($password);

/* ======================
   LOGIN ADMIN / USER
   ====================== */
$sql = mysqli_query($koneksi, "
    SELECT * FROM user
    WHERE nama='$username' AND pass='$pass_md5'
");

if ($sql && mysqli_num_rows($sql) > 0) {

    $rs = mysqli_fetch_assoc($sql);

    $_SESSION['idu']   = $rs['idu'];
    $_SESSION['nama']  = $rs['nama'];
    $_SESSION['level'] = $rs['level'];
    $_SESSION['idk']   = "";
    $_SESSION['ortu']  = "";
    $_SESSION['id']    = $rs['id'];

    header("Location: media.php?module=home");
    exit;
}

/* ======================
   LOGIN SISWA
   ====================== */
$sql = mysqli_query($koneksi, "
    SELECT * FROM siswa
    WHERE nis='$username' AND pass='$pass_md5'
");

if ($sql && mysqli_num_rows($sql) > 0) {

    $rs = mysqli_fetch_assoc($sql);

    $_SESSION['idu']   = $rs['ids'];
    $_SESSION['nama']  = $rs['nama'];
    $_SESSION['level'] = "user";
    $_SESSION['ortu']  = $password;
    $_SESSION['idk']   = $rs['idk'];
    $_SESSION['id']    = "2";

    header("Location: media.php?module=home");
    exit;
}

/* ======================
   LOGIN GURU
   ====================== */
$sql = mysqli_query($koneksi, "
    SELECT * FROM guru
    WHERE nip='$username' AND pass='$pass_md5'
");

if ($sql && mysqli_num_rows($sql) > 0) {

    $rs = mysqli_fetch_assoc($sql);

    $_SESSION['idu']   = $rs['idg'];
    $_SESSION['nama']  = $rs['nama'];
    $_SESSION['idk']   = $rs['idk'];
    $_SESSION['level'] = "guru";
    $_SESSION['ortu']  = "";
    $_SESSION['id']    = "2";

    header("Location: media.php?module=home");
    exit;
}

/* ======================
   JIKA SEMUA GAGAL
   ====================== */
echo "<script>
    alert('Username atau Password salah!');
    window.location='login.php';
</script>";
exit;
