<?php
include 'db.php'; // Koneksi dan memulai session
include 'auth_check_util.php'; // Include utilitas role

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit();
}

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

// Prepared statement untuk menghindari SQL Injection
$stmt = $conn->prepare("SELECT id, username, password, role FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if ($user) {
    // Verifikasi password
    // Asumsi: password sudah di-hash saat disimpan
    if (password_verify($password, $user['password'])) {
        
        // Login berhasil, simpan data ke session
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['role'] = $user['role'];

        // Arahkan sesuai role ke folder masing-masing
        if ($user['role'] === 'superadmin') {
            header("Location: superadmin/superadmin_dashboard.php");
        } elseif ($user['role'] === 'employer') {
            header("Location: employer/employer_dashboard.php");
        } elseif ($user['role'] === 'member') {
            header("Location: member/member_dashboard.php");
        } else {
            // Role tidak dikenal, arahkan ke login lagi
            header("Location: login.php?error=unknown_role");
        }
        exit();
    } else {
        header("Location: login.php?error=password_salah");
        exit();
    }
} else {
    header("Location: login.php?error=username_salah");
    exit();
}
?>