<?php
session_start();
require 'koneksi.php';

// Ambil data dari form
$user = $_POST['username'] ?? '';
$pass = $_POST['password'] ?? '';

// Validasi input kosong
if (empty($user) || empty($pass)) {
    echo "<script>alert('Username dan Password harus diisi'); window.location='index2.php';</script>";
    exit();
}

// Cek data petugas berdasarkan username
$stmt = $conn->prepare("SELECT * FROM petugas WHERE username = ?");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();

// Cek apakah username ditemukan
if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();

    // Verifikasi password
    if ($pass === $data['password']) {
        $_SESSION['id_petugas'] = $data['id_petugas'];
        $_SESSION['user']       = $user;
        $_SESSION['nama']       = $data['nama_petugas'];
        $_SESSION['level']      = $data['level'];

        // Redirect berdasarkan level
        if ($data['level'] === 'admin') {
            header('Location: admin/admin.php');
        } elseif ($data['level'] === 'petugas') {
            header('Location: petugas/petugas.php');
        } else {
            echo "<script>alert('Level tidak dikenali'); window.location='index2.php';</script>";
        }
        exit();
    } else {
        echo "<script>alert('Password salah'); window.location='index2.php';</script>";
    }
} else {
    echo "<script>alert('Username tidak ditemukan'); window.location='index2.php';</script>";
}

$stmt->close();
$conn->close();
?>
