<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

// Cek halaman saat ini
$current_page = basename($_SERVER['PHP_SELF']);
$current_path = $_SERVER['REQUEST_URI'];

// Daftar halaman yang boleh diakses tanpa login
$public_pages = ['login.php', 'index.php'];

// Jika belum login dan bukan halaman publik, redirect ke login
if (!isLoggedIn() && !in_array($current_page, $public_pages)) {
    redirect('login.php');
    exit;
}

// Jika sudah login
if (isLoggedIn()) {
    
    // Admin harus di folder admin/
    if (isAdmin()) {
        $is_in_admin_folder = (strpos($current_path, '/admin/') !== false) || ($current_page == 'index.php' && empty($_GET));
        
        if (!$is_in_admin_folder && $current_page != 'login.php') {
            // Jika admin mengakses halaman non-admin, redirect ke dashboard admin
            if (strpos($current_path, '/penguji/') !== false) {
                redirect('admin/dashboard.php');
                exit;
            }
        }
    }
    
    // Penguji harus di folder penguji/
    if (isPenguji()) {
        $is_in_penguji_folder = (strpos($current_path, '/penguji/') !== false) || ($current_page == 'index.php' && empty($_GET));
        
        if (!$is_in_penguji_folder && $current_page != 'login.php') {
            // Jika penguji mengakses halaman non-penguji, redirect ke dashboard penguji
            if (strpos($current_path, '/admin/') !== false) {
                redirect('penguji/dashboard_penguji.php');
                exit;
            }
        }
    }
    
    // Jika sudah login dan mengakses halaman login, redirect ke dashboard sesuai role
    if ($current_page == 'login.php') {
        if (isAdmin()) {
            redirect('admin/dashboard.php');
        } elseif (isPenguji()) {
            redirect('penguji/dashboard_penguji.php');
        }
        exit;
    }
}
?>