<?php
// File: config/auth.php
require_once 'database.php';
session_start();

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function isAdmin() {
    return isset($_SESSION['user_level']) && $_SESSION['user_level'] === 'admin';
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: index.php?error=unauthorized');
        exit;
    }
}

function login($username, $password) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT id, username, password, nama_lengkap, level, is_active FROM belloto_users WHERE username = ? AND is_active = 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        if (password_verify($password, $row['password'])) {
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['username'] = $row['username'];
            $_SESSION['nama_lengkap'] = $row['nama_lengkap'];
            $_SESSION['user_level'] = $row['level'];
            return true;
        }
    }
    return false;
}

function logout() {
    session_destroy();
    header('Location: index.php');
    exit;
}
?>