<?php
/**
 * Authentication & Session Management
 */

// Auto-start session jika belum dimulai
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Start session (wrapper untuk kompatibilitas)
 */
function startSession() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    return true;
}

/**
 * Login user
 */
function login($username, $password) {
    $db = db();
    $stmt = $db->prepare("SELECT u.*, b.code as branch_code FROM users u 
                          LEFT JOIN branches b ON u.branch_id = b.id 
                          WHERE u.username = ? AND u.status = 'active' LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id']    = $user['id'];
        $_SESSION['username']   = $user['username'];
        $_SESSION['name']       = $user['name'];
        $_SESSION['role']       = $user['role'];
        $_SESSION['branch_id']  = $user['branch_id'];
        $_SESSION['branch_code']= $user['branch_code'] ?? 'PUSAT';
        $_SESSION['logged_in']  = true;

        $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
        logActivity($user['id'], 'login', 'User logged in');
        return true;
    }
    return false;
}

/**
 * Logout user
 */
function logout() {
    if (isset($_SESSION['user_id'])) {
        logActivity($_SESSION['user_id'], 'logout', 'User logged out');
    }
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
}

/**
 * Cek apakah user sudah login
 */
function isLoggedIn() {
    return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}

/**
 * Require login (redirect jika belum login)
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: /login.php');
        exit;
    }
}

/**
 * Require role tertentu
 */
function requireRole($roles) {
    requireLogin();
    $roles = is_array($roles) ? $roles : [$roles];
    if (!in_array($_SESSION['role'] ?? '', $roles)) {
        http_response_code(403);
        die('Akses Ditolak: Anda tidak memiliki izin untuk halaman ini.');
    }
}

/**
 * Helper functions untuk session
 */
function currentUserId()  { return $_SESSION['user_id'] ?? null; }
function currentRole()    { return $_SESSION['role'] ?? null; }
function currentBranchId(){ return $_SESSION['branch_id'] ?? null; }
function isSuperAdmin()   { return currentRole() === 'super_admin'; }
function isBranchUser()   { return in_array(currentRole(), ['branch_admin','staff']); }