<?php
// ============================================================
//  user_view.php — View Single User Profile
//  Place in: /admin/user_view.php
// ============================================================
require_once 'includes/auth_check.php';

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

$user = db_fetch_one(
    "SELECT * FROM users WHERE id = ?", [$user_id]
);

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

$page_title = 'User Profile — ' . $user['full_name'];

// ── Flash messages ────────────────────────────────────────────
$flash_success = $_SESSION['flash_success'] ?? '';
$flash_error   = $_SESSION['flash_error']   ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

// ── CSRF ──────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ── Handle quick status change via POST ───────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quick_status'])) {
    if ($_POST['csrf_token'] !== $csrf) {
        $_SESSION['flash_error'] = 'Invalid token.';
    } else {
        $new_status = $_POST['quick_status'];
        $allowed    = ['active', 'inactive', 'banned', 'pending'];
        if (in_array($new_status, $allowed)) {
            db_execute("UPDATE users SET status = ? WHERE id = ?", [$new_status, $user_id]);
            db_execute(
                "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                 VALUES (?, 'changed_user_status', 'user', ?, ?, ?, ?)",
                [$current_admin['id'], $user_id, $user['full_name'],
                 "Status changed to {$new_status}", $_SERVER['REMOTE_ADDR']]
            );
            $_SESSION['flash_success'] = "Status updated to " . ucfirst($new_status) . ".";
        }
    }
    header("Location: user_view.php?id={$user_id}");
    exit;
}

// ── Reload fresh user data ────────────────────────────────────
$user = db_fetch_one("SELECT * FROM users WHERE id = ?", [$user_id]);

// ── User's activity log ───────────────────────────────────────
$user_log = db_fetch_all(
    "SELECT al.action, al.details, al.created_at, a.full_name AS admin_name
     FROM activity_log al
     JOIN admins a ON a.id = al.admin_id
     WHERE al.target_id = ? AND al.target_type = 'user'
     ORDER BY al.created_at DESC LIMIT 15",
    [$user_id]
);

// ── Member duration ───────────────────────────────────────────
$joined_ts    = strtotime($user['created_at']);
$days_member  = max(0, floor((time() - $joined_ts) / 86400));

require_once 'includes/header.php';
?>

<style>
/* ── Profile Hero ─────────────────────────────────────────── */
.profile-hero {
  position: relative;
  border-radius: var(--radius-xl);
  overflow: hidden;
  margin-bottom: 22px;
  border: 1px solid var(--glass-border);
  animation: fadeUp .5s ease both;
}

.hero-banner {
  height: 130px;
  background: linear-gradient(135deg,
    rgba(108,99,255,0.4) 0%,
    rgba(167,139,250,0.2) 50%,
    rgba(244,114,182,0.25) 100%);
  position: relative;
  overflow: hidden;
}
.hero-banner::before {
  content: '';
  position: absolute; inset: 0;
  background: url("data:image/svg+xml,%3Csvg width='60' height='60' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='30' cy='30' r='1' fill='rgba(255,255,255,0.08)'/%3E%3C/svg%3E");
  background-size: 30px 30px;
}

.hero-body {
  background: var(--glass-bg);
  backdrop-filter: blur(24px);
  -webkit-backdrop-filter: blur(24px);
  padding: 0 32px 28px;
}

.hero-avatar-wrap {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-top: -52px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.hero-avatar {
  width: 100px; height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid var(--bg-deep);
  box-shadow: 0 0 0 2px var(--glass-border-lg), 0 8px 24px rgba(0,0,0,0.4);
  background: var(--bg-mid);
}

.hero-actions { display:flex; gap:8px; flex-wrap:wrap; align-items:center; }

.hero-name {
  font-family: 'Syne', sans-serif;
  font-size: 24px;
  font-weight: 800;
  color: var(--text-primary);
  letter-spacing: -0.4px;
  line-height: 1.2;
}
.hero-username {
  font-size: 14px;
  color: var(--accent-2);
  margin-top: 2px;
  font-weight: 500;
}
.hero-email {
  font-size: 13px;
  color: var(--text-secondary);
  margin-top: 6px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* ── Info Grid ────────────────────────────────────────────── */
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 22px;
}

.info-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  padding: 22px 24px;
  animation: fadeUp .5s ease both;
}

.info-card h3 {
  font-family: 'Syne', sans-serif;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-card h3 i { color: var(--accent-2); }

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px solid rgba(255,255,255,0.04);
  gap: 16px;
}
.info-row:last-child { border-bottom: none; padding-bottom: 0; }

.info-label {
  font-size: 12px;
  color: var(--text-muted);
  font-weight: 600;
  flex-shrink: 0;
  padding-top: 2px;
}

.info-value {
  font-size: 13.5px;
  color: var(--text-primary);
  text-align: right;
  word-break: break-all;
}

/* ── Quick Status Change ──────────────────────────────────── */
.status-panel {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  padding: 22px 24px;
  animation: fadeUp .5s ease both;
  animation-delay: .1s;
}

.status-panel h3 {
  font-family: 'Syne', sans-serif;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 1px;
  text-transform: uppercase;
  color: var(--text-muted);
  margin-bottom: 16px;
  display: flex; align-items:center; gap:8px;
}
.status-panel h3 i { color: var(--accent-2); }

.status-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.status-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  padding: 10px;
  border-radius: var(--radius-sm);
  font-size: 13px;
  font-weight: 600;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all var(--transition);
  font-family: 'DM Sans', sans-serif;
}
.status-btn.current { cursor: default; opacity: .5; }
.status-btn-active   { background:var(--success-bg); border-color:var(--success-border); color:var(--success); }
.status-btn-inactive { background:var(--glass-bg); border-color:var(--glass-border); color:var(--text-secondary); }
.status-btn-banned   { background:var(--danger-bg); border-color:var(--danger-border); color:var(--danger); }
.status-btn-pending  { background:var(--warning-bg); border-color:var(--warning-border); color:var(--warning); }

.status-btn:not(.current):hover { transform: translateY(-2px); filter: brightness(1.15); }

/* ── Timeline / Activity ──────────────────────────────────── */
.timeline { display: flex; flex-direction: column; gap: 0; }

.tl-item {
  display: flex;
  gap: 14px;
  padding: 13px 0;
  border-bottom: 1px solid rgba(255,255,255,0.04);
  position: relative;
}
.tl-item:last-child { border-bottom: none; }

.tl-dot {
  width: 30px; height: 30px;
  border-radius: 50%;
  background: rgba(108,99,255,0.15);
  border: 1px solid rgba(108,99,255,0.25);
  display: grid;
  place-items: center;
  font-size: 11px;
  color: var(--accent-2);
  flex-shrink: 0;
  margin-top: 2px;
}

.tl-body { flex: 1; }
.tl-action {
  font-size: 13px;
  color: var(--text-primary);
  font-weight: 500;
}
.tl-meta {
  font-size: 11px;
  color: var(--text-muted);
  margin-top: 3px;
  display: flex;
  gap: 10px;
}

.no-activity {
  text-align: center;
  padding: 32px;
  color: var(--text-muted);
  font-size: 13px;
}
.no-activity i {
  display: block;
  font-size: 28px;
  margin-bottom: 10px;
  opacity: .25;
}

@media (max-width: 900px) {
  .info-grid { grid-template-columns: 1fr; }
  .view-layout { grid-template-columns: 1fr !important; }
}
@media (max-width: 600px) {
  .hero-body { padding: 0 18px 22px; }
  .hero-name { font-size: 20px; }
  .status-buttons { grid-template-columns: 1fr 1fr; }
}
</style>

<!-- Flash -->
<?php if ($flash_success): ?>
  <div class="flash-alert flash-success">
    <i class="fas fa-circle-check"></i><span><?= htmlspecialchars($flash_success) ?></span>
  </div>
<?php endif; ?>
<?php if ($flash_error): ?>
  <div class="flash-alert flash-error">
    <i class="fas fa-circle-exclamation"></i><span><?= htmlspecialchars($flash_error) ?></span>
  </div>
<?php endif; ?>

<!-- Page Header -->
<div class="page-header">
  <div class="page-header-left">
    <h1>User <span style="color:var(--accent-2)">Profile</span></h1>
    <p>Viewing account details for <?= htmlspecialchars($user['full_name']) ?></p>
  </div>
  <div class="page-header-right">
    <a href="users.php" class="btn btn-glass btn-sm">
      <i class="fas fa-arrow-left"></i> Back to Users
    </a>
    <a href="user_edit.php?id=<?= $user_id ?>" class="btn btn-primary btn-sm">
      <i class="fas fa-pen-to-square"></i> Edit User
    </a>
  </div>
</div>

<!-- ── Profile Hero ─────────────────────────────────────────── -->
<div class="profile-hero">
  <div class="hero-banner"></div>
  <div class="hero-body">
    <div class="hero-avatar-wrap">
      <img src="assets/images/avatars/<?= htmlspecialchars($user['avatar'] ?? 'default_avatar.png') ?>"
           onerror="this.src='assets/images/Avatar.png'"
           class="hero-avatar" alt="<?= htmlspecialchars($user['full_name']) ?>" />
      <div class="hero-actions">
        <span class="badge badge-<?= $user['status'] ?>" style="font-size:12px;padding:5px 12px;">
          <?= ucfirst($user['status']) ?>
        </span>
        <?php if ($user['email_verified']): ?>
          <span class="badge" style="background:var(--info-bg);border-color:var(--info-border);color:var(--info);font-size:12px;padding:5px 12px;">
            <i class="fas fa-shield-check"></i> Verified
          </span>
        <?php else: ?>
          <span class="badge" style="background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning);font-size:12px;padding:5px 12px;">
            <i class="fas fa-triangle-exclamation"></i> Unverified
          </span>
        <?php endif; ?>
        <a href="user_edit.php?id=<?= $user_id ?>" class="btn btn-primary btn-sm">
          <i class="fas fa-pen"></i> Edit Profile
        </a>
      </div>
    </div>
    <div class="hero-name"><?= htmlspecialchars($user['full_name']) ?></div>
    <div class="hero-username">@<?= htmlspecialchars($user['username']) ?></div>
    <div class="hero-email">
      <i class="fas fa-envelope" style="color:var(--accent-2);font-size:12px;"></i>
      <?= htmlspecialchars($user['email']) ?>
    </div>
    <?php if ($user['bio']): ?>
      <div style="margin-top:12px;font-size:13.5px;color:var(--text-secondary);max-width:560px;line-height:1.6;">
        <?= nl2br(htmlspecialchars($user['bio'])) ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- ── Main Layout: left info + right sidebar ─────────────── -->
<div style="display:grid;grid-template-columns:1fr 300px;gap:20px;" class="view-layout">

  <!-- LEFT: Info Cards + Timeline -->
  <div style="display:flex;flex-direction:column;gap:20px;">

    <!-- Account Details -->
    <div class="info-card anim-delay-1">
      <h3><i class="fas fa-id-card"></i> Account Details</h3>

      <div class="info-row">
        <span class="info-label">User ID</span>
        <span class="info-value" style="font-family:'Syne',sans-serif;font-weight:700;color:var(--accent-2);">
          #<?= $user['id'] ?>
        </span>
      </div>
      <div class="info-row">
        <span class="info-label">Full Name</span>
        <span class="info-value"><?= htmlspecialchars($user['full_name']) ?></span>
      </div>
      <div class="info-row">
        <span class="info-label">Username</span>
        <span class="info-value" style="color:var(--accent-2);">@<?= htmlspecialchars($user['username']) ?></span>
      </div>
      <div class="info-row">
        <span class="info-label">Email</span>
        <span class="info-value"><?= htmlspecialchars($user['email']) ?></span>
      </div>
      <div class="info-row">
        <span class="info-label">Phone</span>
        <span class="info-value"><?= $user['phone'] ? htmlspecialchars($user['phone']) : '<span class="text-muted">Not provided</span>' ?></span>
      </div>
      <div class="info-row">
        <span class="info-label">Email Verified</span>
        <span class="info-value">
          <?php if ($user['email_verified']): ?>
            <span style="color:var(--success);font-weight:600;"><i class="fas fa-circle-check"></i> Yes</span>
          <?php else: ?>
            <span style="color:var(--warning);font-weight:600;"><i class="fas fa-circle-xmark"></i> No</span>
          <?php endif; ?>
        </span>
      </div>
    </div>

    <!-- Activity Details -->
    <div class="info-card anim-delay-2">
      <h3><i class="fas fa-chart-pulse"></i> Activity & Timestamps</h3>

      <div class="info-row">
        <span class="info-label">Member Since</span>
        <span class="info-value">
          <?= date('d M Y', strtotime($user['created_at'])) ?>
          <span style="color:var(--text-muted);font-size:12px;"> (<?= $days_member ?> days)</span>
        </span>
      </div>
      <div class="info-row">
        <span class="info-label">Last Login</span>
        <span class="info-value">
          <?= $user['last_login']
            ? date('d M Y, H:i', strtotime($user['last_login']))
            : '<span class="text-muted">Never logged in</span>' ?>
        </span>
      </div>
      <div class="info-row">
        <span class="info-label">Last Updated</span>
        <span class="info-value"><?= date('d M Y, H:i', strtotime($user['updated_at'])) ?></span>
      </div>
      <div class="info-row">
        <span class="info-label">Current Status</span>
        <span class="info-value">
          <span class="badge badge-<?= $user['status'] ?>"><?= ucfirst($user['status']) ?></span>
        </span>
      </div>
    </div>

    <!-- Admin Action Log for this user -->
    <div class="info-card anim-delay-3">
      <h3><i class="fas fa-clock-rotate-left"></i> Admin Actions on This Account</h3>

      <?php if (empty($user_log)): ?>
        <div class="no-activity">
          <i class="fas fa-shield-halved"></i>
          No admin actions recorded for this account yet.
        </div>
      <?php else: ?>
        <div class="timeline">
          <?php foreach ($user_log as $log): ?>
            <div class="tl-item">
              <div class="tl-dot"><i class="fas fa-shield-halved"></i></div>
              <div class="tl-body">
                <div class="tl-action">
                  <?= htmlspecialchars(ucwords(str_replace('_', ' ', $log['action']))) ?>
                </div>
                <?php if ($log['details']): ?>
                  <div style="font-size:12px;color:var(--text-secondary);margin-top:2px;">
                    <?= htmlspecialchars($log['details']) ?>
                  </div>
                <?php endif; ?>
                <div class="tl-meta">
                  <span><i class="fas fa-user-shield" style="font-size:10px;"></i> <?= htmlspecialchars($log['admin_name']) ?></span>
                  <span><i class="fas fa-clock" style="font-size:10px;"></i> <?= date('d M Y, H:i', strtotime($log['created_at'])) ?></span>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>

  </div>

  <!-- RIGHT: Status + Danger zone -->
  <div style="display:flex;flex-direction:column;gap:18px;">

    <!-- Quick Status Change -->
    <div class="status-panel">
      <h3><i class="fas fa-toggle-on"></i> Change Status</h3>

      <form method="POST" action="">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
        <div class="status-buttons">
          <?php foreach (['active','inactive','pending','banned'] as $s): ?>
            <button type="submit" name="quick_status" value="<?= $s ?>"
                    class="status-btn status-btn-<?= $s ?> <?= $user['status'] === $s ? 'current' : '' ?>"
                    <?= $user['status'] === $s ? 'disabled title="Current status"' : "onclick=\"return confirm('Set this user to {$s}?')\"" ?>>
              <i class="fas fa-<?= ['active'=>'circle-check','inactive'=>'circle-minus','banned'=>'ban','pending'=>'clock'][$s] ?>"></i>
              <?= ucfirst($s) ?>
              <?php if ($user['status'] === $s): ?>
                <i class="fas fa-check" style="margin-left:2px;font-size:10px;"></i>
              <?php endif; ?>
            </button>
          <?php endforeach; ?>
        </div>
      </form>

      <div style="margin-top:16px;padding-top:14px;border-top:1px solid var(--glass-border);">
        <div style="font-size:11px;color:var(--text-muted);line-height:1.6;">
          Current status: <strong style="color:var(--text-primary);"><?= ucfirst($user['status']) ?></strong><br>
          Changing status takes effect immediately.
        </div>
      </div>
    </div>

    <!-- Quick Links -->
    <div class="status-panel" style="animation-delay:.15s;">
      <h3><i class="fas fa-bolt"></i> Quick Actions</h3>
      <div style="display:flex;flex-direction:column;gap:8px;">
        <a href="user_edit.php?id=<?= $user_id ?>" class="btn btn-glass" style="justify-content:flex-start;">
          <i class="fas fa-pen-to-square" style="color:var(--accent-2)"></i> Edit Full Profile
        </a>
        <a href="user_edit.php?id=<?= $user_id ?>&tab=password" class="btn btn-glass" style="justify-content:flex-start;">
          <i class="fas fa-key" style="color:var(--warning)"></i> Reset Password
        </a>
        <a href="user_edit.php?id=<?= $user_id ?>&tab=avatar" class="btn btn-glass" style="justify-content:flex-start;">
          <i class="fas fa-image" style="color:var(--teal)"></i> Change Avatar
        </a>
        <a href="mailto:<?= htmlspecialchars($user['email']) ?>" class="btn btn-glass" style="justify-content:flex-start;">
          <i class="fas fa-envelope" style="color:var(--info)"></i> Send Email
        </a>
      </div>
    </div>

    <!-- Danger Zone -->
    <div class="status-panel" style="border-color:var(--danger-border);animation-delay:.2s;">
      <h3 style="color:var(--danger);"><i class="fas fa-triangle-exclamation"></i> Danger Zone</h3>
      <p style="font-size:12.5px;color:var(--text-secondary);margin-bottom:14px;line-height:1.6;">
        Permanently deleting a user cannot be undone. All their data will be lost.
      </p>
      <a href="user_delete.php?id=<?= $user_id ?>&csrf=<?= urlencode($csrf) ?>"
         class="btn btn-danger"
         style="width:100%;justify-content:center;"
         onclick="return confirm('PERMANENTLY delete <?= addslashes(htmlspecialchars($user['full_name'])) ?>?\n\nThis action cannot be undone.')">
        <i class="fas fa-trash"></i> Delete This User
      </a>
    </div>

  </div>
</div>

<?php require_once 'includes/footer.php'; ?>
