<?php
/**
 * Enterprise HRM ERP System - Create HR Admin
 */

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

if (!canManageHRAdmin()) {
    $_SESSION['error'] = 'Only Super Admin can create HR Admins.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Create HR Admin';
$currentModule = 'settings';

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

// Get HR Admin role ID
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT role_id FROM roles WHERE role_code = 'hr_admin'");
    $stmt->execute();
    $hrAdminRole = $stmt->fetch();
    $hrAdminRoleId = $hrAdminRole ? $hrAdminRole['role_id'] : 0;
    
    if (!$hrAdminRoleId) {
        $errors[] = 'HR Admin role not found in system.';
    }
    
    // Get all sites
    $stmt = $db->prepare("SELECT site_id, site_name FROM sites WHERE site_status = 'active' ORDER BY site_name");
    $stmt->execute();
    $sites = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $sites = [];
}

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'] ?? ''),
        'sites' => $_POST['sites'] ?? [],
    ];
    
    // Validation
    if (empty($formData['username'])) {
        $errors[] = 'Username is required.';
    }
    
    if (empty($formData['email']) || !validateEmail($formData['email'])) {
        $errors[] = 'Valid email is required.';
    }
    
    if (empty($formData['password'])) {
        $errors[] = 'Password is required.';
    } elseif (strlen($formData['password']) < 8) {
        $errors[] = 'Password must be at least 8 characters long.';
    }
    
    if ($formData['password'] !== $formData['password_confirm']) {
        $errors[] = 'Passwords do not match.';
    }
    
    if (empty($formData['full_name'])) {
        $errors[] = 'Full name is required.';
    }
    
    if (empty($formData['sites'])) {
        $errors[] = 'Please assign at least one site to the HR Admin.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if username exists
            $stmt = $db->prepare("SELECT user_id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$formData['username'], $formData['email']]);
            if ($stmt->fetch()) {
                $errors[] = 'Username or email already exists.';
                $db->rollBack();
            } else {
                // Create user
                $passwordHash = hashPassword($formData['password']);
                $stmt = $db->prepare("
                    INSERT INTO users (
                        username, email, password_hash, full_name, phone, role_id, user_status
                    ) VALUES (?, ?, ?, ?, ?, ?, 'active')
                ");
                $stmt->execute([
                    $formData['username'],
                    $formData['email'],
                    $passwordHash,
                    $formData['full_name'],
                    $formData['phone'] ?: null,
                    $hrAdminRoleId
                ]);
                
                $userId = $db->lastInsertId();
                
                // Assign sites
                $primarySet = false;
                foreach ($formData['sites'] as $index => $siteId) {
                    $isPrimary = ($index === 0) ? 1 : 0; // First site is primary
                    $stmt = $db->prepare("
                        INSERT INTO user_sites (user_id, site_id, is_primary, assigned_by)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $userId,
                        (int)$siteId,
                        $isPrimary,
                        getCurrentUserId()
                    ]);
                }
                
                $db->commit();
                
                logAudit('CREATE', 'users', $userId);
                
                redirect(BASE_URL . '/admin/hr_admins.php', 'HR Admin created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating HR Admin: " . $e->getMessage());
            $errors[] = 'An error occurred while creating HR Admin. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create HR Admin</h2>
        <a href="<?php echo BASE_URL; ?>/admin/hr_admins.php" class="btn btn-secondary">Back to HR Admins</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" 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'] ?? ''); ?>">
            </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'] ?? ''); ?>">
            </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">
                <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">
            </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="text" id="phone" name="phone" class="form-control"
                       value="<?php echo htmlspecialchars($formData['phone'] ?? ''); ?>">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label">Assign Sites *</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 10px;">
                    <?php foreach ($sites as $site): ?>
                    <label style="display: flex; align-items: center; gap: 8px; padding: 10px; background: #f9fafb; border-radius: 6px; cursor: pointer;">
                        <input type="checkbox" name="sites[]" value="<?php echo $site['site_id']; ?>"
                               <?php echo in_array($site['site_id'], $formData['sites'] ?? []) ? 'checked' : ''; ?>>
                        <span><?php echo htmlspecialchars($site['site_name']); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <small style="color: var(--text-secondary); margin-top: 5px; display: block;">
                    Select one or more sites. The first selected site will be set as primary.
                </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/hr_admins.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create HR Admin</button>
        </div>
    </form>
</div>

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

