<?php
/**
 * Enterprise HRM ERP System - Create HR Admin
 * Only Super Admin can create HR Admins
 */

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

// Only Super Admin can access
if (!isSuperAdmin()) {
    $_SESSION['error'] = 'Access denied. Super Admin only.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Create HR Admin';
$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'] ?? ''),
        'site_id' => isset($_POST['site_id']) ? (int)$_POST['site_id'] : 0,
        '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['site_id'] <= 0) {
        $errors[] = 'Please select a site.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Get HR Admin role_id (case-insensitive)
            $stmt = $db->prepare("SELECT role_id FROM roles WHERE LOWER(role_code) = 'hr_admin' OR role_code = 'HR_ADMIN' LIMIT 1");
            $stmt->execute();
            $hrAdminRole = $stmt->fetch();
            
            if (!$hrAdminRole) {
                $errors[] = 'HR Admin role not found. Please ensure HR_ADMIN role exists in roles table.';
                $db->rollBack();
            } else {
                // 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 {
                        // Verify site exists
                        $stmt = $db->prepare("SELECT site_id FROM sites WHERE site_id = ? AND site_status = 'active'");
                        $stmt->execute([$formData['site_id']]);
                        if (!$stmt->fetch()) {
                            $errors[] = 'Selected site is invalid or inactive.';
                            $db->rollBack();
                        } else {
                            // Hash password
                            $passwordHash = hashPassword($formData['password']);
                            
                            // Insert user with HR Admin role
                            $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,
                                $hrAdminRole['role_id'],
                                $formData['site_id'],
                                $formData['user_status']
                            ]);
                            
                            $userId = $db->lastInsertId();
                            
                            // Add user to user_sites (set as primary) - if table exists
                            try {
                                // Check if user_sites table exists
                                $checkTable = $db->query("SHOW TABLES LIKE 'user_sites'");
                                if ($checkTable->rowCount() > 0) {
                            $stmt = $db->prepare("
                                INSERT INTO user_sites (user_id, site_id, is_primary, assigned_by)
                                VALUES (?, ?, 1, ?)
                            ");
                            $stmt->execute([$userId, $formData['site_id'], getCurrentUserId()]);
                                }
                            } catch (Exception $e) {
                                // user_sites table doesn't exist or error - continue anyway
                                error_log("Note: user_sites table not found or error: " . $e->getMessage());
                            }
                            
                            $db->commit();
                            
                            // Log audit
                            logAudit('CREATE', 'users', $userId, null, json_encode([
                                'action' => 'HR Admin Created',
                                'created_by' => getCurrentUserId(),
                                'site_id' => $formData['site_id']
                            ]));
                            
                            $_SESSION['success'] = 'HR Admin created successfully.';
                            header('Location: ' . BASE_URL . '/dashboards/super_admin.php');
                            exit;
                        }
                    }
                }
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating HR Admin: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            
            // More specific error message
            $errorMsg = 'An error occurred while creating HR Admin. ';
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $errorMsg .= 'Username or email already exists.';
            } elseif (strpos($e->getMessage(), 'foreign key') !== false) {
                $errorMsg .= 'Invalid site or role selected.';
            } else {
                $errorMsg .= 'Error: ' . htmlspecialchars($e->getMessage());
            }
            $errors[] = $errorMsg;
        }
    }
}

// Get active sites
try {
    $db = getDB();
    $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();
} catch (Exception $e) {
    error_log("Error loading sites: " . $e->getMessage());
    $sites = [];
}

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; ?>/dashboards/super_admin.php" class="btn btn-secondary">Back</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
        <br>
        <p><strong>Need help?</strong> <a href="test_hr_creation.php" style="color: #fff; text-decoration: underline;">🔍 Run Diagnostic Check</a></p>
    </div>
    <?php endif; ?>
    
    <form method="POST" action="">
        <div class="form-row">
            <div class="form-group">
                <label class="form-label" for="username">Username *</label>
                <input type="text" id="username" name="username" class="form-control" required
                       minlength="3" value="<?php echo htmlspecialchars($formData['username'] ?? ''); ?>"
                       placeholder="Enter 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'] ?? ''); ?>"
                       placeholder="Enter email">
            </div>
        </div>
        
        <div class="form-row">
            <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"
                       placeholder="Minimum 8 characters">
            </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"
                       placeholder="Confirm password">
            </div>
        </div>
        
        <div class="form-row">
            <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'] ?? ''); ?>"
                       placeholder="Enter 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'] ?? ''); ?>"
                       placeholder="Enter phone number">
            </div>
        </div>
        
        <div class="form-row">
            <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'] . ' (' . $site['site_code'] . ')'); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small class="form-text">This HR Admin will manage employees in the selected site.</small>
            </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>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">Create HR Admin</button>
            <a href="<?php echo BASE_URL; ?>/dashboards/super_admin.php" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
</div>

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

