<?php
// auth.php - proteksi portal dengan 1 password bersama

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Password portal (plain) = "SantiIGD"
 * Di-hash pakai bcrypt supaya aman:
 * $2y$12$ug/uMoAvf/Wb0v0foiTR9uh2SAmJMPE4TI86Ar4sNDmOphwfnjBxK
 */
const PORTAL_PASSWORD_HASH = '$2y$12$ug/uMoAvf/Wb0v0foiTR9uh2SAmJMPE4TI86Ar4sNDmOphwfnjBxK';

function portal_logged_in(): bool {
    return !empty($_SESSION['portal_logged_in']);
}

function portal_login(string $password): bool {
    if (password_verify($password, PORTAL_PASSWORD_HASH)) {
        $_SESSION['portal_logged_in'] = true;
        // ini yg dipakai index.php untuk "Hai, ..."
        $_SESSION['user'] = 'Staf Keperawatan';
        return true;
    }
    return false;
}

function portal_logout(): void {
    $_SESSION = [];
    if (session_id()) {
        session_destroy();
    }
}

/**
 * Dipanggil di atas setiap halaman yg mau dikunci:
 *   require 'auth.php';
 *   portal_require_login();
 */
function portal_require_login(): void {
    // handle logout jika ada ?logout=1
    if (isset($_GET['logout'])) {
        portal_logout();
        header('Location: /login.php');
        exit;
    }

    if (!portal_logged_in()) {
        $next = $_SERVER['REQUEST_URI'] ?? '/';
        header('Location: /login.php?next=' . urlencode($next));
        exit;
    }
}
