<?php
// Helper untuk mengatur akses admin
function checkAdminAccess($current_page = '')
{
    // Halaman yang memerlukan login
    $protected_pages = ['dashboard.php', 'profile.php'];

    // Cek apakah halaman saat ini memerlukan login
    $requires_login = false;
    foreach ($protected_pages as $page) {
        if (strpos($current_page, $page) !== false) {
            $requires_login = true;
            break;
        }
    }

    // Jika memerlukan login, cek session
    if ($requires_login) {
        if (!isset($_SESSION['admin_id']) && !isset($_SESSION['user_id'])) {
            header("Location: ../login/admin_login.php");
            exit;
        }

        // Jika login sebagai user biasa, cek apakah admin
        if (isset($_SESSION['user_id']) && !isset($_SESSION['admin_id'])) {
            global $conn;
            if (!$conn) {
                require_once '../config.php';
            }
            $stmt = $conn->prepare("SELECT peran FROM pengguna WHERE id = ?");
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();

            if (!$user || $user['peran'] !== 'admin') {
                header("Location: ../login/admin_login.php");
                exit;
            }

            // Set admin_id jika belum ada
            $_SESSION['admin_id'] = $_SESSION['user_id'];
        }
    }

    return true;
}

// Fungsi untuk mendapatkan info admin yang sedang login (untuk halaman yang memerlukan login)
function getAdminInfo()
{
    if (!isset($_SESSION['admin_id']) && !isset($_SESSION['user_id'])) {
        return null;
    }

    global $conn;
    if (!$conn) {
        require_once '../config.php';
    }
    $admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'];

    $stmt = $conn->prepare("SELECT * FROM pengguna WHERE id = ? AND peran = 'admin'");
    $stmt->bind_param("i", $admin_id);
    $stmt->execute();
    $result = $stmt->get_result();

    return $result->fetch_assoc();
}
