<?php
/**
 * Enterprise HRM ERP System - Assign Role to Employee
 * HR Admin can assign roles to employees
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();
requirePermission('EMPLOYEE_ROLE_ASSIGN');

$pageTitle = 'Assign Role to Employee';
$currentModule = 'employee';

$siteId = getCurrentSiteId();
$errors = [];
$success = false;

// Pre-select employee if provided in URL
$preselectedEmployeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

// Handle role assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_role'])) {
    $employeeId = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
    $roleId = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
    
    if ($employeeId <= 0 || $roleId <= 0) {
        $errors[] = 'Please select both employee and role.';
    } else {
        try {
            $db = getDB();
            $userId = getCurrentUserId();
            
            // Check if employee exists and is in accessible site
            $accessibleSiteIds = getAccessibleSiteIds();
            if (empty($accessibleSiteIds)) {
                $errors[] = 'You do not have access to any sites.';
            } else {
                $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
                $stmt = $db->prepare("
                    SELECT employee_id, employee_code, first_name, last_name, site_id
                    FROM employees 
                    WHERE employee_id = ? AND site_id IN ($placeholders)
                ");
                $stmt->execute(array_merge([$employeeId], $accessibleSiteIds));
                $employee = $stmt->fetch();
                
                if (!$employee) {
                    $errors[] = 'Employee not found or you do not have access to this employee.';
                } else {
                    // Check if employee has a user account
                    $stmt = $db->prepare("SELECT user_id FROM users WHERE employee_id = ?");
                    $stmt->execute([$employeeId]);
                    $user = $stmt->fetch();
                    
                    if ($user) {
                        // Update existing user's role
                        $stmt = $db->prepare("UPDATE users SET role_id = ? WHERE user_id = ?");
                        $stmt->execute([$roleId, $user['user_id']]);
                        
                        logAudit('UPDATE', 'users', $user['user_id'], ['action' => 'role_assigned_to_employee', 'employee_id' => $employeeId, 'role_id' => $roleId]);
                    } else {
                        // Create user account for employee if email exists
                        if (!empty($employee['email'])) {
                            // Check if email already exists in users table
                            $stmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
                            $stmt->execute([$employee['email']]);
                            $existingUser = $stmt->fetch();
                            
                            if ($existingUser) {
                                // Link existing user to employee and update role
                                $stmt = $db->prepare("UPDATE users SET employee_id = ?, role_id = ? WHERE user_id = ?");
                                $stmt->execute([$employeeId, $roleId, $existingUser['user_id']]);
                                
                                logAudit('UPDATE', 'users', $existingUser['user_id'], ['action' => 'employee_linked_and_role_assigned', 'employee_id' => $employeeId, 'role_id' => $roleId]);
                            } else {
                                // Create new user account
                                $username = strtolower(str_replace(' ', '', $employee['first_name'] . $employee['last_name'])) . '_' . $employee['employee_code'];
                                $defaultPassword = hashPassword('password123'); // Default password, should be changed on first login
                                
                                $stmt = $db->prepare("
                                    INSERT INTO users (site_id, username, email, password_hash, full_name, role_id, employee_id, user_status)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, 'active')
                                ");
                                $fullName = trim($employee['first_name'] . ' ' . $employee['last_name']);
                                $stmt->execute([
                                    $employee['site_id'],
                                    $username,
                                    $employee['email'],
                                    $defaultPassword,
                                    $fullName,
                                    $roleId,
                                    $employeeId
                                ]);
                                
                                $newUserId = $db->lastInsertId();
                                
                                // Add to user_sites
                                $stmt = $db->prepare("INSERT INTO user_sites (user_id, site_id, is_primary, assigned_by) VALUES (?, ?, 1, ?)");
                                $stmt->execute([$newUserId, $employee['site_id'], $userId]);
                                
                                logAudit('CREATE', 'users', $newUserId, ['action' => 'user_created_for_employee', 'employee_id' => $employeeId, 'role_id' => $roleId]);
                            }
                        } else {
                            $errors[] = 'Employee does not have an email address. Please add email to employee record first.';
                        }
                    }
                    
                    if (empty($errors)) {
                        $success = true;
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error assigning role: " . $e->getMessage());
            $errors[] = 'An error occurred while assigning role.';
        }
    }
}

// Get employees
try {
    $db = getDB();
    $accessibleSiteIds = getAccessibleSiteIds();
    
    if (empty($accessibleSiteIds)) {
        $employees = [];
    } else {
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        $stmt = $db->prepare("
            SELECT e.employee_id, e.employee_code, e.first_name, e.last_name, e.email,
                   e.site_id, u.user_id, r.role_name, r.role_code
            FROM employees e
            LEFT JOIN users u ON e.employee_id = u.employee_id
            LEFT JOIN roles r ON u.role_id = r.role_id
            WHERE e.site_id IN ($placeholders) AND e.employment_status = 'active'
            ORDER BY e.employee_code
        ");
        $stmt->execute($accessibleSiteIds);
        $employees = $stmt->fetchAll();
    }
    
    // Get all roles (excluding super_admin for HR)
    if (isSuperAdmin()) {
        $stmt = $db->prepare("SELECT role_id, role_name, role_code FROM roles ORDER BY role_name");
    } else {
        $stmt = $db->prepare("SELECT role_id, role_name, role_code FROM roles WHERE role_code != 'SUPER_ADMIN' ORDER BY role_name");
    }
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $employees = [];
    $roles = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Assign Role to Employee</h2>
        <a href="<?php echo BASE_URL; ?>/modules/employee/list.php" class="btn btn-secondary">Back to Employees</a>
    </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; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="employee_id">Employee *</label>
                <select id="employee_id" name="employee_id" class="form-control" required>
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_id']; ?>"
                            <?php echo ($preselectedEmployeeId == $emp['employee_id'] || ($formData['employee_id'] ?? 0) == $emp['employee_id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . trim($emp['first_name'] . ' ' . $emp['last_name'])); ?>
                        <?php if ($emp['role_name']): ?>
                            (Current: <?php echo htmlspecialchars($emp['role_name']); ?>)
                        <?php endif; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="role_id">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']); ?> (<?php echo htmlspecialchars($role['role_code']); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/modules/employee/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" name="assign_role" class="btn btn-primary">Assign Role</button>
        </div>
    </form>
</div>

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

