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

$username = $_POST['username'];
$password = $_POST['password'];

// Ambil user dengan status aktif
$sql = "SELECT * FROM users WHERE username = ? AND status = 1 LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();

    if (password_verify($password, $user['password'])) {
        // Simpan data ke session
        $_SESSION['id_user']   = $user['id_user'];
        $_SESSION['username']  = $user['username'];
        $_SESSION['name']      = $user['name'] ?? '';
        $_SESSION['jabatan']   = $user['jabatan']; // Simpan jabatan
        $_SESSION['role']      = strtolower($user['role']); // admin / user

        // Redirect ke dashboard umum
        echo "<script>
            alert('Selamat Datang Kembali {$user['name']}');
            window.location.href = '../index.php';
        </script>";
        exit;

    } else {
        echo "<script>alert('Password salah'); window.location='login.php';</script>";
    }
} else {
    echo "<script>alert('User tidak ditemukan atau akun nonaktif'); window.location='login.php';</script>";
}
?>
