<?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 u.*, up.*,
           (SELECT COUNT(*) FROM user_activities ua WHERE ua.user_id = u.id) as total_activities,
           (SELECT COUNT(*) FROM user_achievements ua2 WHERE ua2.user_id = u.id) as total_achievements
    FROM users u
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE u.id = ?
");
$stmt->execute([$user_id]);
$user_data = $stmt->fetch();

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

// Get user activities (recent)
$activities_stmt = $pdo->prepare("
    SELECT * FROM user_activities
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT 20
");
$activities_stmt->execute([$user_id]);
$activities = $activities_stmt->fetchAll();

// Get user achievements
$achievements_stmt = $pdo->prepare("
    SELECT * FROM user_achievements
    WHERE user_id = ?
    ORDER BY earned_at DESC
");
$achievements_stmt->execute([$user_id]);
$achievements = $achievements_stmt->fetchAll();

// Handle role change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_role'])) {
    $new_role = $_POST['new_role'] ?? '';
    if (in_array($new_role, getAllRoles()) && $new_role !== $user_data['role']) {
        $stmt = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
        if ($stmt->execute([$new_role, $user_id])) {
            // Log activity
            logUserActivity($user_id, 'role_changed', "Role changed from {$user_data['role']} to $new_role");

            $user_data['role'] = $new_role;
            $success_message = "User role updated successfully.";
        } else {
            $error_message = "Failed to update user role.";
        }
    }
}

// Handle status change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_status'])) {
    $new_status = isset($_POST['email_verified']) ? 1 : 0;
    if ($new_status != $user_data['email_verified']) {
        $stmt = $pdo->prepare("UPDATE users SET email_verified = ? WHERE id = ?");
        if ($stmt->execute([$new_status, $user_id])) {
            // Log activity
            $status_text = $new_status ? 'verified' : 'unverified';
            logUserActivity($user_id, 'status_changed', "Account status changed to $status_text");

            $user_data['email_verified'] = $new_status;
            $success_message = "User status updated successfully.";
        } else {
            $error_message = "Failed to update user status.";
        }
    }
}

// Handle account lock/unlock
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['lock_account'])) {
    $lock_duration = intval($_POST['lock_duration'] ?? 15); // minutes
    $lock_until = date('Y-m-d H:i:s', strtotime("+$lock_duration minutes"));

    $stmt = $pdo->prepare("UPDATE users SET account_locked_until = ?, failed_login_attempts = 5 WHERE id = ?");
    if ($stmt->execute([$lock_until, $user_id])) {
        logUserActivity($user_id, 'account_locked', "Account locked for $lock_duration minutes");
        $success_message = "Account locked successfully.";
        $user_data['account_locked_until'] = $lock_until;
    } else {
        $error_message = "Failed to lock account.";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unlock_account'])) {
    $stmt = $pdo->prepare("UPDATE users SET account_locked_until = NULL, failed_login_attempts = 0 WHERE id = ?");
    if ($stmt->execute([$user_id])) {
        logUserActivity($user_id, 'account_unlocked', "Account unlocked");
        $success_message = "Account unlocked successfully.";
        $user_data['account_locked_until'] = null;
    } else {
        $error_message = "Failed to unlock account.";
    }
}

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

// Helper function to log user activity
function logUserActivity($user_id, $action_type, $description) {
    global $pdo;
    $stmt = $pdo->prepare("
        INSERT INTO user_activities (user_id, action_type, action_description, ip_address, user_agent)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $user_id,
        $action_type,
        $description,
        $_SERVER['REMOTE_ADDR'] ?? '',
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}
?>

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

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

<div class="user-profile">
    <div class="profile-header">
        <div class="user-avatar">
            <?php if (!empty($user_data['avatar'])): ?>
                <img src="<?php echo htmlspecialchars($user_data['avatar']); ?>" alt="Avatar">
            <?php else: ?>
                <div class="avatar-placeholder">
                    <i class="fas fa-user"></i>
                </div>
            <?php endif; ?>
        </div>

        <div class="user-details">
            <h1><?php echo htmlspecialchars($user_data['username']); ?></h1>
            <div class="user-meta">
                <span class="email"><?php echo htmlspecialchars($user_data['email']); ?></span>
                <span class="role-badge role-<?php echo $user_data['role']; ?>">
                    <?php echo getRoleDisplayName($user_data['role']); ?>
                </span>
                <?php if ($user_data['email_verified']): ?>
                    <span class="status-badge status-active">Verified</span>
                <?php else: ?>
                    <span class="status-badge status-inactive">Unverified</span>
                <?php endif; ?>
            </div>

            <?php if ($user_data['first_name'] || $user_data['last_name']): ?>
                <p class="full-name"><?php echo htmlspecialchars(trim($user_data['first_name'] . ' ' . $user_data['last_name'])); ?></p>
            <?php endif; ?>

            <div class="user-stats">
                <div class="stat">
                    <span class="stat-value"><?php echo $user_data['total_activities']; ?></span>
                    <span class="stat-label">Activities</span>
                </div>
                <div class="stat">
                    <span class="stat-value"><?php echo $user_data['total_achievements']; ?></span>
                    <span class="stat-label">Achievements</span>
                </div>
                <div class="stat">
                    <span class="stat-value"><?php echo $user_data['last_login'] ? formatDate($user_data['last_login']) : 'Never'; ?></span>
                    <span class="stat-label">Last Login</span>
                </div>
            </div>
        </div>

        <div class="profile-actions">
            <a href="user_edit.php?id=<?php echo $user_id; ?>" class="btn btn-primary">
                <i class="fas fa-edit"></i> Edit User
            </a>
            <a href="users.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Users
            </a>
        </div>
    </div>

    <div class="profile-content">
        <div class="profile-section">
            <h2><i class="fas fa-info-circle"></i> Account Information</h2>
            <div class="info-grid">
                <div class="info-item">
                    <label>User ID:</label>
                    <span><?php echo $user_data['id']; ?></span>
                </div>
                <div class="info-item">
                    <label>Username:</label>
                    <span><?php echo htmlspecialchars($user_data['username']); ?></span>
                </div>
                <div class="info-item">
                    <label>Email:</label>
                    <span><?php echo htmlspecialchars($user_data['email']); ?></span>
                </div>
                <div class="info-item">
                    <label>Role:</label>
                    <span class="role-badge role-<?php echo $user_data['role']; ?>">
                        <?php echo getRoleDisplayName($user_data['role']); ?>
                    </span>
                </div>
                <div class="info-item">
                    <label>Email Verified:</label>
                    <span><?php echo $user_data['email_verified'] ? 'Yes' : 'No'; ?></span>
                </div>
                <div class="info-item">
                    <label>Account Status:</label>
                    <span>
                        <?php if ($user_data['account_locked_until'] && strtotime($user_data['account_locked_until']) > time()): ?>
                            <span class="status-badge status-inactive">Locked until <?php echo formatDate($user_data['account_locked_until']); ?></span>
                        <?php else: ?>
                            <span class="status-badge status-active">Active</span>
                        <?php endif; ?>
                    </span>
                </div>
                <div class="info-item">
                    <label>Created:</label>
                    <span><?php echo formatDate($user_data['created_at']); ?></span>
                </div>
                <div class="info-item">
                    <label>Last Login:</label>
                    <span><?php echo $user_data['last_login'] ? formatDate($user_data['last_login']) : 'Never'; ?></span>
                </div>
            </div>
        </div>

        <?php if ($user_data['bio'] || $user_data['phone'] || $user_data['address'] || $user_data['website']): ?>
            <div class="profile-section">
                <h2><i class="fas fa-user"></i> Profile Information</h2>
                <div class="profile-details">
                    <?php if ($user_data['bio']): ?>
                        <div class="detail-item">
                            <label>Bio:</label>
                            <p><?php echo nl2br(htmlspecialchars($user_data['bio'])); ?></p>
                        </div>
                    <?php endif; ?>

                    <?php if ($user_data['phone']): ?>
                        <div class="detail-item">
                            <label>Phone:</label>
                            <span><?php echo htmlspecialchars($user_data['phone']); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($user_data['address']): ?>
                        <div class="detail-item">
                            <label>Address:</label>
                            <p><?php echo nl2br(htmlspecialchars($user_data['address'])); ?></p>
                        </div>
                    <?php endif; ?>

                    <?php if ($user_data['website']): ?>
                        <div class="detail-item">
                            <label>Website:</label>
                            <a href="<?php echo htmlspecialchars($user_data['website']); ?>" target="_blank">
                                <?php echo htmlspecialchars($user_data['website']); ?>
                            </a>
                        </div>
                    <?php endif; ?>

                    <?php if ($user_data['date_of_birth']): ?>
                        <div class="detail-item">
                            <label>Date of Birth:</label>
                            <span><?php echo formatDate($user_data['date_of_birth']); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($user_data['gender']): ?>
                        <div class="detail-item">
                            <label>Gender:</label>
                            <span><?php echo ucfirst(str_replace('_', ' ', $user_data['gender'])); ?></span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="profile-section">
            <h2><i class="fas fa-cogs"></i> Account Management</h2>
            <div class="management-actions">
                <form method="POST" class="inline-form">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <div class="form-group">
                        <label>Change Role:</label>
                        <select name="new_role" required>
                            <?php foreach (getAllRoles() as $role): ?>
                                <option value="<?php echo $role; ?>" <?php echo $role === $user_data['role'] ? 'selected' : ''; ?>>
                                    <?php echo getRoleDisplayName($role); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" name="change_role" class="btn btn-sm">Update Role</button>
                    </div>
                </form>

                <form method="POST" class="inline-form">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <div class="form-group">
                        <label>Account Status:</label>
                        <label>
                            <input type="checkbox" name="email_verified"
                                   <?php echo $user_data['email_verified'] ? 'checked' : ''; ?>>
                            Email Verified
                        </label>
                        <button type="submit" name="change_status" class="btn btn-sm">Update Status</button>
                    </div>
                </form>

                <?php if ($user_data['account_locked_until'] && strtotime($user_data['account_locked_until']) > time()): ?>
                    <form method="POST" class="inline-form">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <button type="submit" name="unlock_account" class="btn btn-sm btn-success">
                            <i class="fas fa-unlock"></i> Unlock Account
                        </button>
                    </form>
                <?php else: ?>
                    <form method="POST" class="inline-form">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <div class="form-group">
                            <label>Lock Account:</label>
                            <select name="lock_duration">
                                <option value="15">15 minutes</option>
                                <option value="60">1 hour</option>
                                <option value="1440">1 day</option>
                                <option value="10080">1 week</option>
                            </select>
                            <button type="submit" name="lock_account" class="btn btn-sm btn-warning">
                                <i class="fas fa-lock"></i> Lock Account
                            </button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!empty($achievements)): ?>
            <div class="profile-section">
                <h2><i class="fas fa-trophy"></i> Achievements</h2>
                <div class="achievements-grid">
                    <?php foreach ($achievements as $achievement): ?>
                        <div class="achievement-item">
                            <div class="achievement-icon">
                                <i class="<?php echo htmlspecialchars($achievement['icon'] ?? 'fas fa-star'); ?>"></i>
                            </div>
                            <div class="achievement-info">
                                <h4><?php echo htmlspecialchars($achievement['title']); ?></h4>
                                <p><?php echo htmlspecialchars($achievement['description']); ?></p>
                                <small>Earned <?php echo formatDate($achievement['earned_at']); ?></small>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="profile-section">
            <h2><i class="fas fa-history"></i> Recent Activity</h2>
            <?php if (!empty($activities)): ?>
                <div class="activity-timeline">
                    <?php foreach ($activities as $activity): ?>
                        <div class="activity-item">
                            <div class="activity-icon">
                                <i class="fas fa-circle"></i>
                            </div>
                            <div class="activity-content">
                                <p><?php echo htmlspecialchars($activity['action_description']); ?></p>
                                <small>
                                    <?php echo formatDate($activity['created_at']); ?>
                                    <?php if ($activity['ip_address']): ?>
                                        - IP: <?php echo htmlspecialchars($activity['ip_address']); ?>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="no-activity">No recent activity found.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

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