<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
    $_SESSION['flash']['danger'] = 'Invalid user ID.';
    header('Location: users.php');
    exit;
}

$user = $db->get(
    "SELECT u.*, ur.role, ur.permissions, ur.assigned_at
     FROM users u
     LEFT JOIN user_roles ur ON u.id = ur.user_id
     WHERE u.id = ?",
    [$id]
);

if (!$user) {
    $_SESSION['flash']['danger'] = 'User not found.';
    header('Location: users.php');
    exit;
}

// Additional stats
$enrollments = $db->get(
    "SELECT COUNT(*) AS cnt FROM course_enrollments WHERE student_id = ?",
    [$id]
);

$certificates = $db->get(
    "SELECT COUNT(*) AS cnt FROM certificates WHERE student_id = ? AND is_revoked = 0",
    [$id]
);

$pageTitle = 'View User';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">User Details</h1>
    <p class="text-muted mb-0">View profile and activity</p>
  </div>
  <div>
    <a href="users_edit.php?id=<?php echo $id; ?>" class="btn btn-primary me-2">
      <i class="fas fa-edit me-2"></i>Edit
    </a>
    <a href="users.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Users
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-4">
    <div class="card">
      <div class="card-body text-center">
        <div class="avatar avatar-xl mb-3">
          <div class="avatar-initial rounded-circle bg-primary">
            <?php echo strtoupper(substr($user['first_name'] ?? '', 0, 1) . substr($user['last_name'] ?? '', 0, 1)); ?>
          </div>
        </div>
        <h5 class="mb-1"><?php echo htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></h5>
        <p class="text-muted mb-3">@<?php echo htmlspecialchars($user['username'] ?? ''); ?></p>
        <span class="badge bg-<?php echo $user['role']==='super_admin'?'danger':($user['role']==='admin'?'warning':'secondary'); ?>">
          <?php echo htmlspecialchars(ucwords(str_replace('_',' ',$user['role'] ?? ''))); ?>
        </span>
      </div>
    </div>
  </div>

  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Profile Information</h5>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Username</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['username'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Email</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Region</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars(ucfirst($user['region'] ?? '')); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Status</strong></div>
          <div class="col-sm-9">
            <span class="badge bg-<?php echo $user['status']==='active'?'success':($user['status']==='suspended'?'danger':'secondary'); ?>">
              <?php echo htmlspecialchars(ucfirst($user['status'] ?? '')); ?>
            </span>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Permissions</strong></div>
          <div class="col-sm-9">
            <?php
                $perms = [];
                if (!empty($user['permissions'])) {
                    $decoded = is_string($user['permissions']) ? json_decode($user['permissions'], true) : $user['permissions'];
                    if (is_array($decoded)) {
                        foreach ($decoded as $k => $v) {
                            if ($v) $perms[] = $k;
                        }
                    }
                }
            ?>
            <?php if (empty($perms)): ?>
                <small class="text-muted">None</small>
            <?php else: ?>
                <?php foreach ($perms as $p): ?>
                    <span class="badge bg-info me-1 small"><?php echo htmlspecialchars($p); ?></span>
                <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Joined</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['created_at'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Last Login</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($user['last_login'] ?? 'Never'); ?></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row mt-4">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Learning Stats</h5>
      </div>
      <div class="card-body">
        <div class="row text-center">
          <div class="col-4">
            <h4 class="mb-1"><?php echo (int)($enrollments['cnt'] ?? 0); ?></h4>
            <small class="text-muted">Enrollments</small>
          </div>
          <div class="col-4">
            <h4 class="mb-1"><?php echo (int)($certificates['cnt'] ?? 0); ?></h4>
            <small class="text-muted">Certificates</small>
          </div>
          <div class="col-4">
            <h4 class="mb-1">—</h4>
            <small class="text-muted">Points</small>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Recent Activity</h5>
      </div>
      <div class="card-body">
        <p class="text-muted">Activity log coming soon.</p>
      </div>
    </div>
  </div>
</div>

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