<?php
// Authentication Functions

require_once __DIR__ . '/../config/database.php';

// Start session jika belum
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']) && isset($_SESSION['user_role']);
}

// Get current user data
function getCurrentUser() {
    if (!isLoggedIn()) {
        return null;
    }
    
    return [
        'id' => $_SESSION['user_id'],
        'username' => $_SESSION['username'],
        'nama' => $_SESSION['nama'],
        'role' => $_SESSION['user_role']
    ];
}

// Check user role
function hasRole($role) {
    return isLoggedIn() && $_SESSION['user_role'] === $role;
}

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

// Require admin role
function requireAdmin() {
    requireLogin();
    if (!hasRole('admin')) {
        header('Location: index.php');
        exit;
    }
}

// Require loket role
function requireLoket() {
    requireLogin();
    if (!hasRole('loket')) {
        header('Location: index.php');
        exit;
    }
}

// Login user
function loginUser($username, $password) {
    $sql = "SELECT id, username, password, nama, role FROM users WHERE username = ?";
    $result = query($sql, [$username], 's');
    
    if ($result->num_rows === 0) {
        return ['success' => false, 'message' => 'Username atau password salah'];
    }
    
    $user = $result->fetch_assoc();
    
    if (!password_verify($password, $user['password'])) {
        return ['success' => false, 'message' => 'Username atau password salah'];
    }
    
    // Set session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['nama'] = $user['nama'];
    $_SESSION['user_role'] = $user['role'];
    
    // Regenerate session ID untuk keamanan
    session_regenerate_id(true);
    
    return ['success' => true, 'role' => $user['role']];
}

// Logout user
function logoutUser() {
    session_unset();
    session_destroy();
    header('Location: login.php');
    exit;
}
?>
