<?php
/**
 * Enterprise HRM ERP System - User Access Role
 * Assign roles to users
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can assign roles to users. Your role: ' . ($roleCode ?: 'Unknown');
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'User Access Role';
$currentModule = 'settings';

$errors = [];
$success = false;

// Handle role assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_role'])) {
    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $roleId = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
    
    if ($userId <= 0 || $roleId <= 0) {
        $errors[] = 'Please select both user and role.';
    } else {
        try {
            $db = getDB();
            
            // Check if user exists
            $stmt = $db->prepare("SELECT user_id, username, full_name FROM users WHERE user_id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            
            if (!$user) {
                $errors[] = 'User not found.';
            } else {
                // Update user role
                $stmt = $db->prepare("UPDATE users SET role_id = ? WHERE user_id = ?");
                $stmt->execute([$roleId, $userId]);
                
                // Update session if current user
                if ($userId == getCurrentUserId()) {
                    $stmt = $db->prepare("SELECT role_code, role_name FROM roles WHERE role_id = ?");
                    $stmt->execute([$roleId]);
                    $role = $stmt->fetch();
                    if ($role) {
                        $_SESSION['role_id'] = $roleId;
                        $_SESSION['role_code'] = $role['role_code'];
                        $_SESSION['role_name'] = $role['role_name'];
                    }
                }
                
                logAudit('UPDATE', 'users', $userId, ['action' => 'role_assigned', 'role_id' => $roleId]);
                $success = true;
            }
        } catch (Exception $e) {
            error_log("Error assigning role: " . $e->getMessage());
            $errors[] = 'An error occurred while assigning role.';
        }
    }
}

// Get all users
try {
    $db = getDB();
    
    // Data isolation for users
    if (isSuperAdmin()) {
        $stmt = $db->prepare("
            SELECT u.*, r.role_name, r.role_code
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            ORDER BY u.full_name
        ");
        $stmt->execute();
    } else {
        $accessibleSiteIds = getAccessibleSiteIds();
        if (!empty($accessibleSiteIds)) {
            $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
            $stmt = $db->prepare("
                SELECT DISTINCT u.*, r.role_name, r.role_code
                FROM users u
                INNER JOIN roles r ON u.role_id = r.role_id
                INNER JOIN user_sites us ON u.user_id = us.user_id
                WHERE us.site_id IN ($placeholders)
                ORDER BY u.full_name
            ");
            $stmt->execute($accessibleSiteIds);
        } else {
            $stmt = $db->prepare("SELECT 1 WHERE 1=0");
            $stmt->execute();
        }
    }
    $users = $stmt->fetchAll();
    
    // Get all roles
    $stmt = $db->prepare("SELECT role_id, role_name, role_code FROM roles ORDER BY role_name");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $users = [];
    $roles = [];
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">User Access Role</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
            <a href="<?php echo BASE_URL; ?>/admin/users.php" class="btn btn-secondary">User Management</a>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Role assigned successfully.
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <!-- Quick Assign Form -->
    <div style="margin-top: 20px; padding: 20px; background: #f9fafb; border-radius: 8px; margin-bottom: 30px;">
        <h3 style="margin-bottom: 15px;">Quick Assign Role</h3>
        <form method="POST" style="display: grid; grid-template-columns: 2fr 2fr 1fr; gap: 15px; align-items: end;">
            <div class="form-group">
                <label class="form-label" for="user_id">Select User *</label>
                <select id="user_id" name="user_id" class="form-control" required>
                    <option value="">-- Select User --</option>
                    <?php foreach ($users as $user): ?>
                    <option value="<?php echo $user['user_id']; ?>">
                        <?php echo htmlspecialchars($user['full_name'] . ' (' . $user['username'] . ')'); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="role_id">Select Role *</label>
                <select id="role_id" name="role_id" class="form-control" required>
                    <option value="">-- Select Role --</option>
                    <?php foreach ($roles as $role): ?>
                    <option value="<?php echo $role['role_id']; ?>">
                        <?php echo htmlspecialchars($role['role_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <button type="submit" name="assign_role" class="btn btn-primary" style="width: 100%;">Assign Role</button>
            </div>
        </form>
    </div>
    
    <!-- Users List with Current Roles -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Users and Their Roles</h3>
        
        <?php if (empty($users)): ?>
        <div class="table-empty">
            <div class="table-empty-icon">👥</div>
            <div class="table-empty-message">No users found</div>
        </div>
        <?php else: ?>
        <div style="overflow-x: auto;">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Full Name</th>
                        <th>Email</th>
                        <th>Current Role</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($user['username']); ?></strong></td>
                        <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                        <td>
                            <span class="status-badge status-active">
                                <?php echo htmlspecialchars($user['role_name']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="status-badge status-<?php echo $user['user_status']; ?>">
                                <?php echo ucfirst($user['user_status']); ?>
                            </span>
                        </td>
                        <td class="table-actions-cell">
                            <a href="<?php echo BASE_URL; ?>/admin/users_edit.php?id=<?php echo $user['user_id']; ?>" 
                               class="btn btn-sm btn-primary">Change Role</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
