<?php
session_start();
require_once '../db_config.php';

class AdminAuth {
    private $db;
    
    public function __construct() {
        $this->db = getDBConnection();
    }
    
    // Role permissions configuration
    private static $rolePermissions = [
        'super_admin' => [
            'dashboard' => ['view'],
            'registrations' => ['view', 'edit', 'delete', 'export'],
            'payments' => ['view', 'edit', 'export'],
            'delegates' => ['view', 'edit', 'export'],
            'settings' => ['view', 'edit'],
            'users' => ['view', 'create', 'edit', 'delete'],
            'activity_log' => ['view']
        ],
        'manager' => [
            'dashboard' => ['view'],
            'registrations' => ['view', 'edit', 'delete', 'export'],
            'payments' => ['view', 'edit', 'export'],
            'delegates' => ['view', 'edit', 'export'],
            'activity_log' => ['view']
        ],
        'viewer' => [
            'dashboard' => ['view'],
            'registrations' => ['view'],
            'payments' => ['view'],
            'delegates' => ['view']
        ]
    ];
    
    // Check if user is logged in
    public function isLoggedIn() {
        return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
    }
    
    // Get current user info
    public function getCurrentUser() {
        if (!$this->isLoggedIn()) {
            return null;
        }
        return $_SESSION['admin_user'] ?? null;
    }
    
    // Get current user role
    public function getCurrentUserRole() {
        $user = $this->getCurrentUser();
        return $user['role'] ?? null;
    }
    
    // Check if current user has permission for specific action
    public function hasPermission($module, $action = 'view') {
        $role = $this->getCurrentUserRole();
        if (!$role) return false;
        
        $permissions = self::$rolePermissions[$role] ?? [];
        $modulePermissions = $permissions[$module] ?? [];
        
        return in_array($action, $modulePermissions);
    }
    
    // Require login for admin pages
    public function requireLogin() {
        if (!$this->isLoggedIn()) {
            header('Location: login.php');
            exit;
        }
    }
    
    // Require specific permission
    public function requirePermission($module, $action = 'view') {
        $this->requireLogin();
        
        if (!$this->hasPermission($module, $action)) {
            $this->accessDenied();
        }
    }
    
    // Access denied handler
    private function accessDenied() {
        http_response_code(403);
        include 'access_denied.php';
        exit;
    }
    
    // Handle login
    public function handleLogin($username, $password) {
        try {
            $stmt = $this->db->prepare("SELECT id, username, password_hash, full_name, email, role, is_active FROM admin_users WHERE username = ? AND is_active = 1");
            $stmt->execute([$username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && password_verify($password, $user['password_hash'])) {
                // Update last login
                $updateStmt = $this->db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
                $updateStmt->execute([$user['id']]);
                
                // Set session
                $_SESSION['admin_logged_in'] = true;
                $_SESSION['admin_user'] = [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'full_name' => $user['full_name'],
                    'email' => $user['email'],
                    'role' => $user['role']
                ];
                $_SESSION['login_time'] = time();
                
                // Log activity
                $this->logActivity($user['id'], 'login', null, null, 'User logged in');
                
                return true;
            }
            
            return false;
        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            return false;
        }
    }
    
    // Handle logout
    public function handleLogout() {
        if ($this->isLoggedIn()) {
            $user = $this->getCurrentUser();
            if ($user) {
                $this->logActivity($user['id'], 'logout', null, null, 'User logged out');
            }
        }
        
        session_destroy();
        header('Location: login.php');
        exit;
    }
    
    // Log admin activity
    public function logActivity($userId, $action, $targetType = null, $targetId = null, $details = null) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO admin_activity_log (admin_user_id, action, target_type, target_id, details, ip_address, user_agent) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $userId,
                $action,
                $targetType,
                $targetId,
                $details,
                $_SERVER['REMOTE_ADDR'] ?? null,
                $_SERVER['HTTP_USER_AGENT'] ?? null
            ]);
        } catch (Exception $e) {
            error_log("Activity log error: " . $e->getMessage());
        }
    }
    
    // Check for logout request
    public function checkLogoutRequest() {
        if (isset($_GET['logout'])) {
            $this->handleLogout();
        }
    }
    
    // Auto-logout after inactivity
    public function checkSessionTimeout($timeoutSeconds = 7200) { // 2 hours default
        if ($this->isLoggedIn() && isset($_SESSION['login_time'])) {
            if (time() - $_SESSION['login_time'] > $timeoutSeconds) {
                $this->handleLogout();
            }
        }
    }
    
    // Get all roles for dropdown
    public static function getAllRoles() {
        return [
            'super_admin' => 'Super Administrator',
            'manager' => 'Manager',
            'viewer' => 'Viewer'
        ];
    }
    
    // Get role display name
    public static function getRoleDisplayName($role) {
        $roles = self::getAllRoles();
        return $roles[$role] ?? $role;
    }
    
    // Check if current user can manage other users
    public function canManageUsers() {
        return $this->hasPermission('users', 'view');
    }
    
    // Check if current user can access settings
    public function canAccessSettings() {
        return $this->hasPermission('settings', 'view');
    }
}

// Initialize auth system
$auth = new AdminAuth();
$auth->checkLogoutRequest();
$auth->checkSessionTimeout();

// Helper functions for backward compatibility and ease of use
function isLoggedIn() {
    global $auth;
    return $auth->isLoggedIn();
}

function requireLogin() {
    global $auth;
    $auth->requireLogin();
}

function requirePermission($module, $action = 'view') {
    global $auth;
    $auth->requirePermission($module, $action);
}

function hasPermission($module, $action = 'view') {
    global $auth;
    return $auth->hasPermission($module, $action);
}

function getCurrentUser() {
    global $auth;
    return $auth->getCurrentUser();
}

function getCurrentUserRole() {
    global $auth;
    return $auth->getCurrentUserRole();
}

function logActivity($action, $targetType = null, $targetId = null, $details = null) {
    global $auth;
    $user = $auth->getCurrentUser();
    if ($user) {
        $auth->logActivity($user['id'], $action, $targetType, $targetId, $details);
    }
}
?>
