<?php
/**
 * Enterprise HRM ERP System - Edit HR Admin & Assign Sites
 */

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

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

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

$userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($userId <= 0) {
    redirect(BASE_URL . '/admin/hr_admins.php', 'Invalid user ID.', 'error');
}

// Get user
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT u.*, r.role_code
        FROM users u
        INNER JOIN roles r ON u.role_id = r.role_id
        WHERE u.user_id = ? AND r.role_code = 'hr_admin'
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if (!$user) {
        redirect(BASE_URL . '/admin/hr_admins.php', 'HR Admin not found.', 'error');
    }
    
    // Get assigned sites
    $stmt = $db->prepare("
        SELECT site_id, is_primary FROM user_sites WHERE user_id = ?
    ");
    $stmt->execute([$userId]);
    $assignedSites = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // 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 HR Admin: " . $e->getMessage());
    redirect(BASE_URL . '/admin/hr_admins.php', 'Error loading HR Admin data.', 'error');
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'full_name' => sanitize($_POST['full_name'] ?? ''),
        'phone' => sanitize($_POST['phone'] ?? ''),
        'user_status' => sanitize($_POST['user_status'] ?? 'active'),
        'sites' => $_POST['sites'] ?? [],
    ];
    
    // Validation
    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.';
    }
    
    // Password change (optional)
    $changePassword = !empty($_POST['new_password']);
    if ($changePassword) {
        if (strlen($_POST['new_password']) < 8) {
            $errors[] = 'Password must be at least 8 characters long.';
        }
        if ($_POST['new_password'] !== $_POST['new_password_confirm']) {
            $errors[] = 'Passwords do not match.';
        }
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Update user
            if ($changePassword) {
                $passwordHash = hashPassword($_POST['new_password']);
                $stmt = $db->prepare("
                    UPDATE users SET
                        full_name = ?,
                        phone = ?,
                        user_status = ?,
                        password_hash = ?,
                        updated_at = NOW()
                    WHERE user_id = ?
                ");
                $stmt->execute([
                    $formData['full_name'],
                    $formData['phone'] ?: null,
                    $formData['user_status'],
                    $passwordHash,
                    $userId
                ]);
            } else {
                $stmt = $db->prepare("
                    UPDATE users SET
                        full_name = ?,
                        phone = ?,
                        user_status = ?,
                        updated_at = NOW()
                    WHERE user_id = ?
                ");
                $stmt->execute([
                    $formData['full_name'],
                    $formData['phone'] ?: null,
                    $formData['user_status'],
                    $userId
                ]);
            }
            
            // Update site assignments
            // Delete existing assignments
            $stmt = $db->prepare("DELETE FROM user_sites WHERE user_id = ?");
            $stmt->execute([$userId]);
            
            // Insert new assignments
            foreach ($formData['sites'] as $index => $siteId) {
                $isPrimary = ($index === 0) ? 1 : 0;
                $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();
            
            $success = true;
            logAudit('UPDATE', 'users', $userId);
            
            // Reload data
            $stmt = $db->prepare("
                SELECT site_id, is_primary FROM user_sites WHERE user_id = ?
            ");
            $stmt->execute([$userId]);
            $assignedSites = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating HR Admin: " . $e->getMessage());
            $errors[] = 'An error occurred while updating HR Admin. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit 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 ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        HR Admin updated successfully.
    </div>
    <?php endif; ?>
    
    <?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">Username</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label">Email</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
            </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'] ?? $user['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'] ?? $user['phone'] ?? ''); ?>">
            </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'] ?? $user['user_status']) === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['user_status'] ?? $user['user_status']) === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    <option value="locked" <?php echo ($formData['user_status'] ?? $user['user_status']) === 'locked' ? 'selected' : ''; ?>>Locked</option>
                </select>
            </div>
        </div>
        
        <!-- Password Change -->
        <div style="margin-top: 30px; padding: 20px; background: #f9fafb; border-radius: 8px;">
            <h3 style="margin-bottom: 15px;">Change Password (Optional)</h3>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <div class="form-group">
                    <label class="form-label" for="new_password">New Password</label>
                    <input type="password" id="new_password" name="new_password" class="form-control"
                           minlength="8" placeholder="Leave blank to keep current password">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="new_password_confirm">Confirm New Password</label>
                    <input type="password" id="new_password_confirm" name="new_password_confirm" class="form-control"
                           minlength="8" placeholder="Confirm new password">
                </div>
            </div>
        </div>
        
        <!-- Site Assignment -->
        <div style="margin-top: 30px;">
            <h3 style="margin-bottom: 15px;">Assign Sites *</h3>
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 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 isset($assignedSites[$site['site_id']]) ? 'checked' : ''; ?>>
                    <span><?php echo htmlspecialchars($site['site_name']); ?></span>
                    <?php if (isset($assignedSites[$site['site_id']]) && $assignedSites[$site['site_id']]): ?>
                    <span style="color: var(--primary-color); font-size: 12px;">(Primary)</span>
                    <?php endif; ?>
                </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 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">Update HR Admin</button>
        </div>
    </form>
</div>

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

