<?php
// Provided by ProfileController::show(): $user, $sessions, $preferences, $two_factor_enabled
$initials = mb_strtoupper(mb_substr($user['first_name'], 0, 1) . mb_substr($user['last_name'] ?? '', 0, 1));
?>
<div class="row g-3">
  <div class="col-lg-4">
    <div class="ab-card text-center mb-3">
      <div class="ab-card-body">
        <div class="ab-avatar mx-auto mb-3" id="abAvatarPreview" style="width:84px; height:84px; font-size:1.6rem; border-radius:20px; overflow:hidden;">
          <?php if (!empty($user['avatar_path'])): ?>
            <img src="<?= e(base_url('uploads-view/' . $user['avatar_path'])) ?>" style="width:100%;height:100%;object-fit:cover;">
          <?php else: ?><?= e($initials) ?><?php endif; ?>
        </div>
        <h3 class="mb-0"><?= e($user['first_name'] . ' ' . ($user['last_name'] ?? '')) ?></h3>
        <div class="ab-text-muted small mb-3"><?= e($user['role_name'] ?? 'No role assigned') ?><?= $user['department_name'] ? ' · ' . e($user['department_name']) : '' ?></div>
        <input type="file" id="abAvatarInput" accept="image/*" class="d-none">
        <button class="btn btn-light-soft btn-sm" id="abChangePhotoBtn"><i class="bi bi-camera me-1"></i>Change Photo</button>
      </div>
      <hr class="m-0 ab-divider">
      <div class="ab-card-body text-start">
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Email</span><span class="small fw-semibold"><?= e($user['email']) ?> <?= $user['email_verified_at'] ? '<i class="bi bi-patch-check-fill text-success" title="Verified"></i>' : '<span class="ab-badge bg-warning-soft">Unverified</span>' ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Phone</span><span class="small fw-semibold ab-mono"><?= e($user['phone'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between"><span class="ab-text-muted small">Member Since</span><span class="small fw-semibold"><?= e(date('M Y', strtotime($user['created_at']))) ?></span></div>
      </div>
    </div>

    <div class="ab-card">
      <div class="ab-card-header"><h2>Active Sessions</h2></div>
      <div class="ab-card-body p-0" id="abSessionsList">
        <?php foreach ($sessions as $s): ?>
        <div class="d-flex align-items-center gap-2 p-3 border-bottom ab-hairline" data-session-id="<?= e($s['id']) ?>">
          <i class="bi bi-<?= $s['is_current'] ? 'laptop text-primary' : 'display' ?>"></i>
          <div class="flex-fill">
            <div class="small fw-semibold"><?= e($s['ip_address']) ?> <?= $s['is_current'] ? '<span class="ab-badge bg-success-soft">This device</span>' : '' ?></div>
            <div class="ab-cell-sub"><?= e($s['last_activity_human']) ?></div>
          </div>
          <?php if (!$s['is_current']): ?>
          <button class="btn btn-icon btn-light-soft btn-sm ab-revoke-session" data-session-id="<?= e($s['id']) ?>" title="Revoke"><i class="bi bi-x-lg"></i></button>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>
      <div class="ab-table-pagination justify-content-end">
        <button class="btn btn-light-soft btn-sm" id="abRevokeAllBtn">Log out other devices</button>
      </div>
    </div>
  </div>

  <div class="col-lg-8">
    <div class="ab-card mb-3">
      <div class="ab-card-header p-0" style="border-bottom:none;">
        <ul class="nav ab-tabs px-3 pt-2">
          <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabInfo">Personal Information</a></li>
          <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabPassword">Password</a></li>
          <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab2fa">Two-Factor Auth</a></li>
          <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabPrefs">Preferences</a></li>
        </ul>
      </div>
      <div class="ab-card-body tab-content">

        <div class="tab-pane fade show active" id="tabInfo">
          <form id="abProfileForm">
            <div class="row g-3">
              <div class="col-md-6"><label class="form-label ab-req">First Name</label><input class="form-control" name="first_name" value="<?= e($user['first_name']) ?>" required></div>
              <div class="col-md-6"><label class="form-label">Last Name</label><input class="form-control" name="last_name" value="<?= e($user['last_name'] ?? '') ?>"></div>
              <div class="col-md-6"><label class="form-label">Phone</label><input class="form-control" name="phone" value="<?= e($user['phone'] ?? '') ?>"></div>
              <div class="col-md-6"><label class="form-label">Job Title</label><input class="form-control" name="job_title" value="<?= e($user['job_title'] ?? '') ?>"></div>
              <div class="col-12"><button type="submit" class="btn btn-primary">Save Changes</button></div>
            </div>
          </form>

          <hr class="my-4 ab-divider">
          <h3 class="fs-6">Change Email Address</h3>
          <form id="abEmailForm" class="row g-3">
            <div class="col-md-8"><input type="email" class="form-control" name="email" placeholder="new-email@example.com" required></div>
            <div class="col-md-4"><button type="submit" class="btn btn-outline-primary w-100">Send Verification</button></div>
          </form>
        </div>

        <div class="tab-pane fade" id="tabPassword">
          <form id="abPasswordForm" class="row g-3" style="max-width:480px;">
            <div class="col-12"><label class="form-label ab-req">Current Password</label><input type="password" class="form-control" name="current_password" required></div>
            <div class="col-12"><label class="form-label ab-req">New Password</label><input type="password" class="form-control" name="password" required></div>
            <div class="col-12"><label class="form-label ab-req">Confirm New Password</label><input type="password" class="form-control" name="password_confirmation" required></div>
            <div class="col-12"><button type="submit" class="btn btn-primary">Update Password</button></div>
          </form>
        </div>

        <div class="tab-pane fade" id="tab2fa">
          <div id="ab2faDisabledPanel" class="<?= $two_factor_enabled ? 'd-none' : '' ?>">
            <p class="ab-text-muted">Add an extra layer of security — after entering your password, you'll also need a code from an authenticator app.</p>
            <button class="btn btn-primary" id="abStart2faBtn"><i class="bi bi-shield-lock me-1"></i>Enable Two-Factor Authentication</button>
            <div id="ab2faSetupPanel" class="d-none mt-4">
              <div class="row g-4 align-items-center">
                <div class="col-md-5 text-center">
                  <div id="abQrPlaceholder" class="border rounded-3 p-3 d-inline-block ab-mono small"></div>
                </div>
                <div class="col-md-7">
                  <p class="small ab-text-muted">Scan this with Google Authenticator, Authy, or 1Password, then enter the 6-digit code it shows.</p>
                  <div class="mb-2"><code id="abSecretText" class="ab-mono"></code></div>
                  <input type="text" id="ab2faConfirmCode" class="form-control mb-2" placeholder="123456" maxlength="6" style="max-width:160px;">
                  <button class="btn btn-primary btn-sm" id="ab2faConfirmBtn">Confirm &amp; Enable</button>
                </div>
              </div>
            </div>
            <div id="abRecoveryCodesPanel" class="d-none mt-4">
              <div class="alert alert-success"><strong>Save these recovery codes</strong> — each can be used once if you lose access to your authenticator app.</div>
              <div class="ab-mono small border rounded-3 p-3" id="abRecoveryCodesList"></div>
            </div>
          </div>
          <div id="ab2faEnabledPanel" class="<?= $two_factor_enabled ? '' : 'd-none' ?>">
            <div class="ab-badge bg-success-soft mb-3"><span class="dot"></span>Two-factor authentication is enabled</div>
            <form id="ab2faDisableForm" class="row g-3" style="max-width:420px;">
              <div class="col-12"><label class="form-label">Enter your password to disable</label><input type="password" class="form-control" name="password" required></div>
              <div class="col-12"><button type="submit" class="btn btn-outline-danger">Disable Two-Factor Authentication</button></div>
            </form>
          </div>
        </div>

        <div class="tab-pane fade" id="tabPrefs">
          <form id="abPrefsForm">
            <div class="mb-3">
              <label class="form-label">Theme</label>
              <select class="form-select" name="theme" style="max-width:280px;">
                <option value="light" <?= ($preferences['theme'] ?? 'light') === 'light' ? 'selected' : '' ?>>Light</option>
                <option value="dark" <?= ($preferences['theme'] ?? '') === 'dark' ? 'selected' : '' ?>>Dark</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">Default Landing Page</label>
              <select class="form-select" name="landing_page" style="max-width:280px;">
                <option value="dashboard" <?= ($preferences['landing_page'] ?? 'dashboard') === 'dashboard' ? 'selected' : '' ?>>Dashboard</option>
                <option value="profile" <?= ($preferences['landing_page'] ?? '') === 'profile' ? 'selected' : '' ?>>My Profile</option>
              </select>
            </div>
            <button type="submit" class="btn btn-primary">Save Preferences</button>
          </form>
        </div>

      </div>
    </div>
  </div>
</div>

<script>
document.getElementById('abProfileForm').addEventListener('submit', function (e) {
  e.preventDefault();
  var form = e.target;
  var data = { first_name: form.first_name.value, last_name: form.last_name.value, phone: form.phone.value, job_title: form.job_title.value };
  abFetch('<?= base_url('profile') ?>', { method: 'PATCH', body: data })
    .then(function (res) { abToast(res.message); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});

document.getElementById('abEmailForm').addEventListener('submit', function (e) {
  e.preventDefault();
  var form = e.target;
  abFetch('<?= base_url('profile/email') ?>', { method: 'POST', body: { email: form.email.value } })
    .then(function (res) { abToast(res.message); form.reset(); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});

document.getElementById('abPasswordForm').addEventListener('submit', function (e) {
  e.preventDefault();
  var form = e.target;
  abFetch('<?= base_url('profile/password') ?>', {
    method: 'POST',
    body: { current_password: form.current_password.value, password: form.password.value, password_confirmation: form.password_confirmation.value }
  }).then(function (res) { abToast(res.message); form.reset(); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});

document.getElementById('abChangePhotoBtn').addEventListener('click', function () {
  document.getElementById('abAvatarInput').click();
});
document.getElementById('abAvatarInput').addEventListener('change', function (e) {
  if (!e.target.files.length) return;
  var fd = new FormData();
  fd.append('avatar', e.target.files[0]);
  abFetch('<?= base_url('profile/avatar') ?>', { method: 'POST', body: fd })
    .then(function (res) {
      abToast(res.message);
      setTimeout(function () { window.location.reload(); }, 800);
    })
    .catch(function (err) { abToast(err.message || 'Upload failed', 'danger'); });
});

// ---- Sessions ----
document.querySelectorAll('.ab-revoke-session').forEach(function (btn) {
  btn.addEventListener('click', function () {
    abFetch('<?= base_url('profile/sessions') ?>/' + btn.dataset.sessionId, { method: 'DELETE' })
      .then(function (res) { abToast(res.message); btn.closest('[data-session-id]').remove(); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
document.getElementById('abRevokeAllBtn').addEventListener('click', function () {
  abFetch('<?= base_url('profile/sessions/revoke-others') ?>', { method: 'POST' })
    .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 800); })
    .catch(function (err) { abToast(err.message, 'danger'); });
});

// ---- 2FA ----
var start2faBtn = document.getElementById('abStart2faBtn');
if (start2faBtn) {
  start2faBtn.addEventListener('click', function () {
    abFetch('<?= base_url('profile/2fa/setup') ?>', { method: 'POST' }).then(function (res) {
      document.getElementById('ab2faSetupPanel').classList.remove('d-none');
      document.getElementById('abSecretText').textContent = res.data.secret;
      document.getElementById('abQrPlaceholder').textContent = res.data.provisioning_uri;
      start2faBtn.classList.add('d-none');
    });
  });
}
var confirm2faBtn = document.getElementById('ab2faConfirmBtn');
if (confirm2faBtn) {
  confirm2faBtn.addEventListener('click', function () {
    var code = document.getElementById('ab2faConfirmCode').value;
    abFetch('<?= base_url('profile/2fa/confirm') ?>', { method: 'POST', body: { code: code } })
      .then(function (res) {
        document.getElementById('ab2faSetupPanel').classList.add('d-none');
        var panel = document.getElementById('abRecoveryCodesPanel');
        panel.classList.remove('d-none');
        document.getElementById('abRecoveryCodesList').innerHTML = res.data.recovery_codes.join('<br>');
        abToast(res.message);
      })
      .catch(function (err) { abToast(err.message || 'Invalid code', 'danger'); });
  });
}
var disable2faForm = document.getElementById('ab2faDisableForm');
if (disable2faForm) {
  disable2faForm.addEventListener('submit', function (e) {
    e.preventDefault();
    abFetch('<?= base_url('profile/2fa/disable') ?>', { method: 'POST', body: { password: e.target.password.value } })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 800); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
}

document.getElementById('abPrefsForm').addEventListener('submit', function (e) {
  e.preventDefault();
  var form = e.target;
  abFetch('<?= base_url('profile/preferences') ?>', {
    method: 'POST',
    body: { preferences: { theme: form.theme.value, landing_page: form.landing_page.value } }
  }).then(function (res) { abToast(res.message); })
    .catch(function (err) { abToast(err.message, 'danger'); });
});
</script>
