<?php /* logs/online.php */
$roleColors = [
  'super_admin' => '#7c3aed','admin'       => '#1d4ed8',
  'developer'   => '#059669','manager'     => '#0891b2',
  'accountant'  => '#d97706','cashier'     => '#16a34a',
  'stock_keeper'=> '#6366f1','hr_manager'  => '#db2777',
];
$roleIcons = [
  'super_admin' => 'bi-shield-fill-check','admin'       => 'bi-shield-fill',
  'developer'   => 'bi-code-slash',       'manager'     => 'bi-person-badge-fill',
  'accountant'  => 'bi-calculator-fill',  'cashier'     => 'bi-cash-coin',
  'stock_keeper'=> 'bi-boxes',            'hr_manager'  => 'bi-people-fill',
];
$onlineCount  = count(array_filter($onlineUsers, fn($u)=>$u['online_status']==='online'));
$awayCount    = count(array_filter($onlineUsers, fn($u)=>$u['online_status']==='away'));
?>

<style>
.ol-hero{background:linear-gradient(135deg,#0f172a,#1e3a5f 55%,#0891b2);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.63rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.85}
.user-card{border-radius:10px;padding:12px 14px;border:1.5px solid #e2e8f0;
  transition:all .15s;margin-bottom:8px}
.user-card.online{border-color:#86efac;background:#f0fdf4}
.user-card.away{border-color:#fde68a;background:#fffbeb}
.usr-avatar{width:40px;height:40px;border-radius:50%;display:flex;
  align-items:center;justify-content:center;font-size:.85rem;font-weight:700;flex-shrink:0}
.status-dot{width:10px;height:10px;border-radius:50%;display:inline-block}
.log-table th{font-size:.7rem;padding:6px 10px;white-space:nowrap}
.log-table td{font-size:.76rem;padding:5px 10px;vertical-align:middle}
.pulse{animation:pulse 2s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.5}}
</style>

<!-- Hero -->
<div class="ol-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1">
        <i class="bi bi-activity me-2"></i>Online Users
        <span class="badge bg-success ms-2 pulse"
              style="font-size:.7rem" id="onlineCountBadge">
          <?=$onlineCount?> online
        </span>
      </h5>
      <div style="opacity:.8;font-size:.82rem">
        <span id="serverTime"><?=date('H:i:s')?></span>
        &nbsp;·&nbsp; <?=$loginStats['total_logins']?> logins today
        &nbsp;·&nbsp;
        <?php if($loginStats['failed_logins']>0):?>
        <span class="text-warning">⚠ <?=$loginStats['failed_logins']?> failed attempts</span>
        <?php else:?>
        No failed logins today
        <?php endif;?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/logs/activity"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-journal-text me-1"></i>Activity Logs
      </a>
      <button class="btn btn-outline-light btn-sm" onclick="refreshPage()">
        <i class="bi bi-arrow-clockwise me-1"></i>Refresh
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Row -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val text-success" id="kpiOnline"><?=$onlineCount?></div>
      <div class="lbl text-success">Online Now</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fffbeb;border:2px solid #d97706">
      <div class="val text-warning" id="kpiAway"><?=$awayCount?></div>
      <div class="lbl text-warning">Away (5-15 min)</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #3b82f6">
      <div class="val text-primary"><?=$loginStats['total_logins']?></div>
      <div class="lbl text-primary">Logins Today</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:<?=$loginStats['failed_logins']>0?'#fef2f2':'#f0fdf4'?>;
                                  border:2px solid <?=$loginStats['failed_logins']>0?'#dc2626':'#16a34a'?>">
      <div class="val" style="color:<?=$loginStats['failed_logins']>0?'#dc2626':'#16a34a'?>">
        <?=$loginStats['failed_logins']?>
      </div>
      <div class="lbl" style="color:<?=$loginStats['failed_logins']>0?'#dc2626':'#16a34a'?>">
        Failed Attempts
      </div>
    </div>
  </div>
</div>

<div class="row g-3">

  <!-- Online/Away Users -->
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
        <span><i class="bi bi-broadcast me-1"></i>Active Sessions</span>
        <span class="badge bg-success" id="sessionCount"><?=count($onlineUsers)?></span>
      </div>
      <div class="card-body p-2" id="onlineList">
        <?php if(empty($onlineUsers)):?>
        <div class="text-center text-muted py-4">
          <i class="bi bi-wifi-off d-block fs-3 mb-2 opacity-25"></i>
          No active sessions right now
        </div>
        <?php endif;?>
        <?php foreach($onlineUsers as $u):
          $rk   = strtolower(str_replace(' ','_',$u['role_name']));
          $clr  = $roleColors[$rk]??'#64748b';
          $icon = $roleIcons[$rk]??'bi-person';
          $initials = strtoupper(substr($u['name'],0,1)
                    .(strpos($u['name'],' ')!==false
                      ?substr(strrchr($u['name'],' '),1,1):''));
          $isOnline = $u['online_status']==='online';
          $sec = (int)$u['seconds_ago'];
          $ago = $sec<60?'Just now':($sec<3600?round($sec/60).'m ago':round($sec/3600).'h ago');
        ?>
        <div class="user-card <?=$u['online_status']?>">
          <div class="d-flex align-items-center gap-2">
            <div class="usr-avatar"
                 style="background:<?=$clr?>18;color:<?=$clr?>">
              <?=e($initials)?>
            </div>
            <div class="flex-grow-1">
              <div class="d-flex align-items-center gap-2">
                <span class="fw-semibold small"><?=e($u['name'])?></span>
                <span class="status-dot"
                      style="background:<?=$isOnline?'#16a34a':'#d97706'?>"></span>
                <span style="font-size:.65rem;color:<?=$isOnline?'#16a34a':'#d97706'?>">
                  <?=$isOnline?'Online':'Away'?>
                </span>
              </div>
              <div style="font-size:.65rem;color:#94a3b8">
                <i class="bi <?=$icon?> me-1" style="color:<?=$clr?>"></i>
                <?=e($u['role_name'])?> &nbsp;·&nbsp;
                <i class="bi bi-building me-1"></i><?=e($u['branch_name'])?>
              </div>
            </div>
            <div class="text-end">
              <div style="font-size:.65rem;font-weight:700;
                          color:<?=$isOnline?'#16a34a':'#d97706'?>">
                <?=$ago?>
              </div>
              <?php if($u['last_login']):?>
              <div style="font-size:.6rem;color:#94a3b8">
                Login: <?=date('H:i',strtotime($u['last_login']))?>
              </div>
              <?php endif;?>
            </div>
          </div>
        </div>
        <?php endforeach;?>
      </div>
    </div>

    <!-- Failed login attempts -->
    <?php if(!empty($failedLogins)):?>
    <div class="card mt-3">
      <div class="card-header fw-semibold small bg-danger text-white">
        <i class="bi bi-exclamation-octagon me-1"></i>
        Failed Login Attempts — Last 24h (<?=count($failedLogins)?>)
      </div>
      <div class="table-responsive">
        <table class="table table-sm mb-0 log-table">
          <thead class="table-secondary">
            <tr>
              <th class="ps-3">Time</th>
              <th>IP Address</th>
              <th>Details</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach(array_slice($failedLogins,0,10) as $f):?>
            <tr>
              <td class="ps-3 text-muted">
                <?=date('H:i:s',strtotime($f['created_at']))?>
              </td>
              <td>
                <code style="font-size:.7rem"><?=e($f['ip_address']??'—')?></code>
              </td>
              <td class="text-muted small">
                <?=e(substr($f['description']??'',0,40))?>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif;?>
  </div>

  <!-- Recent Login Activity -->
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
        <span><i class="bi bi-clock-history me-1"></i>Recent Login Activity — Last 24h</span>
        <span class="badge bg-secondary"><?=count($recentLogins)?></span>
      </div>
      <div class="table-responsive" style="max-height:500px;overflow-y:auto">
        <table class="table table-sm table-hover mb-0 log-table">
          <thead class="table-dark" style="position:sticky;top:0">
            <tr>
              <th class="ps-3">Time</th>
              <th>User</th>
              <th>Role</th>
              <th>IP Address</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($recentLogins)):?>
            <tr>
              <td colspan="5" class="text-center text-muted py-4">
                No login activity in the last 24 hours.
              </td>
            </tr>
            <?php endif;?>
            <?php foreach($recentLogins as $log):
              $rk  = strtolower(str_replace(' ','_',$log['role_name']));
              $clr = $roleColors[$rk]??'#64748b';
              $init= strtoupper(substr($log['user_name'],0,1)
                   .(strpos($log['user_name'],' ')!==false
                     ?substr(strrchr($log['user_name'],' '),1,1):''));
              $timeAgo = '';
              $sec2 = (int)(time()-strtotime($log['created_at']));
              if($sec2<60) $timeAgo='Just now';
              elseif($sec2<3600) $timeAgo=round($sec2/60).'m ago';
              elseif($sec2<86400) $timeAgo=round($sec2/3600).'h ago';
              else $timeAgo=round($sec2/86400).'d ago';
            ?>
            <tr>
              <td class="ps-3">
                <div class="fw-semibold small">
                  <?=date('H:i:s',strtotime($log['created_at']))?>
                </div>
                <div style="font-size:.62rem;color:#94a3b8"><?=$timeAgo?></div>
              </td>
              <td>
                <div class="d-flex align-items-center gap-2">
                  <div style="width:26px;height:26px;border-radius:50%;flex-shrink:0;
                              background:<?=$clr?>18;color:<?=$clr?>;
                              display:flex;align-items:center;justify-content:center;
                              font-size:.62rem;font-weight:700">
                    <?=$init?>
                  </div>
                  <div>
                    <div class="fw-semibold" style="font-size:.78rem">
                      <?=e($log['user_name'])?>
                    </div>
                    <div style="font-size:.62rem;color:#94a3b8">
                      <?=e($log['username']??'')?>
                    </div>
                  </div>
                </div>
              </td>
              <td>
                <span style="font-size:.65rem;font-weight:700;
                             color:<?=$clr?>">
                  <?=e($log['role_name'])?>
                </span>
              </td>
              <td>
                <code style="font-size:.68rem;color:#64748b">
                  <?=e($log['ip_address']??'—')?>
                </code>
              </td>
              <td>
                <span class="badge bg-success" style="font-size:.6rem">
                  <i class="bi bi-box-arrow-in-right me-1"></i>Login
                </span>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Quick link to full logs -->
    <div class="mt-2 text-end">
      <a href="<?=APP_URL?>/logs/activity"
         class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-journal-text me-1"></i>View All Activity Logs
      </a>
    </div>
  </div>

</div>

<script>
// Auto-refresh every 30s
let refreshTimer = 30;
let countdown;

function refreshPage() {
  clearInterval(countdown);
  window.location.reload();
}

function startCountdown() {
  countdown = setInterval(() => {
    refreshTimer--;
    const el = document.getElementById('refreshCountdown');
    if(el) el.textContent = refreshTimer + 's';
    if(refreshTimer <= 0) refreshPage();
  }, 1000);
}

// Update server time
setInterval(() => {
  const now = new Date();
  const t = document.getElementById('serverTime');
  if(t) t.textContent = now.toTimeString().substr(0,8);
}, 1000);

startCountdown();
</script>