<?php
// ============================================================
//  profile.php — Admin Own Profile Management
//  Place in: /admin/profile.php
// ============================================================
require_once 'includes/auth_check.php';

$page_title  = 'My Profile';
$active_tab  = in_array($_GET['tab'] ?? '', ['password','avatar','sessions']) ? $_GET['tab'] : 'details';

// ── Flash ─────────────────────────────────────────────────────
$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'];

// ── Load full admin record ─────────────────────────────────────
$admin = db_fetch_one("SELECT * FROM admins WHERE id = ?", [$current_admin['id']]);

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

// ============================================================
//  HANDLE POST
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (($_POST['csrf_token'] ?? '') !== $csrf) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } else {
        $action = $_POST['action'] ?? '';

        // ── UPDATE DETAILS ────────────────────────────────────
        if ($action === 'update_details') {
            $full_name = trim($_POST['full_name'] ?? '');
            $username  = trim($_POST['username']  ?? '');
            $email     = trim($_POST['email']     ?? '');
            $phone     = trim($_POST['phone']     ?? '');

            if (empty($full_name)) $errors[] = 'Full name is required.';
            if (empty($username))  $errors[] = 'Username is required.';
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';

            if (empty($errors)) {
                $dup_u = db_fetch_one("SELECT id FROM admins WHERE username=? AND id!=?", [$username, $admin['id']]);
                $dup_e = db_fetch_one("SELECT id FROM admins WHERE email=? AND id!=?",    [$email,    $admin['id']]);
                if ($dup_u) $errors[] = "Username '@{$username}' is already taken.";
                if ($dup_e) $errors[] = "Email '{$email}' is already in use by another admin.";
            }

            if (empty($errors)) {
                db_execute(
                    "UPDATE admins SET full_name=?, username=?, email=?, phone=? WHERE id=?",
                    [$full_name, $username, $email, $phone ?: null, $admin['id']]
                );
                // Update session
                $_SESSION['admin_name']     = $full_name;
                $_SESSION['admin_username'] = $username;

                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'updated_own_profile', 'admin', ?, ?, 'Updated profile details', ?)",
                    [$admin['id'], $admin['id'], $full_name, $_SERVER['REMOTE_ADDR']]
                );

                $_SESSION['flash_success'] = 'Profile updated successfully.';
                header('Location: profile.php?tab=details');
                exit;
            }
            $active_tab = 'details';
        }

        // ── UPDATE PASSWORD ───────────────────────────────────
        if ($action === 'update_password') {
            $current_pw  = $_POST['current_password']  ?? '';
            $new_pw      = $_POST['new_password']       ?? '';
            $confirm_pw  = $_POST['confirm_password']   ?? '';

            // Verify current password first
            if (!password_verify($current_pw, $admin['password_hash'])) {
                $errors[] = 'Current password is incorrect.';
            }
            if (strlen($new_pw) < 8)                        $errors[] = 'New password must be at least 8 characters.';
            if (!preg_match('/[A-Z]/', $new_pw))             $errors[] = 'Must contain at least one uppercase letter.';
            if (!preg_match('/[0-9]/', $new_pw))             $errors[] = 'Must contain at least one number.';
            if (!preg_match('/[^A-Za-z0-9]/', $new_pw))     $errors[] = 'Must contain at least one special character.';
            if ($new_pw !== $confirm_pw)                     $errors[] = 'Passwords do not match.';
            if ($new_pw === $current_pw)                     $errors[] = 'New password must differ from current password.';

            if (empty($errors)) {
                $hash = password_hash($new_pw, PASSWORD_BCRYPT);
                db_execute("UPDATE admins SET password_hash=? WHERE id=?", [$hash, $admin['id']]);
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'changed_own_password', 'admin', ?, ?, 'Admin changed own password', ?)",
                    [$admin['id'], $admin['id'], $admin['full_name'], $_SERVER['REMOTE_ADDR']]
                );
                $_SESSION['flash_success'] = 'Password changed successfully. Please use your new password next login.';
                header('Location: profile.php?tab=password');
                exit;
            }
            $active_tab = 'password';
        }

        // ── UPDATE AVATAR ─────────────────────────────────────
        if ($action === 'update_avatar') {

            if (isset($_POST['remove_avatar'])) {
                $old = $admin['avatar'];
                if ($old && $old !== 'logo.png' && file_exists("assets/images/avatars/{$old}")) {
                    unlink("assets/images/avatars/{$old}");
                }
                db_execute("UPDATE admins SET avatar='logo.png' WHERE id=?", [$admin['id']]);
                $_SESSION['admin_avatar'] = 'logo.png';
                $_SESSION['flash_success'] = 'Avatar removed.';
                header('Location: profile.php?tab=avatar');
                exit;
            }

            if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
                $errors[] = 'Please select an image file to upload.';
            } else {
                $file    = $_FILES['avatar'];
                $ext     = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                $allowed = ['jpg','jpeg','png','gif','webp'];
                $max     = 2 * 1024 * 1024;

                if (!in_array($ext, $allowed))          $errors[] = 'Only JPG, PNG, WEBP or GIF allowed.';
                if ($file['size'] > $max)               $errors[] = 'File must be under 2MB.';
                if (!@getimagesize($file['tmp_name']))  $errors[] = 'File is not a valid image.';

                if (empty($errors)) {
                    $old = $admin['avatar'];
                    if ($old && $old !== 'logo.png') {
                        $old_path = "assets/images/avatars/{$old}";
                        if (file_exists($old_path)) unlink($old_path);
                    }

                    $new_filename = 'admin_' . $admin['id'] . '_' . time() . '.' . $ext;
                    $dest         = "assets/images/avatars/{$new_filename}";

                    if (move_uploaded_file($file['tmp_name'], $dest)) {
                        db_execute("UPDATE admins SET avatar=? WHERE id=?", [$new_filename, $admin['id']]);
                        $_SESSION['admin_avatar'] = $new_filename;

                        db_execute(
                            "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                             VALUES (?, 'updated_own_avatar', 'admin', ?, ?, 'Admin updated profile avatar', ?)",
                            [$admin['id'], $admin['id'], $admin['full_name'], $_SERVER['REMOTE_ADDR']]
                        );

                        $_SESSION['flash_success'] = 'Avatar updated successfully.';
                        header('Location: profile.php?tab=avatar');
                        exit;
                    } else {
                        $errors[] = 'Failed to save image. Check folder permissions.';
                    }
                }
            }
            $active_tab = 'avatar';
        }
    }
}

// ── Reload fresh admin data ───────────────────────────────────
$admin = db_fetch_one("SELECT * FROM admins WHERE id = ?", [$current_admin['id']]);

// ── Stats for profile card ────────────────────────────────────
$total_actions   = db_fetch_one("SELECT COUNT(*) AS c FROM activity_log WHERE admin_id=?", [$admin['id']])['c'] ?? 0;
$users_managed   = db_fetch_one(
    "SELECT COUNT(DISTINCT target_id) AS c FROM activity_log
     WHERE admin_id=? AND target_type='user'", [$admin['id']]
)['c'] ?? 0;
$days_as_admin   = max(0, floor((time() - strtotime($admin['created_at'])) / 86400));

// ── Own activity log ──────────────────────────────────────────
$own_activity = db_fetch_all(
    "SELECT action, target_type, target_name, details, ip_address, created_at
     FROM activity_log WHERE admin_id=?
     ORDER BY created_at DESC LIMIT 20",
    [$admin['id']]
);

// ── All admins list (for super admin awareness) ───────────────
$all_admins = ($current_admin['role'] === 'super_admin')
    ? db_fetch_all("SELECT id, full_name, username, email, role, status, last_login, created_at FROM admins ORDER BY role DESC, created_at ASC")
    : [];

require_once 'includes/header.php';
?>

<style>
/* ════════════════════════════════════════════════════════════
   PROFILE PAGE STYLES
════════════════════════════════════════════════════════════ */

/* ── Profile Hero ────────────────────────────────────────── */
.profile-hero-wrap {
  position: relative;
  margin-bottom: 28px;
  animation: fadeUp .5s ease both;
}

.profile-banner {
  height: 160px;
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
  background:
    linear-gradient(135deg, rgba(108,99,255,.5) 0%, rgba(167,139,250,.2) 40%, rgba(45,212,191,.25) 100%);
  position: relative;
  overflow: hidden;
}

.profile-banner::before {
  content: '';
  position: absolute; inset: 0;
  background-image: radial-gradient(circle at 20% 50%, rgba(108,99,255,.4) 0%, transparent 50%),
                    radial-gradient(circle at 80% 20%, rgba(244,114,182,.3) 0%, transparent 40%);
}

/* Animated shimmer on banner */
.profile-banner::after {
  content: '';
  position: absolute; inset: 0;
  background: linear-gradient(105deg, transparent 40%, rgba(255,255,255,.06) 50%, transparent 60%);
  animation: shimmer 3.5s ease-in-out infinite;
  background-size: 200% 100%;
}

@keyframes shimmer {
  0%   { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

.profile-body {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-top: none;
  border-radius: 0 0 var(--radius-xl) var(--radius-xl);
  backdrop-filter: blur(24px);
  -webkit-backdrop-filter: blur(24px);
  padding: 0 36px 28px;
}

.profile-avatar-row {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-top: -56px;
  margin-bottom: 18px;
  flex-wrap: wrap;
  gap: 14px;
}

.profile-avatar-frame {
  position: relative;
  display: inline-block;
}

.profile-avatar {
  width: 110px; height: 110px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid var(--bg-deep);
  box-shadow: 0 0 0 2px var(--glass-border-lg), 0 10px 30px rgba(0,0,0,.5);
  display: block;
  transition: transform .3s ease;
}

.profile-avatar:hover { transform: scale(1.03); }

.profile-avatar-ring {
  position: absolute; inset: -6px;
  border-radius: 50%;
  background: conic-gradient(var(--accent) 0deg, var(--accent-2) 120deg, var(--pink) 240deg, var(--accent) 360deg);
  z-index: -1;
  animation: spin-ring 6s linear infinite;
}

@keyframes spin-ring { to { transform: rotate(360deg); } }

.profile-badge-wrap {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.role-badge {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 6px 14px;
  border-radius: 30px;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: .5px;
}

.role-super {
  background: linear-gradient(135deg, rgba(244,114,182,.2), rgba(167,139,250,.2));
  border: 1px solid rgba(244,114,182,.35);
  color: var(--pink);
}

.role-admin {
  background: rgba(108,99,255,.15);
  border: 1px solid rgba(108,99,255,.3);
  color: var(--accent-2);
}

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

/* Stats row inside hero */
.profile-stats-row {
  display: flex;
  gap: 0;
  margin-top: 20px;
  border-top: 1px solid var(--glass-border);
  padding-top: 18px;
  flex-wrap: wrap;
}

.pstat {
  flex: 1;
  text-align: center;
  padding: 0 20px;
  border-right: 1px solid var(--glass-border);
  min-width: 100px;
}
.pstat:last-child { border-right: none; }

.pstat-value {
  font-family: 'Syne', sans-serif;
  font-size: 26px;
  font-weight: 800;
  color: var(--text-primary);
  letter-spacing: -1px;
  line-height: 1;
}
.pstat-label { font-size: 11.5px; color: var(--text-muted); margin-top: 4px; font-weight: 500; }

/* ── Tabs ────────────────────────────────────────────────── */
.profile-tabs {
  display: flex;
  gap: 4px;
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-md);
  padding: 4px;
  margin-bottom: 22px;
  overflow-x: auto;
  flex-wrap: nowrap;
  scrollbar-width: none;
}
.profile-tabs::-webkit-scrollbar { display: none; }

.ptab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-secondary);
  text-decoration: none;
  transition: all var(--transition);
  border: 1px solid transparent;
  white-space: nowrap;
  flex-shrink: 0;
}
.ptab:hover { color: var(--text-primary); background: var(--glass-bg-hover); }
.ptab.active {
  background: rgba(108,99,255,.2);
  border-color: rgba(108,99,255,.3);
  color: var(#F48340);
}
.ptab i { font-size: 13px; }

/* ── Form sections ───────────────────────────────────────── */
.profile-form-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  animation: fadeUp .5s ease both;
}

.pfc-header {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 22px 26px 20px;
  border-bottom: 1px solid var(--glass-border);
  background: rgba(255,255,255,.02);
}

.pfc-icon {
  width: 42px; height: 42px;
  border-radius: 13px;
  display: grid; place-items: center;
  font-size: 16px;
  flex-shrink: 0;
}

.pfc-title    { font-family: 'Syne', sans-serif; font-size: 17px; font-weight: 700; color: var(--text-primary); }
.pfc-subtitle { font-size: 12px; color: var(--text-muted); margin-top: 2px; }

.pfc-body     { padding: 26px; }

.form-row-2   { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }

.pfc-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 22px;
  margin-top: 22px;
  border-top: 1px solid var(--glass-border);
}

/* ── Password rules ──────────────────────────────────────── */
.pw-strength  { height: 5px; background: rgba(255,255,255,.06); border-radius: 10px; overflow: hidden; margin-top: 9px; }
.pw-bar       { height: 100%; border-radius: 10px; width: 0; transition: width .3s, background .3s; }

.pw-rules     { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; margin-top: 14px; }
.pw-rule      { display: flex; align-items: center; gap: 7px; font-size: 12px; color: var(--text-muted); transition: color .2s; }
.pw-rule.pass { color: var(--success); }
.pw-rule i    { font-size: 11px; width: 14px; text-align: center; }

/* ── Avatar tab ──────────────────────────────────────────── */
.avatar-current-row {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 18px;
  background: rgba(108,99,255,.06);
  border: 1px solid rgba(108,99,255,.15);
  border-radius: var(--radius-md);
  margin-bottom: 20px;
}

.avatar-current-img {
  width: 72px; height: 72px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid var(--glass-border-lg);
  box-shadow: 0 4px 20px rgba(0,0,0,.3);
  flex-shrink: 0;
}

.avatar-drop-zone {
  border: 2px dashed var(--glass-border);
  border-radius: var(--radius-md);
  padding: 40px 20px;
  text-align: center;
  position: relative;
  cursor: pointer;
  background: var(--glass-bg);
  transition: all var(--transition);
}
.avatar-drop-zone:hover,
.avatar-drop-zone.drag { border-color: var(--accent); background: rgba(235, 171, 74, 0.87); }
.avatar-drop-zone input { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; }
.drop-icon { font-size: 36px; color: var(--accent-2); margin-bottom: 12px; display: block; animation: bounce 2s ease infinite; }
@keyframes bounce { 0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)} }
.drop-text { font-size: 15px; color: var(--text-secondary); font-weight: 500; }
.drop-sub  { font-size: 12px; color: var(--text-muted); margin-top: 5px; }

.avatar-new-preview {
  display: none;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
  padding: 14px 18px;
  background: var(--success-bg);
  border: 1px solid var(--success-border);
  border-radius: var(--radius-md);
}
.avatar-new-preview img {
  width: 56px; height: 56px; border-radius: 50%; object-fit: cover;
  border: 2px solid var(--success-border);
}

/* ── Activity timeline ───────────────────────────────────── */
.act-timeline { display: flex; flex-direction: column; }

.act-item {
  display: flex;
  gap: 14px;
  padding: 14px 0;
  border-bottom: 1px solid rgba(255,255,255,.04);
  animation: fadeUp .4s ease both;
}
.act-item:last-child { border-bottom: none; }

.act-icon {
  width: 34px; height: 34px; border-radius: 10px;
  display: grid; place-items: center; font-size: 13px;
  flex-shrink: 0; margin-top: 2px;
}

.act-body { flex: 1; }
.act-title { font-size: 13.5px; color: var(--text-primary); font-weight: 500; }
.act-detail { font-size: 12px; color: var(--text-secondary); margin-top: 2px; }
.act-meta   { font-size: 11px; color: var(--text-muted); margin-top: 4px; display: flex; gap: 12px; flex-wrap: wrap; }

/* ── Danger zone section ─────────────────────────────────── */
.danger-card {
  background: rgba(248,113,113,.04);
  border: 1px solid var(--danger-border);
  border-radius: var(--radius-lg);
  padding: 24px;
  margin-top: 22px;
  animation: fadeUp .5s ease both;
  animation-delay: .15s;
}
.danger-card h3 {
  font-family: 'Syne', sans-serif;
  font-size: 15px;
  font-weight: 700;
  color: var(--danger);
  margin-bottom: 6px;
  display: flex; align-items: center; gap: 8px;
}
.danger-card p { font-size: 13px; color: var(--text-secondary); line-height: 1.6; margin-bottom: 16px; }

/* Pass toggle button */
.ptoggle {
  position: absolute; right: 13px; top: 50%; transform: translateY(-50%);
  background: none; border: none; color: var(--text-secondary);
  cursor: pointer; font-size: 14px; padding: 4px; transition: color .2s;
}
.ptoggle:hover { color: var(--accent-2); }

/* Security info box */
.security-box {
  background: var(--info-bg);
  border: 1px solid var(--info-border);
  border-radius: var(--radius-md);
  padding: 14px 18px;
  font-size: 13px;
  color: #7dd3fc;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  line-height: 1.6;
  margin-bottom: 22px;
}

/* Error list */
.error-list {
  background: var(--danger-bg);
  border: 1px solid var(--danger-border);
  border-radius: var(--radius-md);
  padding: 14px 18px;
  margin-bottom: 22px;
}
.error-list li {
  font-size: 13px; color: #fca5a5;
  display: flex; align-items: center; gap: 8px;
  padding: 3px 0; list-style: none;
}

/* Action icon colour mapping */
.icon-login    { background:rgba(52,211,153,.12);  color:var(--success); }
.icon-logout   { background:rgba(248,113,113,.12); color:var(--danger); }
.icon-edit     { background:rgba(108,99,255,.12);  color:var(--accent-2); }
.icon-password { background:rgba(251,191,36,.12);  color:var(--warning); }
.icon-avatar   { background:rgba(45,212,191,.12);  color:var(--teal); }
.icon-user     { background:rgba(167,139,250,.12); color:var(--accent-2); }
.icon-default  { background:rgba(255,255,255,.06); color:var(--text-muted); }

@media (max-width: 768px) {
  .profile-body    { padding: 0 20px 22px; }
  .profile-name    { font-size: 20px; }
  .pstat           { padding: 0 12px; }
  .form-row-2      { grid-template-columns: 1fr; }
  .pw-rules        { grid-template-columns: 1fr; }
  .profile-stats-row { gap: 0; }
}
</style>

<!-- Flash messages -->
<?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; ?>

<!-- Error list from POST -->
<?php if (!empty($errors)): ?>
  <div class="error-list">
    <ul>
      <?php foreach ($errors as $e): ?>
        <li><i class="fas fa-circle-exclamation"></i><?= htmlspecialchars($e) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<!-- Page header -->
<div class="page-header">
  <div class="page-header-left">
    <h1>My <span style="color:#F48340">Profile</span></h1>
    <p>Manage your admin account settings and security preferences</p>
  </div>
</div>

<!-- ═══════════════════════════════════════
     PROFILE HERO CARD
════════════════════════════════════════ -->
<div class="profile-hero-wrap">
  <div class="profile-banner"></div>
  <div class="profile-body">

    <div class="profile-avatar-row">
      <!-- Avatar with animated ring -->
      <div class="profile-avatar-frame">
        <div class="profile-avatar-ring"></div>
        <img src="assets/images/avatars/<?= htmlspecialchars($admin['avatar'] ?? 'logo.png') ?>"
             onerror="this.src='assets/images/logo.png'"
             class="profile-avatar" id="heroAvatar"
             alt="<?= htmlspecialchars($admin['full_name']) ?>" />
      </div>

      <!-- Badges -->
      <div class="profile-badge-wrap">
        <span class="role-badge <?= $admin['role']==='super_admin' ? 'role-super' : 'role-admin' ?>">
          <i class="fas fa-<?= $admin['role']==='super_admin' ? 'crown' : 'shield-halved' ?>"></i>
          <?= $admin['role']==='super_admin' ? 'Super Admin' : 'Admin' ?>
        </span>
        <span class="badge badge-active" style="font-size:12px;padding:5px 12px;">
          <i class="fas fa-wifi"></i> Online
        </span>
        <a href="profile.php?tab=avatar" class="btn btn-glass btn-sm">
          <i class="fas fa-camera"></i> Change Photo
        </a>
      </div>
    </div>

    <!-- Name + info -->
    <div class="profile-name"><?= htmlspecialchars($admin['full_name']) ?></div>
    <div class="profile-handle">@<?= htmlspecialchars($admin['username']) ?></div>
    <div class="profile-email">
      <i class="fas fa-envelope" style="color:var(--accent-2);font-size:12px;"></i>
      <?= htmlspecialchars($admin['email']) ?>
      <?php if ($admin['phone']): ?>
        &nbsp;·&nbsp;
        <i class="fas fa-phone" style="color:var(--teal);font-size:12px;"></i>
        <?= htmlspecialchars($admin['phone']) ?>
      <?php endif; ?>
    </div>

    <!-- Stats strip -->
    <div class="profile-stats-row">
      <div class="pstat">
        <div class="pstat-value"><?= number_format($total_actions) ?></div>
        <div class="pstat-label">Total Actions</div>
      </div>
      <div class="pstat">
        <div class="pstat-value"><?= number_format($users_managed) ?></div>
        <div class="pstat-label">Users Managed</div>
      </div>
      <div class="pstat">
        <div class="pstat-value"><?= $days_as_admin ?></div>
        <div class="pstat-label">Days as Admin</div>
      </div>
      <div class="pstat">
        <div class="pstat-value">
          <?= $admin['last_login'] ? date('d M', strtotime($admin['last_login'])) : '—' ?>
        </div>
        <div class="pstat-label">Last Login</div>
      </div>
    </div>

  </div>
</div>

<!-- ═══════════════════════════════════════
     TABS
════════════════════════════════════════ -->
<div class="profile-tabs">
  <a href="profile.php?tab=details"  class="ptab <?= $active_tab==='details'  ?'active':'' ?>">
    <i class="fas fa-id-badge"></i> Profile Details
  </a>
  <a href="profile.php?tab=password" class="ptab <?= $active_tab==='password' ?'active':'' ?>">
    <i class="fas fa-lock"></i> Security & Password
  </a>
  <a href="profile.php?tab=avatar"   class="ptab <?= $active_tab==='avatar'   ?'active':'' ?>">
    <i class="fas fa-image"></i> Avatar
  </a>
  <a href="profile.php?tab=sessions" class="ptab <?= $active_tab==='sessions' ?'active':'' ?>">
    <i class="fas fa-clock-rotate-left"></i> My Activity
  </a>
</div>

<!-- ═══════════════════════════════════════
     TAB: DETAILS
════════════════════════════════════════ -->
<?php if ($active_tab === 'details'): ?>
<div class="profile-form-card">
  <div class="pfc-header">
    <div class="pfc-icon" style="background:rgba(108,99,255,.15);color:var(--accent-2);">
      <i class="fas fa-id-badge"></i>
    </div>
    <div>
      <div class="pfc-title">Profile Details</div>
      <div class="pfc-subtitle">Update your name, username, email and phone number</div>
    </div>
  </div>
  <div class="pfc-body">
    <form method="POST" action="" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
      <input type="hidden" name="action" value="update_details" />

      <div class="form-row-2">
        <div class="form-group">
          <label class="form-label">Full Name <span style="color:var(--danger)">*</span></label>
          <input type="text" name="full_name" class="form-control"
                 value="<?= htmlspecialchars($_POST['full_name'] ?? $admin['full_name']) ?>"
                 placeholder="Your full name" required />
        </div>
        <div class="form-group">
          <label class="form-label">Username <span style="color:var(--danger)">*</span></label>
          <div style="position:relative;">
            <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);">@</span>
            <input type="text" name="username" class="form-control" style="padding-left:28px;"
                   value="<?= htmlspecialchars($_POST['username'] ?? $admin['username']) ?>"
                   placeholder="adminhandle" required />
          </div>
        </div>
      </div>

      <div class="form-row-2">
        <div class="form-group">
          <label class="form-label">Email Address <span style="color:var(--danger)">*</span></label>
          <input type="email" name="email" class="form-control"
                 value="<?= htmlspecialchars($_POST['email'] ?? $admin['email']) ?>"
                 placeholder="you@domain.com" required />
        </div>
        <div class="form-group">
          <label class="form-label">Phone Number</label>
          <input type="tel" name="phone" class="form-control"
                 value="<?= htmlspecialchars($_POST['phone'] ?? $admin['phone'] ?? '') ?>"
                 placeholder="+1 555 000 0000" />
        </div>
      </div>

      <!-- Read-only role / status info -->
      <div class="form-row-2">
        <div class="form-group">
          <label class="form-label">Role</label>
          <div class="form-control" style="display:flex;align-items:center;gap:8px;cursor:default;opacity:.8;">
            <i class="fas fa-<?= $admin['role']==='super_admin'?'crown':'shield-halved' ?>"
               style="color:var(--<?= $admin['role']==='super_admin'?'pink':'accent-2' ?>)"></i>
            <?= $admin['role']==='super_admin' ? 'Super Admin' : 'Admin' ?>
          </div>
          <div style="font-size:11px;color:var(--text-muted);margin-top:5px;">
            Role can only be changed by a Super Admin.
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">Account Status</label>
          <div class="form-control" style="display:flex;align-items:center;gap:8px;cursor:default;opacity:.8;">
            <span class="badge badge-<?= $admin['status'] ?>">
              <?= ucfirst($admin['status']) ?>
            </span>
          </div>
        </div>
      </div>

      <div class="pfc-footer">
        <span style="font-size:12px;color:var(--text-muted);">
          <i class="fas fa-clock" style="margin-right:4px;"></i>
          Last updated: <?= date('d M Y, H:i', strtotime($admin['updated_at'])) ?>
        </span>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-floppy-disk"></i> Save Changes
        </button>
      </div>
    </form>
  </div>
</div>

<!-- ═══════════════════════════════════════
     TAB: PASSWORD
════════════════════════════════════════ -->
<?php elseif ($active_tab === 'password'): ?>
<div class="profile-form-card">
  <div class="pfc-header">
    <div class="pfc-icon" style="background:rgba(251,191,36,.15);color:var(--warning);">
      <i class="fas fa-lock"></i>
    </div>
    <div>
      <div class="pfc-title">Security & Password</div>
      <div class="pfc-subtitle">Change your admin account password</div>
    </div>
  </div>
  <div class="pfc-body">

    <div class="security-box">
      <i class="fas fa-shield-halved" style="flex-shrink:0;margin-top:2px;font-size:16px;"></i>
      <span>
        You must enter your <strong>current password</strong> to set a new one.
        Your new password must be at least 8 characters and include an uppercase letter, a number, and a special character.
      </span>
    </div>

    <form method="POST" action="" id="profilePwForm" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
      <input type="hidden" name="action" value="update_password" />

      <div class="form-group">
        <label class="form-label">Current Password <span style="color:var(--danger)">*</span></label>
        <div style="position:relative;">
          <input type="password" name="current_password" id="currentPw" class="form-control"
                 style="padding-right:44px;" placeholder="Enter your current password"
                 autocomplete="current-password" />
          <button type="button" class="ptoggle" onclick="togglePw('currentPw',this)">
            <i class="fas fa-eye"></i>
          </button>
        </div>
      </div>

      <div style="height:1px;background:var(--glass-border);margin:20px 0;"></div>

      <div class="form-group">
        <label class="form-label">New Password <span style="color:var(--danger)">*</span></label>
        <div style="position:relative;">
          <input type="password" name="new_password" id="newPw" class="form-control"
                 style="padding-right:44px;" placeholder="Minimum 8 characters"
                 autocomplete="new-password" />
          <button type="button" class="ptoggle" onclick="togglePw('newPw',this)">
            <i class="fas fa-eye"></i>
          </button>
        </div>
        <div class="pw-strength"><div class="pw-bar" id="pwBar"></div></div>
        <div class="pw-rules">
          <div class="pw-rule" id="rl-len">  <i class="fas fa-circle"></i> Min 8 characters</div>
          <div class="pw-rule" id="rl-up">   <i class="fas fa-circle"></i> Uppercase letter</div>
          <div class="pw-rule" id="rl-num">  <i class="fas fa-circle"></i> Number (0–9)</div>
          <div class="pw-rule" id="rl-spec"> <i class="fas fa-circle"></i> Special char (!@#…)</div>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">Confirm New Password <span style="color:var(--danger)">*</span></label>
        <div style="position:relative;">
          <input type="password" name="confirm_password" id="confirmPw" class="form-control"
                 style="padding-right:44px;" placeholder="Repeat the new password"
                 autocomplete="new-password" />
          <button type="button" class="ptoggle" onclick="togglePw('confirmPw',this)">
            <i class="fas fa-eye"></i>
          </button>
        </div>
        <div id="matchMsg" style="font-size:12px;margin-top:7px;min-height:18px;"></div>
      </div>

      <div class="pfc-footer">
        <a href="profile.php" class="btn btn-glass">Cancel</a>
        <button type="submit" class="btn btn-primary" id="pwSubmitBtn">
          <i class="fas fa-lock"></i> Update Password
        </button>
      </div>
    </form>

  </div>
</div>

<!-- ═══════════════════════════════════════
     TAB: AVATAR
════════════════════════════════════════ -->
<?php elseif ($active_tab === 'avatar'): ?>
<div class="profile-form-card">
  <div class="pfc-header">
    <div class="pfc-icon" style="background:rgba(45,212,191,.15);color:var(--teal);">
      <i class="fas fa-image"></i>
    </div>
    <div>
      <div class="pfc-title">Profile Avatar</div>
      <div class="pfc-subtitle">Upload a photo for your admin account (max 2MB)</div>
    </div>
  </div>
  <div class="pfc-body">

    <!-- Current avatar -->
    <div class="avatar-current-row">
      <img src="assets/images/avatars/<?= htmlspecialchars($admin['avatar'] ?? 'logo.png') ?>"
           onerror="this.src='assets/images/logo.png'"
           id="currentAvatarImg" class="avatar-current-img" alt="Current avatar" />
      <div>
        <div style="font-size:14px;font-weight:600;color:var(--text-primary);">Your Current Avatar</div>
        <div style="font-size:12px;color:var(--text-muted);margin-top:3px;">
          <?= htmlspecialchars($admin['avatar'] ?? 'logo.png') ?>
        </div>
        <div style="font-size:12px;color:var(--accent-2);margin-top:5px;">
          <i class="fas fa-circle-info"></i> Shown in sidebar, topbar, and activity logs across the panel
        </div>
      </div>
    </div>

    <form method="POST" enctype="multipart/form-data" action="">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
      <input type="hidden" name="action" value="update_avatar" />

      <div class="avatar-drop-zone" id="dropZone">
        <input type="file" name="avatar" id="avatarFileInput" accept="image/*" />
        <i class="fas fa-cloud-arrow-up drop-icon"></i>
        <div class="drop-text">Click to browse or drag & drop your photo here</div>
        <div class="drop-sub">Supports JPG, PNG, WEBP, GIF — maximum 2MB</div>
      </div>

      <!-- New preview -->
      <div class="avatar-new-preview" id="newPreview">
        <img id="newPreviewImg" src="" alt="Preview" />
        <div>
          <div style="font-size:13.5px;font-weight:600;color:var(--success);">
            <i class="fas fa-circle-check"></i> Ready to upload
          </div>
          <div id="newPreviewMeta" style="font-size:12px;color:var(--text-secondary);margin-top:3px;"></div>
        </div>
      </div>

      <div class="pfc-footer">
        <button type="submit" name="remove_avatar" value="1"
                class="btn btn-danger"
                onclick="return confirm('Remove your avatar and use the default image?')"
                <?= ($admin['avatar']==='logo.png' || !$admin['avatar']) ? 'disabled' : '' ?>>
          <i class="fas fa-trash"></i> Remove
        </button>
        <button type="submit" id="uploadAvatarBtn" class="btn btn-primary" disabled>
          <i class="fas fa-cloud-arrow-up"></i> Upload Avatar
        </button>
      </div>
    </form>

  </div>
</div>

<!-- ═══════════════════════════════════════
     TAB: MY ACTIVITY
════════════════════════════════════════ -->
<?php elseif ($active_tab === 'sessions'): ?>
<div class="profile-form-card">
  <div class="pfc-header">
    <div class="pfc-icon" style="background:rgba(56,189,248,.15);color:var(--info);">
      <i class="fas fa-clock-rotate-left"></i>
    </div>
    <div>
      <div class="pfc-title">My Recent Activity</div>
      <div class="pfc-subtitle">Last 20 actions performed under your admin account</div>
    </div>
  </div>
  <div class="pfc-body" style="padding-top:8px;">

    <?php if (empty($own_activity)): ?>
      <div style="text-align:center;padding:40px 20px;color:var(--text-muted);">
        <i class="fas fa-clock-rotate-left" style="font-size:32px;opacity:.2;display:block;margin-bottom:12px;"></i>
        No activity recorded yet for your account.
      </div>
    <?php else: ?>
      <div class="act-timeline">
        <?php
        // Determine icon class based on action keyword
        function act_icon_class(string $action): array {
          if (str_contains($action,'login'))    return ['icon-login',   'fa-right-to-bracket'];
          if (str_contains($action,'logout'))   return ['icon-logout',  'fa-right-from-bracket'];
          if (str_contains($action,'password')) return ['icon-password','fa-key'];
          if (str_contains($action,'avatar'))   return ['icon-avatar',  'fa-image'];
          if (str_contains($action,'profile'))  return ['icon-edit',    'fa-pen-to-square'];
          if (str_contains($action,'user'))     return ['icon-user',    'fa-user'];
          if (str_contains($action,'delete'))   return ['icon-logout',  'fa-trash'];
          if (str_contains($action,'export'))   return ['icon-edit',    'fa-file-arrow-down'];
          return ['icon-default','fa-circle'];
        }
        foreach ($own_activity as $i => $log):
          [$icon_cls, $icon_fa] = act_icon_class($log['action']);
        ?>
          <div class="act-item" style="animation-delay:<?= $i * 0.04 ?>s;">
            <div class="act-icon <?= $icon_cls ?>">
              <i class="fas <?= $icon_fa ?>"></i>
            </div>
            <div class="act-body">
              <div class="act-title">
                <?= htmlspecialchars(ucwords(str_replace('_',' ', $log['action']))) ?>
                <?php if ($log['target_name']): ?>
                  <span style="color:var(--text-secondary);font-weight:400;"> — <?= htmlspecialchars($log['target_name']) ?></span>
                <?php endif; ?>
              </div>
              <?php if ($log['details']): ?>
                <div class="act-detail"><?= htmlspecialchars($log['details']) ?></div>
              <?php endif; ?>
              <div class="act-meta">
                <span><i class="fas fa-clock" style="font-size:10px;"></i> <?= date('d M Y, H:i', strtotime($log['created_at'])) ?></span>
                <?php if ($log['ip_address']): ?>
                  <span><i class="fas fa-location-dot" style="font-size:10px;"></i> <?= htmlspecialchars($log['ip_address']) ?></span>
                <?php endif; ?>
                <?php if ($log['target_type']): ?>
                  <span style="text-transform:capitalize;"><i class="fas fa-tag" style="font-size:10px;"></i> <?= htmlspecialchars($log['target_type']) ?></span>
                <?php endif; ?>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

  </div>
</div>
<?php endif; ?>

<!-- Danger zone (always visible below any tab) -->
<?php if ($active_tab === 'details'): ?>
<div class="danger-card">
  <h3><i class="fas fa-triangle-exclamation"></i> Account Security</h3>
  <p>
    If you believe your account has been compromised, sign out all sessions immediately.
    Contact your system administrator to reset or deactivate this account.
  </p>
  <div style="display:flex;gap:10px;flex-wrap:wrap;">
    <a href="logout.php" class="btn btn-danger btn-sm"
       onclick="return confirm('Sign out of your current session?')">
      <i class="fas fa-right-from-bracket"></i> Sign Out Now
    </a>
    <a href="profile.php?tab=password" class="btn btn-glass btn-sm">
      <i class="fas fa-lock"></i> Change Password
    </a>
  </div>
</div>
<?php endif; ?>

<?php
$extra_scripts = <<<'JS'
<script>
// ── Password visibility toggle ──────────────────────────────
function togglePw(id, btn) {
  const inp  = document.getElementById(id);
  const icon = btn.querySelector('i');
  const show = inp.type === 'password';
  inp.type   = show ? 'text' : 'password';
  icon.className = show ? 'fas fa-eye-slash' : 'fas fa-eye';
}

// ── Password strength ───────────────────────────────────────
const newPw     = document.getElementById('newPw');
const confirmPw = document.getElementById('confirmPw');
const pwBar     = document.getElementById('pwBar');
const matchMsg  = document.getElementById('matchMsg');

const rules = {
  len:  { el: document.getElementById('rl-len'),  fn: v => v.length >= 8 },
  up:   { el: document.getElementById('rl-up'),   fn: v => /[A-Z]/.test(v) },
  num:  { el: document.getElementById('rl-num'),  fn: v => /[0-9]/.test(v) },
  spec: { el: document.getElementById('rl-spec'), fn: v => /[^A-Za-z0-9]/.test(v) },
};

newPw?.addEventListener('input', () => {
  const v  = newPw.value;
  let pass = 0;
  for (const k in rules) {
    const ok = rules[k].fn(v);
    rules[k].el?.classList.toggle('pass', ok);
    const ico = rules[k].el?.querySelector('i');
    if (ico) ico.className = ok ? 'fas fa-circle-check' : 'fas fa-circle';
    if (ok) pass++;
  }
  const pct    = (pass / 4) * 100;
  const colors = ['', '#f87171', '#fbbf24', '#a78bfa', '#34d399'];
  if (pwBar) {
    pwBar.style.width      = pct + '%';
    pwBar.style.background = colors[pass];
  }
  checkMatch();
});

confirmPw?.addEventListener('input', checkMatch);

function checkMatch() {
  if (!confirmPw || !matchMsg || !confirmPw.value) {
    if (matchMsg) matchMsg.innerHTML = '';
    return;
  }
  const ok = newPw.value === confirmPw.value;
  matchMsg.innerHTML = ok
    ? '<span style="color:var(--success)"><i class="fas fa-circle-check"></i> Passwords match</span>'
    : '<span style="color:var(--danger)"><i class="fas fa-circle-xmark"></i> Passwords do not match</span>';
}

// ── Avatar upload preview ───────────────────────────────────
const fileInput     = document.getElementById('avatarFileInput');
const dropZone      = document.getElementById('dropZone');
const newPreview    = document.getElementById('newPreview');
const newPreviewImg = document.getElementById('newPreviewImg');
const newPreviewMeta= document.getElementById('newPreviewMeta');
const uploadBtn     = document.getElementById('uploadAvatarBtn');
const heroAvatar    = document.getElementById('heroAvatar');

fileInput?.addEventListener('change', showPreview);

function showPreview() {
  const file = fileInput.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = e => {
    if (newPreviewImg)  newPreviewImg.src = e.target.result;
    if (newPreviewMeta) newPreviewMeta.textContent = file.name + ' · ' + (file.size/1024).toFixed(1) + ' KB';
    if (newPreview)     newPreview.style.display = 'flex';
    if (uploadBtn)      uploadBtn.disabled = false;
    // Live update hero + sidebar avatar
    if (heroAvatar) heroAvatar.src = e.target.result;
    document.querySelectorAll('.topbar-avatar, .sp-avatar img').forEach(img => img.src = e.target.result);
  };
  reader.readAsDataURL(file);
}

// Drag & drop
dropZone?.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag'); });
dropZone?.addEventListener('dragleave', () => dropZone.classList.remove('drag'));
dropZone?.addEventListener('drop', e => {
  e.preventDefault();
  dropZone.classList.remove('drag');
  if (e.dataTransfer.files.length) {
    fileInput.files = e.dataTransfer.files;
    showPreview();
  }
});
</script>
JS;

require_once 'includes/footer.php';
?>
