<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$pdo = getDB();

// Get user ID from URL
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$user_id) {
    header('Location: users.php');
    exit;
}

// Get user data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user_data = $stmt->fetch();

if (!$user_data) {
    header('Location: users.php');
    exit;
}

// Get user profile
$stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
$stmt->execute([$user_id]);
$user_profile = $stmt->fetch() ?: [];

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = $_POST['role'] ?? $user_data['role'];
    $email_verified = isset($_POST['email_verified']) ? 1 : 0;
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $bio = trim($_POST['bio'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $website = trim($_POST['website'] ?? '');
    $date_of_birth = trim($_POST['date_of_birth'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $change_password = isset($_POST['change_password']);
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validation
    if (!$username) {
        $errors[] = 'Username is required.';
    } elseif (!preg_match('/^[a-zA-Z0-9_]{3,50}$/', $username)) {
        $errors[] = 'Username must be 3-50 characters and contain only letters, numbers, and underscores.';
    }

    if (!$email) {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }

    if (!in_array($role, getAllRoles())) {
        $errors[] = 'Invalid role selected.';
    }

    // Check if username or email already exists (excluding current user)
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?) AND id != ?");
        $stmt->execute([$username, $email, $user_id]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = 'Username or email already exists.';
        }
    }

    // Password validation if changing
    if ($change_password) {
        if (!$new_password) {
            $errors[] = 'New password is required.';
        } elseif (strlen($new_password) < 6) {
            $errors[] = 'Password must be at least 6 characters long.';
        } elseif ($new_password !== $confirm_password) {
            $errors[] = 'Passwords do not match.';
        }
    }

    // Website validation
    if ($website && !filter_var($website, FILTER_VALIDATE_URL)) {
        $errors[] = 'Please enter a valid website URL.';
    }

    // Update user if no errors
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Update user basic info
            $update_data = [
                'username' => $username,
                'email' => $email,
                'role' => $role,
                'email_verified' => $email_verified
            ];

            if ($change_password) {
                $update_data['password'] = password_hash($new_password, PASSWORD_DEFAULT);
            }

            $set_parts = [];
            foreach (array_keys($update_data) as $column) {
                $set_parts[] = "$column = ?";
            }
            $set_clause = implode(', ', $set_parts);

            $stmt = $pdo->prepare("UPDATE users SET $set_clause WHERE id = ?");
            $stmt->execute(array_merge(array_values($update_data), [$user_id]));

            // Update or insert profile
            $profile_data = [
                'first_name' => $first_name,
                'last_name' => $last_name,
                'phone' => $phone,
                'bio' => $bio,
                'address' => $address,
                'website' => $website,
                'date_of_birth' => $date_of_birth ?: null,
                'gender' => $gender,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if (empty($user_profile)) {
                // Insert new profile
                $profile_data['user_id'] = $user_id;
                $columns = implode(', ', array_keys($profile_data));
                $placeholders = str_repeat('?, ', count($profile_data) - 1) . '?';
                $stmt = $pdo->prepare("INSERT INTO user_profiles ($columns) VALUES ($placeholders)");
                $stmt->execute(array_values($profile_data));
            } else {
                // Update existing profile
                $set_parts = [];
                foreach (array_keys($profile_data) as $column) {
                    $set_parts[] = "$column = ?";
                }
                $set_clause = implode(', ', $set_parts);
                $stmt = $pdo->prepare("UPDATE user_profiles SET $set_clause WHERE user_id = ?");
                $stmt->execute(array_merge(array_values($profile_data), [$user_id]));
            }

            // Log activity
            $changes = [];
            if ($username !== $user_data['username']) $changes[] = "username: {$user_data['username']} → $username";
            if ($email !== $user_data['email']) $changes[] = "email: {$user_data['email']} → $email";
            if ($role !== $user_data['role']) $changes[] = "role: {$user_data['role']} → $role";
            if ($email_verified != $user_data['email_verified']) $changes[] = "email_verified: " . ($user_data['email_verified'] ? 'true' : 'false') . " → " . ($email_verified ? 'true' : 'false');
            if ($change_password) $changes[] = "password changed";

            if (!empty($changes)) {
                $stmt = $pdo->prepare("
                    INSERT INTO user_activities (user_id, action_type, action_description, ip_address, user_agent)
                    VALUES (?, 'user_updated', ?, ?, ?)
                ");
                $stmt->execute([
                    $_SESSION['user_id'],
                    "Updated user {$username}: " . implode(', ', $changes),
                    $_SERVER['REMOTE_ADDR'] ?? '',
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
            }

            $pdo->commit();
            $success = 'User updated successfully!';

            // Refresh data
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user_data = $stmt->fetch();

            $stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $user_profile = $stmt->fetch() ?: [];

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = 'Error updating user: ' . $e->getMessage();
        }
    }
}

$page_title = 'Edit User - ' . htmlspecialchars($user_data['username']);
include 'includes/admin_header.php';
?>

<div class="user-form-page">
    <div class="form-header">
        <h1><i class="fas fa-user-edit"></i> Edit User</h1>
        <p>Modify user information, role, and permissions.</p>
        <div class="header-actions">
            <a href="user_profile.php?id=<?php echo $user_id; ?>" class="btn btn-secondary">
                <i class="fas fa-eye"></i> View Profile
            </a>
            <a href="users.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Users
            </a>
        </div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <?php echo htmlspecialchars($success); ?>
        </div>
    <?php endif; ?>

    <div class="form-container">
        <form method="POST" class="user-form">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

            <div class="form-section">
                <h2><i class="fas fa-user"></i> Account Information</h2>

                <div class="form-row">
                    <div class="form-group">
                        <label for="username">Username *</label>
                        <input type="text" id="username" name="username" required
                               value="<?php echo htmlspecialchars($user_data['username']); ?>"
                               pattern="[a-zA-Z0-9_]{3,50}">
                        <small>User ID: <?php echo $user_data['id']; ?></small>
                    </div>

                    <div class="form-group">
                        <label for="email">Email Address *</label>
                        <input type="email" id="email" name="email" required
                               value="<?php echo htmlspecialchars($user_data['email']); ?>">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="role">Role *</label>
                        <select id="role" name="role" required>
                            <?php foreach (getAllRoles() as $role_option): ?>
                                <option value="<?php echo $role_option; ?>" <?php echo $user_data['role'] === $role_option ? 'selected' : ''; ?>>
                                    <?php echo getRoleDisplayName($role_option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="email_verified" <?php echo $user_data['email_verified'] ? 'checked' : ''; ?>>
                            Email Verified
                        </label>
                        <small>Last login: <?php echo $user_data['last_login'] ? formatDate($user_data['last_login']) : 'Never'; ?></small>
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h2><i class="fas fa-id-card"></i> Profile Information</h2>

                <div class="form-row">
                    <div class="form-group">
                        <label for="first_name">First Name</label>
                        <input type="text" id="first_name" name="first_name"
                               value="<?php echo htmlspecialchars($user_profile['first_name'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="last_name">Last Name</label>
                        <input type="text" id="last_name" name="last_name"
                               value="<?php echo htmlspecialchars($user_profile['last_name'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone"
                           value="<?php echo htmlspecialchars($user_profile['phone'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label for="bio">Bio</label>
                    <textarea id="bio" name="bio" rows="3"><?php echo htmlspecialchars($user_profile['bio'] ?? ''); ?></textarea>
                </div>

                <div class="form-group">
                    <label for="address">Address</label>
                    <textarea id="address" name="address" rows="2"><?php echo htmlspecialchars($user_profile['address'] ?? ''); ?></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="website">Website</label>
                        <input type="url" id="website" name="website"
                               value="<?php echo htmlspecialchars($user_profile['website'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="date_of_birth">Date of Birth</label>
                        <input type="date" id="date_of_birth" name="date_of_birth"
                               value="<?php echo htmlspecialchars($user_profile['date_of_birth'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label for="gender">Gender</label>
                    <select id="gender" name="gender">
                        <option value="">Prefer not to say</option>
                        <option value="male" <?php echo ($user_profile['gender'] ?? '') === 'male' ? 'selected' : ''; ?>>Male</option>
                        <option value="female" <?php echo ($user_profile['gender'] ?? '') === 'female' ? 'selected' : ''; ?>>Female</option>
                        <option value="other" <?php echo ($user_profile['gender'] ?? '') === 'other' ? 'selected' : ''; ?>>Other</option>
                    </select>
                </div>
            </div>

            <div class="form-section">
                <h2><i class="fas fa-key"></i> Password Management</h2>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="change_password" id="change_password">
                        Change Password
                    </label>
                </div>

                <div id="password-fields" style="display: none;">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="new_password">New Password *</label>
                            <input type="password" id="new_password" name="new_password" minlength="6">
                            <small>Minimum 6 characters</small>
                        </div>

                        <div class="form-group">
                            <label for="confirm_password">Confirm New Password *</label>
                            <input type="password" id="confirm_password" name="confirm_password">
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Changes
                </button>
                <a href="users.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle password fields
    const changePassword = document.getElementById('change_password');
    const passwordFields = document.getElementById('password-fields');

    changePassword.addEventListener('change', function() {
        passwordFields.style.display = this.checked ? 'block' : 'none';
        const inputs = passwordFields.querySelectorAll('input');
        inputs.forEach(input => {
            input.required = this.checked;
        });
    });

    // Password confirmation validation
    const newPassword = document.getElementById('new_password');
    const confirmPassword = document.getElementById('confirm_password');

    if (newPassword && confirmPassword) {
        confirmPassword.addEventListener('input', function() {
            if (this.value && this.value !== newPassword.value) {
                this.setCustomValidity('Passwords do not match');
            } else {
                this.setCustomValidity('');
            }
        });
    }

    // Username validation
    const username = document.getElementById('username');
    username.addEventListener('input', function() {
        const regex = /^[a-zA-Z0-9_]{3,50}$/;
        if (!regex.test(this.value)) {
            this.setCustomValidity('Username must be 3-50 characters and contain only letters, numbers, and underscores');
        } else {
            this.setCustomValidity('');
        }
    });
});
</script>

<?php include 'includes/admin_footer.php'; ?>