<?php
/**
 * Enterprise HRM ERP System - Create User
 */

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

$pageTitle = 'Create User';
$currentModule = 'settings';

$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'username' => sanitize($_POST['username'] ?? ''),
        'email' => sanitize($_POST['email'] ?? ''),
        'password' => $_POST['password'] ?? '',
        'password_confirm' => $_POST['password_confirm'] ?? '',
        'full_name' => sanitize($_POST['full_name'] ?? ''),
        'phone' => sanitize($_POST['phone'] ?? ''),
        'role_id' => isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0,
        'site_id' => isset($_POST['site_id']) ? (int)$_POST['site_id'] : 0,
        'employee_id' => isset($_POST['employee_id']) && $_POST['employee_id'] !== '' ? (int)$_POST['employee_id'] : null,
        'user_status' => sanitize($_POST['user_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['username'])) {
        $errors[] = 'Username is required.';
    } elseif (strlen($formData['username']) < 3) {
        $errors[] = 'Username must be at least 3 characters.';
    }
    
    if (empty($formData['email'])) {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format.';
    }
    
    if (empty($formData['password'])) {
        $errors[] = 'Password is required.';
    } elseif (strlen($formData['password']) < 8) {
        $errors[] = 'Password must be at least 8 characters.';
    } elseif ($formData['password'] !== $formData['password_confirm']) {
        $errors[] = 'Passwords do not match.';
    }
    
    if (empty($formData['full_name'])) {
        $errors[] = 'Full name is required.';
    }
    
    if ($formData['role_id'] <= 0) {
        $errors[] = 'Please select a role.';
    }
    
    if ($formData['site_id'] <= 0) {
        $errors[] = 'Please select a site.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if username already exists
            $stmt = $db->prepare("SELECT user_id FROM users WHERE username = ?");
            $stmt->execute([$formData['username']]);
            if ($stmt->fetch()) {
                $errors[] = 'Username already exists.';
                $db->rollBack();
            } else {
                // Check if email already exists
                $stmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
                $stmt->execute([$formData['email']]);
                if ($stmt->fetch()) {
                    $errors[] = 'Email already exists.';
                    $db->rollBack();
                } else {
                    // Hash password
                    $passwordHash = hashPassword($formData['password']);
                    
                    // Check if employee_id column exists
                    $stmt = $db->query("SHOW COLUMNS FROM users LIKE 'employee_id'");
                    $employeeIdColumnExists = $stmt->rowCount() > 0;
                    
                    // Insert user
                    if ($employeeIdColumnExists && $formData['employee_id']) {
                        $stmt = $db->prepare("
                            INSERT INTO users (
                                username, email, password_hash, full_name, phone, 
                                role_id, site_id, employee_id, user_status
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $formData['username'],
                            $formData['email'],
                            $passwordHash,
                            $formData['full_name'],
                            $formData['phone'] ?: null,
                            $formData['role_id'],
                            $formData['site_id'],
                            $formData['employee_id'],
                            $formData['user_status']
                        ]);
                    } else {
                        $stmt = $db->prepare("
                            INSERT INTO users (
                                username, email, password_hash, full_name, phone, 
                                role_id, site_id, user_status
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $formData['username'],
                            $formData['email'],
                            $passwordHash,
                            $formData['full_name'],
                            $formData['phone'] ?: null,
                            $formData['role_id'],
                            $formData['site_id'],
                            $formData['user_status']
                        ]);
                    }
                    
                    $userId = $db->lastInsertId();
                    
                    // Add user to user_sites (set as primary)
                    $stmt = $db->prepare("
                        INSERT INTO user_sites (user_id, site_id, is_primary, assigned_by)
                        VALUES (?, ?, 1, ?)
                    ");
                    $stmt->execute([$userId, $formData['site_id'], getCurrentUserId()]);
                    
                    $db->commit();
                    
                    // Log audit
                    logAudit('CREATE', 'users', $userId);
                    
                    redirect(BASE_URL . '/admin/users.php', 'User created successfully.');
                }
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating user: " . $e->getMessage());
            $errors[] = 'An error occurred while creating user. Please try again.';
        }
    }
}

// Get roles, sites, and employees
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT role_id, role_name, role_code FROM roles ORDER BY role_name");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
    $stmt = $db->prepare("SELECT site_id, site_name, site_code FROM sites WHERE site_status = 'active' ORDER BY site_name");
    $stmt->execute();
    $sites = $stmt->fetchAll();
    
    // Load employees with data isolation
    require_once __DIR__ . '/../includes/data_isolation.php';
    $accessibleSiteIds = getAccessibleSiteIds();
    
    if (empty($accessibleSiteIds)) {
        $employees = [];
    } else {
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        $employeeQuery = "
            SELECT employee_id, site_id, employee_code, first_name, middle_name, last_name, employment_status
            FROM employees 
            WHERE employment_status = 'active' AND site_id IN ($placeholders)
            ORDER BY employee_code, first_name, last_name
        ";
        $stmt = $db->prepare($employeeQuery);
        $stmt->execute($accessibleSiteIds);
        $employees = $stmt->fetchAll();
    }
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $roles = [];
    $sites = [];
    $employees = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create New User</h2>
        <a href="<?php echo BASE_URL; ?>/admin/users.php" class="btn btn-secondary">Back to Users</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <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" id="userForm" 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="username">Username *</label>
                <input type="text" id="username" name="username" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['username'] ?? ''); ?>"
                       minlength="3" autocomplete="username">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="email">Email *</label>
                <input type="email" id="email" name="email" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['email'] ?? ''); ?>"
                       autocomplete="email">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="password">Password *</label>
                <input type="password" id="password" name="password" class="form-control" required
                       minlength="8" autocomplete="new-password">
                <small style="color: var(--text-secondary);">Minimum 8 characters</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="password_confirm">Confirm Password *</label>
                <input type="password" id="password_confirm" name="password_confirm" class="form-control" required
                       minlength="8" autocomplete="new-password">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="full_name">Full Name *</label>
                <input type="text" id="full_name" name="full_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['full_name'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="phone">Phone</label>
                <input type="tel" id="phone" name="phone" class="form-control"
                       value="<?php echo htmlspecialchars($formData['phone'] ?? ''); ?>">
            </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 ($formData['role_id'] ?? 0) == $role['role_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($role['role_name']); ?> (<?php echo htmlspecialchars($role['role_code']); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_id">Site *</label>
                <select id="site_id" name="site_id" class="form-control" required>
                    <option value="">Select Site</option>
                    <?php foreach ($sites as $site): ?>
                    <option value="<?php echo $site['site_id']; ?>" 
                            <?php echo ($formData['site_id'] ?? 0) == $site['site_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($site['site_name']); ?> (<?php echo htmlspecialchars($site['site_code']); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="user_status">Status *</label>
                <select id="user_status" name="user_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['user_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['user_status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="employee_id">Employee (Optional)</label>
                <select id="employee_id" name="employee_id" class="form-control">
                    <option value="">Select Employee (Optional)</option>
                    <?php foreach ($employees as $emp): 
                        $empName = trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name']);
                        $empDisplay = $emp['employee_code'] . ' - ' . $empName;
                    ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            data-site="<?php echo $emp['site_id']; ?>"
                            <?php echo ($formData['employee_id'] ?? null) == $emp['employee_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($empDisplay); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small style="color: var(--text-secondary);">Link this user account to an employee record</small>
            </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; ?>/admin/users.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create User</button>
        </div>
    </form>
</div>

<script>
document.getElementById('userForm').addEventListener('submit', function(e) {
    const password = document.getElementById('password').value;
    const passwordConfirm = document.getElementById('password_confirm').value;
    
    if (password !== passwordConfirm) {
        e.preventDefault();
        alert('Passwords do not match!');
        return false;
    }
    
    if (password.length < 8) {
        e.preventDefault();
        alert('Password must be at least 8 characters long!');
        return false;
    }
});

// Filter employees based on selected site
document.getElementById('site_id').addEventListener('change', function() {
    const selectedSiteId = this.value;
    const employeeSelect = document.getElementById('employee_id');
    const options = employeeSelect.querySelectorAll('option');
    
    // Show/hide options based on site
    options.forEach(function(option) {
        if (option.value === '') {
            // Always show the default option
            option.style.display = '';
        } else {
            const optionSiteId = option.getAttribute('data-site');
            if (selectedSiteId === '' || optionSiteId === selectedSiteId) {
                option.style.display = '';
            } else {
                option.style.display = 'none';
            }
        }
    });
    
    // Reset selection if current selection doesn't match site
    if (selectedSiteId && employeeSelect.value) {
        const selectedOption = employeeSelect.options[employeeSelect.selectedIndex];
        if (selectedOption && selectedOption.getAttribute('data-site') !== selectedSiteId) {
            employeeSelect.value = '';
        }
    }
});

// Trigger on page load if site is already selected
document.addEventListener('DOMContentLoaded', function() {
    const siteSelect = document.getElementById('site_id');
    if (siteSelect.value) {
        siteSelect.dispatchEvent(new Event('change'));
    }
});
</script>

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

