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

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

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

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

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

// Get user details
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT u.*, r.role_name, r.role_code,
               (SELECT site_id FROM user_sites WHERE user_id = u.user_id AND is_primary = 1 LIMIT 1) as primary_site_id
        FROM users u
        INNER JOIN roles r ON u.role_id = r.role_id
        WHERE u.user_id = ?
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if (!$user) {
        redirect(BASE_URL . '/admin/users.php', 'User not found.', 'error');
    }
    
    $formData = $user;
    
} catch (Exception $e) {
    error_log("Error loading user: " . $e->getMessage());
    redirect(BASE_URL . '/admin/users.php', 'Error loading user data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        '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,
        'user_status' => sanitize($_POST['user_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['email'])) {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format.';
    }
    
    if (!empty($formData['password'])) {
        if (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 email already exists (excluding current user)
            $stmt = $db->prepare("SELECT user_id FROM users WHERE email = ? AND user_id != ?");
            $stmt->execute([$formData['email'], $userId]);
            if ($stmt->fetch()) {
                $errors[] = 'Email already exists.';
                $db->rollBack();
            } else {
                // Build update query
                $updateFields = [
                    'email = ?',
                    'full_name = ?',
                    'phone = ?',
                    'role_id = ?',
                    'user_status = ?',
                    'updated_at = NOW()'
                ];
                $updateParams = [
                    $formData['email'],
                    $formData['full_name'],
                    $formData['phone'] ?: null,
                    $formData['role_id'],
                    $formData['user_status']
                ];
                
                // Update password if provided
                if (!empty($formData['password'])) {
                    $updateFields[] = 'password_hash = ?';
                    $updateParams[] = hashPassword($formData['password']);
                }
                
                $updateParams[] = $userId;
                
                $sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE user_id = ?";
                $stmt = $db->prepare($sql);
                $stmt->execute($updateParams);
                
                // Update primary site in user_sites
                $currentPrimarySite = $formData['primary_site_id'] ?? 0;
                if ($currentPrimarySite != $formData['site_id']) {
                    // Remove primary flag from current site
                    if ($currentPrimarySite > 0) {
                        $stmt = $db->prepare("UPDATE user_sites SET is_primary = 0 WHERE user_id = ? AND site_id = ?");
                        $stmt->execute([$userId, $currentPrimarySite]);
                    }
                    
                    // Check if user already has this site
                    $stmt = $db->prepare("SELECT user_site_id FROM user_sites WHERE user_id = ? AND site_id = ?");
                    $stmt->execute([$userId, $formData['site_id']]);
                    if ($stmt->fetch()) {
                        // Update existing
                        $stmt = $db->prepare("UPDATE user_sites SET is_primary = 1 WHERE user_id = ? AND site_id = ?");
                        $stmt->execute([$userId, $formData['site_id']]);
                    } else {
                        // Insert new
                        $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('UPDATE', 'users', $userId);
                
                redirect(BASE_URL . '/admin/users.php', 'User updated successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating user: " . $e->getMessage());
            $errors[] = 'An error occurred while updating user. Please try again.';
        }
    }
}

// Get roles and sites
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();
    
    // Get all sites assigned to this user
    $stmt = $db->prepare("
        SELECT us.site_id, s.site_name, s.site_code, us.is_primary
        FROM user_sites us
        INNER JOIN sites s ON us.site_id = s.site_id
        WHERE us.user_id = ?
        ORDER BY us.is_primary DESC, s.site_name
    ");
    $stmt->execute([$userId]);
    $userSites = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $roles = [];
    $sites = [];
    $userSites = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit User: <?php echo htmlspecialchars($formData['username']); ?></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">Username</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($formData['username']); ?>" disabled>
                <small style="color: var(--text-secondary);">Username cannot be changed</small>
            </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">New Password</label>
                <input type="password" id="password" name="password" class="form-control"
                       minlength="8" autocomplete="new-password" placeholder="Leave blank to keep current password">
                <small style="color: var(--text-secondary);">Leave blank to keep current password</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="password_confirm">Confirm New Password</label>
                <input type="password" id="password_confirm" name="password_confirm" class="form-control"
                       minlength="8" autocomplete="new-password" placeholder="Leave blank to keep current 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">Primary 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['primary_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>
                    <option value="locked" <?php echo ($formData['user_status'] ?? '') === 'locked' ? 'selected' : ''; ?>>Locked</option>
                </select>
            </div>
        </div>
        
        <!-- User Sites Information -->
        <?php if (count($userSites) > 0): ?>
        <div style="margin-top: 30px; padding: 20px; background: #f8fafc; border-radius: 8px;">
            <h3 style="margin-bottom: 15px;">Assigned Sites</h3>
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                <?php foreach ($userSites as $us): ?>
                <div style="padding: 10px; background: white; border-radius: 6px; border: 1px solid var(--border-color);">
                    <div style="font-weight: 600;"><?php echo htmlspecialchars($us['site_name']); ?></div>
                    <div style="font-size: 12px; color: var(--text-secondary);"><?php echo htmlspecialchars($us['site_code']); ?></div>
                    <?php if ($us['is_primary']): ?>
                    <span style="font-size: 11px; color: var(--primary-color); font-weight: 600;">Primary</span>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <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">Update 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) {
        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;
        }
    }
});
</script>

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

