<?php
// ============================================================
//  user/profile.php — Wadata User Profile
// ============================================================
session_start();
require_once '../includes/db.php';

if (empty($_SESSION['user_id'])) { header('Location: login.php'); exit; }

$user = db_fetch_one("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']]);
if (!$user) { session_destroy(); header('Location: login.php'); exit; }

if (empty($_SESSION['user_csrf'])) { $_SESSION['user_csrf'] = bin2hex(random_bytes(32)); }

$flash_success = $flash_error = '';

// ── Handle POST ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['user_csrf']) {
        $flash_error = 'Invalid request.';
    } else {
        $action = $_POST['action'] ?? '';

        if ($action === 'update_profile') {
            $full_name = trim($_POST['full_name'] ?? '');
            $username  = trim($_POST['username']  ?? '');
            $phone     = trim($_POST['phone']     ?? '');
            $bio       = trim($_POST['bio']       ?? '');

            $errors = [];
            if (strlen($full_name) < 2) $errors[] = 'Full name too short.';
            if (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $username)) $errors[] = 'Invalid username format.';

            // Check username uniqueness (exclude self)
            $taken = db_fetch_one("SELECT id FROM users WHERE username = ? AND id != ? LIMIT 1", [$username, $user['id']]);
            if ($taken) $errors[] = 'Username already taken.';

            if (empty($errors)) {
                db_execute(
                    "UPDATE users SET full_name=?, username=?, phone=?, bio=?, updated_at=NOW() WHERE id=?",
                    [$full_name, $username, $phone, $bio, $user['id']]
                );
                $_SESSION['user_name']     = $full_name;
                $_SESSION['user_username'] = $username;
                $user = db_fetch_one("SELECT * FROM users WHERE id=?", [$user['id']]);
                $flash_success = 'Profile updated successfully!';
            } else {
                $flash_error = implode(' ', $errors);
            }
        }

        elseif ($action === 'change_password') {
            $current = $_POST['current_password'] ?? '';
            $new_pw  = $_POST['new_password']     ?? '';
            $confirm = $_POST['confirm_password'] ?? '';

            if (!password_verify($current, $user['password_hash'])) {
                $flash_error = 'Current password is incorrect.';
            } elseif (strlen($new_pw) < 8) {
                $flash_error = 'New password must be at least 8 characters.';
            } elseif ($new_pw !== $confirm) {
                $flash_error = 'New passwords do not match.';
            } else {
                db_execute("UPDATE users SET password_hash=?, updated_at=NOW() WHERE id=?",
                    [password_hash($new_pw, PASSWORD_BCRYPT), $user['id']]);
                $flash_success = 'Password changed successfully!';
            }
        }

        elseif ($action === 'upload_avatar') {
            $file = $_FILES['avatar'] ?? null;
            if ($file && $file['error'] === UPLOAD_ERR_OK) {
                $allowed = ['image/jpeg','image/png','image/webp','image/gif'];
                $size    = $file['size'];
                $type    = mime_content_type($file['tmp_name']);

                if (!in_array($type, $allowed))     $flash_error = 'Only JPG, PNG, WebP, GIF allowed.';
                elseif ($size > 2 * 1024 * 1024)    $flash_error = 'Image must be under 2MB.';
                elseif (!getimagesize($file['tmp_name'])) $flash_error = 'Invalid image file.';
                else {
                    $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
                    $filename = 'user_' . $user['id'] . '_' . time() . '.' . $ext;
                    $dest     = '../assets/images/avatars/' . $filename;

                    if (move_uploaded_file($file['tmp_name'], $dest)) {
                        // Delete old avatar
                        if ($user['avatar'] && $user['avatar'] !== 'default_avatar.png') {
                            @unlink('../assets/images/avatars/' . $user['avatar']);
                        }
                        db_execute("UPDATE users SET avatar=?, updated_at=NOW() WHERE id=?", [$filename, $user['id']]);
                        $_SESSION['user_avatar'] = $filename;
                        $user = db_fetch_one("SELECT * FROM users WHERE id=?", [$user['id']]);
                        $flash_success = 'Avatar updated successfully!';
                    } else {
                        $flash_error = 'Upload failed. Check folder permissions.';
                    }
                }
            }
        }
    }
}

$avatar_src = (!empty($user['avatar']) && $user['avatar'] !== 'default_avatar.png')
    ? '../assets/images/avatars/' . htmlspecialchars($user['avatar'])
    : '../assets/images/avatars/default_avatar.png';

$member_since = date('d F Y', strtotime($user['created_at']));
$initials     = strtoupper(substr($user['full_name'], 0, 1));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>My Profile — WADATA Skills Acquisition Center</title>
<link rel="icon" type="image/png" href="../assets/img/logo.png"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"/>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Epilogue:wght@700;800&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../assets/css/style.css"/>
<style>
:root {
  --primary:#0B2545; --primary-l:#1e3a5f;
  --accent:#FF6A00;  --accent-l:#ff8533;
  --light:#F6F9FC;   --page:#EDF4FC;
  --glass:rgba(255,255,255,.72); --glass2:rgba(255,255,255,.50); --glass3:rgba(255,255,255,.30);
  --bdr:rgba(255,255,255,.82);   --bdr2:rgba(11,37,69,.12);
  --sh:0 4px 24px rgba(11,37,69,.09),0 1px 4px rgba(0,0,0,.04);
  --sh2:0 16px 48px rgba(11,37,69,.13);
  --sh-inp:0 0 0 3px rgba(255,106,0,.20);
  --th:#0B2545; --tb:#2D3E5E; --tm:#6C7E9A;
  --mesh:rgba(11,37,69,.032);
  --w:250px; --top:62px; --rad:16px; --rads:10px; --radxs:7px;
  --t:.22s cubic-bezier(.22,1,.36,1);
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;font-family:'Plus Jakarta Sans',sans-serif;background:var(--page);color:var(--tb)}

.scene{position:fixed;inset:0;z-index:0;overflow:hidden;pointer-events:none}
.scene::before{content:'';position:absolute;inset:0;
  background:radial-gradient(ellipse 65% 55% at 3% 6%,rgba(255,106,0,.16),transparent 55%),
             radial-gradient(ellipse 60% 65% at 97% 95%,rgba(11,37,69,.12),transparent 55%)}
.scene::after{content:'';position:absolute;inset:0;
  background-image:linear-gradient(var(--mesh) 1px,transparent 1px),linear-gradient(90deg,var(--mesh) 1px,transparent 1px);
  background-size:56px 56px}
.orb{position:absolute;border-radius:50%;filter:blur(88px);animation:drift ease-in-out infinite alternate;pointer-events:none}
.oa{width:450px;height:450px;background:radial-gradient(#ff8533,transparent 70%);top:-150px;left:-80px;opacity:.38;animation-duration:16s}
.ob{width:350px;height:350px;background:radial-gradient(#1e3a5f,transparent 70%);bottom:-90px;right:-60px;opacity:.28;animation-duration:13s;animation-delay:-6s}
@keyframes drift{0%{transform:translate(0,0) scale(1)}100%{transform:translate(38px,26px) scale(1.07)}}

.shell{position:relative;z-index:1;display:flex;height:100vh;overflow:hidden}

/* ── SIDEBAR (same as dashboard) ────────────────────────── */
.sidebar{width:var(--w);flex-shrink:0;background:var(--glass);border-right:1px solid var(--bdr);
  backdrop-filter:blur(36px) saturate(200%);-webkit-backdrop-filter:blur(36px) saturate(200%);
  box-shadow:4px 0 28px rgba(0,0,0,.06);display:flex;flex-direction:column;overflow:hidden}
.sb-top{padding:18px 18px 14px;border-bottom:1px solid var(--bdr2);display:flex;align-items:center;gap:11px}
.sb-logo{width:36px;height:36px;border-radius:10px;overflow:hidden;background:#fff;padding:4px;
  box-shadow:0 3px 12px rgba(255,106,0,.2);flex-shrink:0;display:grid;place-items:center}
.sb-logo img{width:100%;height:100%;object-fit:contain}
.sb-logo .fb{width:100%;height:100%;border-radius:7px;background:linear-gradient(135deg,var(--accent),var(--primary));display:grid;place-items:center;color:#fff;font-size:14px}
.sb-name strong{display:block;font-family:'Epilogue',sans-serif;font-size:14px;font-weight:800;color:var(--th)}
.sb-name em{font-style:normal;font-size:9px;font-weight:700;letter-spacing:1.8px;text-transform:uppercase;color:var(--accent)}
.sb-nav{padding:8px 10px;flex:1;overflow-y:auto;scrollbar-width:none}
.sb-nav::-webkit-scrollbar{display:none}
.sbl{font-size:9px;font-weight:800;letter-spacing:2px;text-transform:uppercase;color:var(--tm);padding:14px 10px 5px}
.sln{display:flex;align-items:center;gap:10px;padding:9px 12px;border-radius:var(--rads);
  font-size:12.5px;font-weight:600;color:var(--tb);text-decoration:none;cursor:pointer;
  transition:all var(--t);margin-bottom:2px;border:1px solid transparent;position:relative}
.sln:hover{background:rgba(255,255,255,.78);color:var(--th)}
.sln.on{background:linear-gradient(135deg,rgba(255,106,0,.14),rgba(11,37,69,.08));
  border-color:rgba(255,106,0,.18);color:var(--accent)}
.sln.on::before{content:'';position:absolute;left:0;top:22%;bottom:22%;width:3px;border-radius:3px;background:linear-gradient(to bottom,var(--accent),var(--primary))}
.sln i{width:16px;text-align:center;font-size:13px;flex-shrink:0}
.sb-foot{padding:12px;border-top:1px solid var(--bdr2)}
.sb-user{display:flex;align-items:center;gap:9px;padding:9px 11px;border-radius:var(--rads);
  background:rgba(255,255,255,.55);border:1px solid var(--bdr2);transition:all var(--t);cursor:pointer;text-decoration:none}
.sb-user:hover{background:rgba(255,255,255,.80)}
.sb-av{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid var(--bdr);flex-shrink:0}
.sb-av-fb{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--primary));
  display:grid;place-items:center;color:#fff;font-size:11px;font-weight:800;flex-shrink:0;border:2px solid var(--bdr)}
.sb-ui strong{display:block;font-size:11.5px;font-weight:700;color:var(--th);line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}
.sb-ui span{font-size:10px;color:var(--tm)}

/* ── MAIN ───────────────────────────────────────────────── */
.main{flex:1;display:flex;flex-direction:column;overflow:hidden}
.topbar{height:var(--top);flex-shrink:0;background:rgba(255,255,255,.75);border-bottom:1px solid var(--bdr2);
  backdrop-filter:blur(32px) saturate(180%);-webkit-backdrop-filter:blur(32px) saturate(180%);
  display:flex;align-items:center;justify-content:space-between;padding:0 26px;gap:16px}
.tb-l{display:flex;align-items:center;gap:14px}
.tb-bc{font-size:12.5px;color:var(--tm)}.tb-bc strong{color:var(--th);font-weight:700}
.tb-r{display:flex;align-items:center;gap:9px}
.tbb{width:34px;height:34px;border-radius:var(--radxs);background:rgba(255,255,255,.88);
  border:1px solid var(--bdr2);display:grid;place-items:center;cursor:pointer;font-size:13px;color:var(--tb);transition:all var(--t)}
.tbb:hover{background:rgba(255,255,255,1);color:var(--th)}

.content{flex:1;overflow-y:auto;padding:22px 26px;scrollbar-width:thin;scrollbar-color:var(--bdr2) transparent}
.content::-webkit-scrollbar{width:5px}
.content::-webkit-scrollbar-thumb{background:var(--bdr2);border-radius:10px}

/* ── PROFILE HERO ───────────────────────────────────────── */
.hero-banner{
  background:linear-gradient(130deg,var(--accent) 0%,var(--accent-l) 38%,var(--primary) 100%);
  border-radius:var(--rad);padding:28px 28px 36px;position:relative;overflow:hidden;
  margin-bottom:0;animation:fadeUp .5s ease both;box-shadow:0 8px 30px rgba(255,106,0,.25)}
.hero-banner::before{content:'';position:absolute;width:260px;height:260px;border-radius:50%;
  background:rgba(255,255,255,.07);right:-60px;top:-80px;pointer-events:none}
.hero-banner::after{content:'';position:absolute;width:140px;height:140px;border-radius:50%;
  background:rgba(255,255,255,.05);left:30%;bottom:-50px;pointer-events:none}

.profile-hero-inner{display:flex;align-items:flex-end;gap:20px;position:relative;z-index:1}
.ph-av-wrap{position:relative;flex-shrink:0}
.ph-av{width:80px;height:80px;border-radius:50%;object-fit:cover;
  border:3px solid rgba(255,255,255,.7);box-shadow:0 6px 22px rgba(0,0,0,.2)}
.ph-av-fb{width:80px;height:80px;border-radius:50%;background:rgba(255,255,255,.25);
  display:grid;place-items:center;color:#fff;font-size:28px;font-weight:800;
  border:3px solid rgba(255,255,255,.7);box-shadow:0 6px 22px rgba(0,0,0,.2)}
.ph-av-upload{position:absolute;bottom:-2px;right:-2px;width:26px;height:26px;
  background:var(--accent);border:2px solid #fff;border-radius:50%;
  display:grid;place-items:center;cursor:pointer;font-size:10px;color:#fff;transition:all .2s}
.ph-av-upload:hover{transform:scale(1.1);background:var(--primary)}
.ph-info h2{font-family:'Epilogue',sans-serif;font-size:22px;font-weight:800;color:#fff;margin-bottom:3px}
.ph-info p{font-size:12.5px;color:rgba(255,255,255,.82)}
.ph-chips{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}
.ph-chip{display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:20px;
  background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.3);
  font-size:11px;font-weight:700;color:#fff}

/* ── TABS ───────────────────────────────────────────────── */
.tabs-wrap{display:flex;gap:2px;padding:12px 20px;
  background:var(--glass);border:1px solid var(--bdr);border-radius:0 0 var(--rad) var(--rad);
  border-top:none;box-shadow:var(--sh);margin-bottom:20px;backdrop-filter:blur(32px);-webkit-backdrop-filter:blur(32px)}
.tab-btn{padding:8px 18px;border-radius:var(--rads);font-size:12.5px;font-weight:700;
  color:var(--tm);background:none;border:1px solid transparent;cursor:pointer;transition:all var(--t)}
.tab-btn:hover{background:rgba(255,255,255,.60);color:var(--th)}
.tab-btn.on{background:linear-gradient(135deg,rgba(255,106,0,.14),rgba(11,37,69,.08));
  border-color:rgba(255,106,0,.18);color:var(--accent)}
.tab-pane{display:none;animation:fadeUp .4s ease both}
.tab-pane.on{display:block}

/* ── GLASS CARD ─────────────────────────────────────────── */
.gc{background:var(--glass);border:1px solid var(--bdr);border-radius:var(--rad);
  backdrop-filter:blur(32px) saturate(180%);-webkit-backdrop-filter:blur(32px) saturate(180%);
  box-shadow:var(--sh);animation:fadeUp .5s ease both}
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
.gc-hd{display:flex;align-items:center;justify-content:space-between;padding:16px 20px 12px;border-bottom:1px solid var(--bdr2)}
.gc-t{font-family:'Epilogue',sans-serif;font-size:14px;font-weight:800;color:var(--th)}
.gc-bd{padding:20px}

/* ── FORM ───────────────────────────────────────────────── */
.fg{margin-bottom:16px}
.fl{display:block;font-size:11px;font-weight:800;letter-spacing:.9px;text-transform:uppercase;color:var(--tm);margin-bottom:6px}
.iw{position:relative}
.ii{position:absolute;left:13px;top:50%;transform:translateY(-50%);font-size:12.5px;color:var(--tm);pointer-events:none;transition:color .2s}
.fi{width:100%;background:rgba(255,255,255,.88);border:1.5px solid var(--bdr2);border-radius:11px;
  padding:11px 14px 11px 40px;color:var(--th);font-family:'Plus Jakarta Sans',sans-serif;
  font-size:13.5px;font-weight:500;outline:none;transition:border-color .22s,box-shadow .22s;-webkit-appearance:none}
.fi::placeholder{color:var(--tm);font-weight:400}
.fi:focus{border-color:var(--accent);box-shadow:var(--sh-inp)}
.iw:focus-within .ii{color:var(--accent)}
.fi.no-ico{padding-left:14px}
.pt{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--tm);cursor:pointer;font-size:12px;padding:4px;transition:color .2s}
.pt:hover{color:var(--accent)}
.ht{padding-right:38px}
.fg2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
textarea.fi{padding-top:11px;resize:vertical;min-height:80px;padding-left:14px}

/* Strength */
.strength-bars{display:flex;gap:3px;margin:6px 0 4px}
.sb2{height:4px;flex:1;border-radius:3px;background:var(--bdr2);transition:background .3s}
.strength-txt{font-size:10px;font-weight:700;color:var(--tm)}

/* Btn */
.btn-s{padding:12px 28px;background:linear-gradient(130deg,var(--accent) 0%,var(--accent-l) 45%,var(--primary) 100%);
  background-size:200% 100%;background-position:0 0;border:none;border-radius:11px;color:#fff;
  font-family:'Epilogue',sans-serif;font-size:14px;font-weight:800;cursor:pointer;
  display:inline-flex;align-items:center;gap:8px;
  transition:background-position .45s,transform .2s,box-shadow .2s;box-shadow:0 5px 22px rgba(255,106,0,.35)}
.btn-s:hover{background-position:100% 0;transform:translateY(-2px);box-shadow:0 8px 28px rgba(255,106,0,.45)}
.btn-s:active{transform:none}

/* Alert */
.al{display:flex;align-items:flex-start;gap:9px;padding:12px 15px;border-radius:12px;
  font-size:13px;font-weight:600;margin-bottom:18px;animation:alIn .3s ease both}
@keyframes alIn{from{opacity:0;transform:translateY(-5px)}to{opacity:1;transform:none}}
.ae{background:rgba(220,38,38,.08);border:1px solid rgba(220,38,38,.22);color:#991B1B}
.as{background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.25);color:#065F46}

/* Avatar drop zone */
.av-drop{border:2px dashed var(--bdr2);border-radius:16px;padding:28px;text-align:center;
  transition:all .2s;cursor:pointer;background:rgba(255,255,255,.50)}
.av-drop:hover,.av-drop.drag{border-color:var(--accent);background:rgba(255,106,0,.05)}
.av-drop img{width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--bdr);margin:0 auto 14px;display:block}
.av-drop .av-fb{width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--primary));
  display:grid;place-items:center;color:#fff;font-size:28px;font-weight:800;margin:0 auto 14px;border:3px solid var(--bdr)}

/* Status chip */
.s-chip{display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:20px;font-size:10.5px;font-weight:700}
.s-chip::before{content:'';width:5px;height:5px;border-radius:50%;flex-shrink:0}
.s-active{background:rgba(16,185,129,.12);color:#059669;border:1px solid rgba(16,185,129,.22)}.s-active::before{background:#10B981}
.s-pending{background:rgba(240,165,0,.12);color:#92400E;border:1px solid rgba(240,165,0,.22)}.s-pending::before{background:#F59E0B}

/* Info row */
.info-row{display:flex;align-items:center;gap:12px;padding:11px 0;border-bottom:1px solid var(--bdr2);font-size:13px}
.info-row:last-child{border-bottom:none;padding-bottom:0}
.info-row i{width:16px;text-align:center;color:var(--accent);font-size:12px;flex-shrink:0}
.info-label{color:var(--tm);font-weight:600;min-width:100px;font-size:11.5px}
.info-val{color:var(--th);font-weight:600}

@media(max-width:700px){.sidebar{display:none}.content{padding:14px}}
@media(max-width:580px){.fg2{grid-template-columns:1fr}}
</style>
</head>
<body>

<div class="scene"><div class="orb oa"></div><div class="orb ob"></div></div>

<div class="shell">

  <!-- SIDEBAR -->
  <aside class="sidebar">
    <div class="sb-top">
      <div class="sb-logo">
        <img src="../assets/img/logo.png" alt="Wadata"
             onerror="this.parentElement.innerHTML='<div class=fb><i class=\'fas fa-graduation-cap\'></i></div>'"/>
      </div>
      <div class="sb-name"><strong>WADATA</strong><em>Skill Center</em></div>
    </div>
    <nav class="sb-nav">
      <div class="sbl">My Learning</div>
      <a class="sln" href="dashboard.php"><i class="fas fa-gauge-high"></i> Dashboard</a>
      <a class="sln on" href="profile.php"><i class="fas fa-circle-user"></i> My Profile</a>
      <a class="sln" href="#"><i class="fas fa-book-open"></i> My Programmes</a>
      <a class="sln" href="#"><i class="fas fa-certificate"></i> Certifications</a>
      <a class="sln" href="#"><i class="fas fa-calendar-check"></i> Schedule</a>
      <div class="sbl" style="margin-top:6px">Resources</div>
      <a class="sln" href="#"><i class="fas fa-chalkboard-user"></i> Instructors</a>
      <a class="sln" href="#"><i class="fas fa-comments"></i> Support</a>
      <a class="sln" href="../index.php"><i class="fas fa-house"></i> Main Website</a>
      <a class="sln" href="logout.php" onclick="return confirm('Sign out?')" style="color:#DC2626;margin-top:4px">
        <i class="fas fa-right-from-bracket"></i> Sign Out
      </a>
    </nav>
    <div class="sb-foot">
      <div class="sb-user">
        <?php if (!empty($user['avatar']) && $user['avatar'] !== 'default_avatar.png'): ?>
          <img src="<?= $avatar_src ?>" class="sb-av" alt=""/>
        <?php else: ?>
          <div class="sb-av-fb"><?= $initials ?></div>
        <?php endif; ?>
        <div class="sb-ui">
          <strong><?= htmlspecialchars($user['full_name']) ?></strong>
          <span>@<?= htmlspecialchars($user['username']) ?></span>
        </div>
      </div>
    </div>
  </aside>

  <!-- MAIN -->
  <div class="main">
    <header class="topbar">
      <div class="tb-l">
        <div class="tb-bc">Wadata / <a href="dashboard.php" style="color:var(--tm);text-decoration:none">Dashboard</a> / <strong>My Profile</strong></div>
      </div>
      <div class="tb-r">
        <div class="tbb" title="Notifications"><i class="fas fa-bell"></i></div>
        <a href="dashboard.php" class="tbb" title="Dashboard"><i class="fas fa-gauge-high"></i></a>
      </div>
    </header>

    <div class="content">

      <?php if ($flash_success): ?>
        <div class="al as"><i class="fas fa-circle-check"></i><?= htmlspecialchars($flash_success) ?></div>
      <?php endif; ?>
      <?php if ($flash_error): ?>
        <div class="al ae"><i class="fas fa-circle-exclamation"></i><?= htmlspecialchars($flash_error) ?></div>
      <?php endif; ?>

      <!-- HERO BANNER -->
      <div class="hero-banner">
        <div class="profile-hero-inner">
          <div class="ph-av-wrap">
            <?php if (!empty($user['avatar']) && $user['avatar'] !== 'default_avatar.png'): ?>
              <img src="<?= $avatar_src ?>" class="ph-av" alt=""/>
            <?php else: ?>
              <div class="ph-av-fb"><?= $initials ?></div>
            <?php endif; ?>
            <label for="quick-av-upload" class="ph-av-upload" title="Change photo">
              <i class="fas fa-camera"></i>
            </label>
          </div>
          <div class="ph-info">
            <h2><?= htmlspecialchars($user['full_name']) ?></h2>
            <p>@<?= htmlspecialchars($user['username']) ?> · Member since <?= $member_since ?></p>
            <div class="ph-chips">
              <span class="ph-chip"><i class="fas fa-<?= $user['email_verified'] ? 'circle-check' : 'circle-xmark' ?>"></i>
                Email <?= $user['email_verified'] ? 'Verified' : 'Unverified' ?></span>
              <span class="ph-chip s-chip s-<?= $user['status'] ?>"><?= ucfirst($user['status']) ?></span>
            </div>
          </div>
        </div>
      </div>

      <!-- Quick avatar upload form (hidden, triggered by camera icon) -->
      <form method="POST" enctype="multipart/form-data" id="quick-av-form" style="display:none">
        <input type="hidden" name="csrf"   value="<?= htmlspecialchars($_SESSION['user_csrf']) ?>"/>
        <input type="hidden" name="action" value="upload_avatar"/>
        <input type="file" id="quick-av-upload" name="avatar" accept="image/*" onchange="document.getElementById('quick-av-form').submit()"/>
      </form>

      <!-- TABS -->
      <div class="tabs-wrap">
        <button class="tab-btn on" onclick="switchTab('details',this)"><i class="fas fa-id-card"></i> Details</button>
        <button class="tab-btn"    onclick="switchTab('password',this)"><i class="fas fa-key"></i> Password</button>
        <button class="tab-btn"    onclick="switchTab('avatar',this)"><i class="fas fa-image"></i> Avatar</button>
        <button class="tab-btn"    onclick="switchTab('account',this)"><i class="fas fa-circle-info"></i> Account Info</button>
      </div>

      <!-- TAB: DETAILS -->
      <div id="tab-details" class="tab-pane on">
        <div class="gc" style="animation-delay:.05s">
          <div class="gc-hd"><div class="gc-t">Profile Details</div></div>
          <div class="gc-bd">
            <form method="POST">
              <input type="hidden" name="csrf"   value="<?= htmlspecialchars($_SESSION['user_csrf']) ?>"/>
              <input type="hidden" name="action" value="update_profile"/>

              <div class="fg2">
                <div class="fg" style="margin-bottom:0">
                  <label class="fl" for="full_name">Full Name</label>
                  <div class="iw">
                    <input type="text" id="full_name" name="full_name" class="fi"
                           value="<?= htmlspecialchars($user['full_name']) ?>" required/>
                    <i class="fas fa-user ii"></i>
                  </div>
                </div>
                <div class="fg" style="margin-bottom:0">
                  <label class="fl" for="username">Username</label>
                  <div class="iw">
                    <input type="text" id="username" name="username" class="fi"
                           value="<?= htmlspecialchars($user['username']) ?>" required/>
                    <i class="fas fa-at ii"></i>
                  </div>
                </div>
              </div>
              <div style="margin-bottom:16px"></div>

              <div class="fg">
                <label class="fl">Email Address</label>
                <div class="iw">
                  <input type="email" class="fi" value="<?= htmlspecialchars($user['email']) ?>" disabled
                         style="opacity:.6;cursor:not-allowed"/>
                  <i class="fas fa-envelope ii"></i>
                </div>
                <div style="font-size:10.5px;color:var(--tm);margin-top:4px">
                  <i class="fas fa-info-circle" style="color:var(--accent)"></i> Contact admin to change your email address.
                </div>
              </div>

              <div class="fg">
                <label class="fl" for="phone">Phone Number</label>
                <div class="iw">
                  <input type="tel" id="phone" name="phone" class="fi" placeholder="+234 xxx xxx xxxx"
                         value="<?= htmlspecialchars($user['phone'] ?? '') ?>"/>
                  <i class="fas fa-phone ii"></i>
                </div>
              </div>

              <div class="fg">
                <label class="fl" for="bio">Short Bio <span style="color:var(--tm);font-weight:400">(optional)</span></label>
                <textarea id="bio" name="bio" class="fi no-ico" placeholder="Tell us a little about yourself…"><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>
              </div>

              <button type="submit" class="btn-s"><i class="fas fa-floppy-disk"></i> Save Changes</button>
            </form>
          </div>
        </div>
      </div>

      <!-- TAB: PASSWORD -->
      <div id="tab-password" class="tab-pane">
        <div class="gc" style="animation-delay:.05s">
          <div class="gc-hd"><div class="gc-t">Change Password</div></div>
          <div class="gc-bd">
            <form method="POST" style="max-width:480px">
              <input type="hidden" name="csrf"   value="<?= htmlspecialchars($_SESSION['user_csrf']) ?>"/>
              <input type="hidden" name="action" value="change_password"/>

              <div class="fg">
                <label class="fl" for="current_password">Current Password</label>
                <div class="iw">
                  <input type="password" id="current_password" name="current_password" class="fi ht"
                         placeholder="Your current password" required/>
                  <i class="fas fa-lock ii"></i>
                  <button type="button" class="pt" onclick="toggle('current_password','ci1')"><i class="fas fa-eye" id="ci1"></i></button>
                </div>
              </div>
              <div class="fg">
                <label class="fl" for="new_password">New Password</label>
                <div class="iw">
                  <input type="password" id="new_password" name="new_password" class="fi ht"
                         placeholder="Min. 8 characters" required oninput="strength2(this.value)"/>
                  <i class="fas fa-lock ii"></i>
                  <button type="button" class="pt" onclick="toggle('new_password','ci2')"><i class="fas fa-eye" id="ci2"></i></button>
                </div>
                <div class="strength-bars">
                  <div class="sb2" id="p1"></div><div class="sb2" id="p2"></div>
                  <div class="sb2" id="p3"></div><div class="sb2" id="p4"></div>
                </div>
                <div class="strength-txt" id="ptxt">Enter new password</div>
              </div>
              <div class="fg">
                <label class="fl" for="confirm_password">Confirm New Password</label>
                <div class="iw">
                  <input type="password" id="confirm_password" name="confirm_password" class="fi ht"
                         placeholder="Repeat new password" required oninput="matchCheck2()"/>
                  <i class="fas fa-lock ii"></i>
                  <button type="button" class="pt" onclick="toggle('confirm_password','ci3')"><i class="fas fa-eye" id="ci3"></i></button>
                </div>
                <div id="match2" style="font-size:10.5px;font-weight:700;margin-top:4px"></div>
              </div>
              <button type="submit" class="btn-s"><i class="fas fa-key"></i> Update Password</button>
            </form>
          </div>
        </div>
      </div>

      <!-- TAB: AVATAR -->
      <div id="tab-avatar" class="tab-pane">
        <div class="gc" style="animation-delay:.05s">
          <div class="gc-hd"><div class="gc-t">Profile Photo</div></div>
          <div class="gc-bd" style="max-width:440px">
            <form method="POST" enctype="multipart/form-data" id="av-form">
              <input type="hidden" name="csrf"   value="<?= htmlspecialchars($_SESSION['user_csrf']) ?>"/>
              <input type="hidden" name="action" value="upload_avatar"/>

              <label for="avatar-input" class="av-drop" id="av-drop">
                <?php if (!empty($user['avatar']) && $user['avatar'] !== 'default_avatar.png'): ?>
                  <img src="<?= $avatar_src ?>" alt="" id="av-preview"/>
                <?php else: ?>
                  <div class="av-fb" id="av-preview-fb"><?= $initials ?></div>
                <?php endif; ?>
                <div style="font-size:13px;font-weight:700;color:var(--th);margin-bottom:4px">Click to upload or drag & drop</div>
                <div style="font-size:11px;color:var(--tm)">JPG, PNG, WebP, GIF · Max 2MB</div>
                <input type="file" id="avatar-input" name="avatar" accept="image/*" style="display:none" onchange="previewAv(this)"/>
              </label>

              <div style="margin-top:16px;display:flex;gap:10px;align-items:center">
                <button type="submit" class="btn-s" id="av-save" style="display:none">
                  <i class="fas fa-floppy-disk"></i> Save Photo
                </button>
                <?php if (!empty($user['avatar']) && $user['avatar'] !== 'default_avatar.png'): ?>
                  <span style="font-size:12px;color:var(--tm)">Current photo active</span>
                <?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- TAB: ACCOUNT INFO -->
      <div id="tab-account" class="tab-pane">
        <div class="gc" style="animation-delay:.05s">
          <div class="gc-hd"><div class="gc-t">Account Information</div></div>
          <div class="gc-bd">
            <div class="info-row"><i class="fas fa-id-badge"></i><span class="info-label">User ID</span><span class="info-val">#<?= $user['id'] ?></span></div>
            <div class="info-row"><i class="fas fa-user"></i><span class="info-label">Full Name</span><span class="info-val"><?= htmlspecialchars($user['full_name']) ?></span></div>
            <div class="info-row"><i class="fas fa-at"></i><span class="info-label">Username</span><span class="info-val">@<?= htmlspecialchars($user['username']) ?></span></div>
            <div class="info-row"><i class="fas fa-envelope"></i><span class="info-label">Email</span><span class="info-val"><?= htmlspecialchars($user['email']) ?></span></div>
            <div class="info-row"><i class="fas fa-phone"></i><span class="info-label">Phone</span><span class="info-val"><?= $user['phone'] ? htmlspecialchars($user['phone']) : '—' ?></span></div>
            <div class="info-row"><i class="fas fa-shield-halved"></i><span class="info-label">Status</span>
              <span class="s-chip s-<?= $user['status'] ?>"><?= ucfirst($user['status']) ?></span></div>
            <div class="info-row"><i class="fas fa-envelope-circle-check"></i><span class="info-label">Email Verified</span>
              <span style="color:<?= $user['email_verified'] ? '#059669' : '#DC2626' ?>;font-weight:700">
                <?= $user['email_verified'] ? 'Yes ✓' : 'No ✗' ?></span></div>
            <div class="info-row"><i class="fas fa-calendar-plus"></i><span class="info-label">Member Since</span><span class="info-val"><?= date('d F Y', strtotime($user['created_at'])) ?></span></div>
            <div class="info-row"><i class="fas fa-clock"></i><span class="info-label">Last Updated</span>
              <span class="info-val"><?= $user['updated_at'] ? date('d F Y, H:i', strtotime($user['updated_at'])) : '—' ?></span></div>
            <div class="info-row"><i class="fas fa-right-to-bracket"></i><span class="info-label">Last Login</span>
              <span class="info-val"><?= $user['last_login'] ? date('d F Y, H:i', strtotime($user['last_login'])) : 'First visit' ?></span></div>
          </div>
        </div>
      </div>

    </div><!-- /content -->
  </div><!-- /main -->
</div><!-- /shell -->

<script>
// Tab switching
function switchTab(name, btn) {
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('on'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('on'));
  document.getElementById('tab-' + name).classList.add('on');
  btn.classList.add('on');
}

// Password toggle
function toggle(id, icoId) {
  const p = document.getElementById(id), i = document.getElementById(icoId), s = p.type === 'password';
  p.type = s ? 'text' : 'password'; i.className = s ? 'fas fa-eye-slash' : 'fas fa-eye';
}

// Strength meter
function strength2(v) {
  const sc = [v.length>=8, /[A-Z]/.test(v), /[0-9]/.test(v), /[^A-Za-z0-9]/.test(v)].filter(Boolean).length;
  const colors = ['','#EF4444','#F59E0B','#3B82F6','#10B981'];
  const labels = ['','Weak','Fair','Good','Strong'];
  [1,2,3,4].forEach(n => { document.getElementById('p'+n).style.background = n<=sc ? colors[sc] : 'rgba(11,37,69,.12)'; });
  const t = document.getElementById('ptxt');
  t.textContent = v.length ? labels[sc] : 'Enter new password';
  t.style.color = colors[sc] || 'var(--tm)';
}
function matchCheck2() {
  const a = document.getElementById('new_password').value;
  const b = document.getElementById('confirm_password').value;
  const m = document.getElementById('match2');
  if (!b) { m.textContent=''; return; }
  m.style.color = a===b ? '#059669' : '#DC2626';
  m.textContent = a===b ? '✓ Passwords match' : '✗ Do not match';
}

// Avatar preview
function previewAv(inp) {
  if (!inp.files[0]) return;
  const reader = new FileReader();
  reader.onload = e => {
    const drop = document.getElementById('av-drop');
    // Replace content
    const fb = document.getElementById('av-preview-fb');
    if (fb) fb.remove();
    let img = document.getElementById('av-preview');
    if (!img) { img = document.createElement('img'); img.id='av-preview'; img.alt=''; drop.prepend(img); }
    img.src = e.target.result;
    img.style.cssText = 'width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--bdr);margin:0 auto 14px;display:block';
    document.getElementById('av-save').style.display = 'inline-flex';
  };
  reader.readAsDataURL(inp.files[0]);
}

// Drag & drop
const drop = document.getElementById('av-drop');
if (drop) {
  drop.addEventListener('dragover', e => { e.preventDefault(); drop.classList.add('drag'); });
  drop.addEventListener('dragleave', () => drop.classList.remove('drag'));
  drop.addEventListener('drop', e => {
    e.preventDefault(); drop.classList.remove('drag');
    const f = e.dataTransfer.files[0];
    if (f && f.type.startsWith('image/')) {
      document.getElementById('avatar-input').files; // can't set directly
      // Create a DataTransfer to set files
      const dt = new DataTransfer(); dt.items.add(f);
      document.getElementById('avatar-input').files = dt.files;
      previewAv(document.getElementById('avatar-input'));
    }
  });
}
</script>
</body>
</html>
