<?php /* logs/audit.php */
$roleColors = [
  'super_admin'=>'#7c3aed','admin'=>'#1d4ed8','developer'=>'#059669',
  'manager'=>'#0891b2','accountant'=>'#d97706','cashier'=>'#16a34a',
  'stock_keeper'=>'#6366f1','hr_manager'=>'#db2777',
];
$actionColors = [
  'login'         => ['bg-success','bi-box-arrow-in-right','Login'],
  'logout'        => ['bg-secondary','bi-box-arrow-left','Logout'],
  'login_failed'  => ['bg-danger','bi-x-circle','Failed Login'],
  'create'        => ['bg-primary','bi-plus-circle','Create'],
  'update'        => ['bg-warning text-dark','bi-pencil','Update'],
  'delete'        => ['bg-danger','bi-trash3','Delete'],
  'approve'       => ['bg-success','bi-check-circle','Approve'],
  'payment'       => ['bg-info text-dark','bi-cash','Payment'],
  'sale'          => ['bg-primary','bi-receipt','Sale'],
  'cheque_update' => ['bg-warning text-dark','bi-bank2','Cheque'],
  'credit_payment'=> ['bg-success','bi-journal-bookmark','Credit Pay'],
  'export'        => ['bg-secondary','bi-download','Export'],
  'import'        => ['bg-secondary','bi-upload','Import'],
  'backup'        => ['bg-info text-dark','bi-hdd','Backup'],
  'restore'       => ['bg-warning text-dark','bi-arrow-counterclockwise','Restore'],
  'db_clear'      => ['bg-danger','bi-database-x','DB Clear'],
];
$moduleColors = [
  'auth'      =>'#7c3aed','sales'     =>'#1d4ed8','purchases'=>'#0891b2',
  'finance'   =>'#d97706','cheques'   =>'#d97706','expenses' =>'#dc2626',
  'products'  =>'#b45309','stock'     =>'#059669','users'    =>'#4f46e5',
  'payroll'   =>'#db2777','reports'   =>'#64748b','system'   =>'#0f172a',
];
?>

<style>
.al-hero{background:linear-gradient(135deg,#0f172a,#1e293b 55%,#334155);
  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}
.al-table th{font-size:.68rem;padding:7px 10px;white-space:nowrap}
.al-table td{font-size:.76rem;padding:6px 10px;vertical-align:middle;border-bottom:1px solid #f1f5f9}
.al-table tr:hover td{background:#f8fafc}
.action-badge{display:inline-flex;align-items:center;gap:3px;
  padding:2px 7px;border-radius:10px;font-size:.62rem;font-weight:700;white-space:nowrap}
.mod-badge{padding:1px 7px;border-radius:10px;font-size:.62rem;font-weight:700}
.usr-init{width:26px;height:26px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.6rem;font-weight:700;flex-shrink:0}
.diff-box{max-width:220px;word-break:break-all;font-size:.65rem;
  background:#f8fafc;border-radius:4px;padding:3px 6px;
  border:1px solid #e2e8f0;font-family:monospace}
</style>

<!-- Hero -->
<div class="al-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-journal-text me-2"></i>Activity Logs
      </h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=date('d M Y',strtotime($from))?> – <?=date('d M Y',strtotime($to))?>
        &nbsp;·&nbsp; <?=number_format($total)?> entries
        &nbsp;·&nbsp; Page <?=$page?>/<?=max(1,$pages)?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/logs/online"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-broadcast me-1"></i>Online Users
      </a>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </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:#f8fafc;border:2px solid #475569">
      <div class="val" style="color:#475569"><?=number_format($total)?></div>
      <div class="lbl" style="color:#475569">Total Entries</div>
    </div>
  </div>
  <?php
  $loginCount  = array_sum(array_column(array_filter($stats,fn($s)=>$s['module']==='auth'),'cnt'));
  $actionCount = count($stats);
  $topModule   = !empty($stats)?$stats[0]['module']:'—';
  $topCnt      = !empty($stats)?(int)$stats[0]['cnt']:0;
  ?>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val text-success">
        <?=array_sum(array_column(array_filter($stats,fn($s)=>in_array($s['module'],['sales','purchases'])),'cnt'))?>
      </div>
      <div class="lbl text-success">Sales/Purchase Actions</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #1d4ed8">
      <div class="val text-primary">
        <?=count(array_unique(array_column($logs,'user_id')))?>
      </div>
      <div class="lbl text-primary">Active Users</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val text-warning"><?=$actionCount?></div>
      <div class="lbl text-warning">Modules Touched</div>
    </div>
  </div>
</div>

<div class="row g-3">

  <!-- Left: Logs table -->
  <div class="col-lg-9">

    <!-- Filters -->
    <div class="card mb-3">
      <div class="card-body py-2">
        <form method="GET" action="<?=APP_URL?>/logs/activity"
              class="d-flex gap-2 flex-wrap align-items-end">
          <div class="d-flex gap-1 align-items-center">
            <input type="date" name="from" class="form-control form-control-sm"
                   value="<?=e($from)?>" style="width:135px">
            <span class="text-muted small">to</span>
            <input type="date" name="to" class="form-control form-control-sm"
                   value="<?=e($to)?>" style="width:135px">
          </div>
          <select name="module" class="form-select form-select-sm" style="max-width:130px">
            <option value="">All Modules</option>
            <?php foreach($modules as $mod):?>
            <option value="<?=e($mod['module'])?>"
                    <?=$module===($mod['module'])?'selected':''?>>
              <?=ucfirst(e($mod['module']))?>
            </option>
            <?php endforeach;?>
          </select>
          <select name="user" class="form-select form-select-sm" style="max-width:150px">
            <option value="0">All Users</option>
            <?php foreach($users as $u):?>
            <option value="<?=$u['id']?>" <?=$userId==$u['id']?'selected':''?>>
              <?=e($u['name'])?>
            </option>
            <?php endforeach;?>
          </select>
          <div class="input-group input-group-sm" style="max-width:180px">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control"
                   placeholder="Search description…"
                   value="<?=e($search)?>">
          </div>
          <button class="btn btn-secondary btn-sm fw-semibold">
            <i class="bi bi-funnel me-1"></i>Filter
          </button>
          <a href="<?=APP_URL?>/logs/activity"
             class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-x-lg"></i>
          </a>
          <!-- Quick shortcuts -->
          <div class="d-flex gap-1">
            <?php foreach([
              'Today'     =>[date('Y-m-d'),     date('Y-m-d')],
              'Yesterday' =>[date('Y-m-d',strtotime('-1 day')),date('Y-m-d',strtotime('-1 day'))],
              'This Week' =>[date('Y-m-d',strtotime('monday this week')),date('Y-m-d')],
            ] as $lbl=>[$f,$t]):
              $isActive = ($from===$f&&$to===$t);
            ?>
            <a href="?from=<?=$f?>&to=<?=$t?>"
               class="btn btn-sm <?=$isActive?'btn-dark':'btn-outline-secondary'?>">
              <?=$lbl?>
            </a>
            <?php endforeach;?>
          </div>
        </form>
      </div>
    </div>

    <!-- Log Table -->
    <div class="card">
      <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
        <span class="fw-semibold small">
          <i class="bi bi-list-ul me-1"></i>Audit Trail
        </span>
        <span class="badge bg-secondary">
          <?=number_format($total)?> entries · Page <?=$page?>/<?=max(1,$pages)?>
        </span>
      </div>
      <div class="table-responsive">
        <table class="table table-sm table-hover mb-0 al-table">
          <thead class="table-dark">
            <tr>
              <th class="ps-3">#</th>
              <th>Time</th>
              <th>User</th>
              <th class="text-center">Module</th>
              <th class="text-center">Action</th>
              <th>Description</th>
              <th class="text-center">IP</th>
              <th class="text-center">Changes</th>
            </tr>
          </thead>
          <tbody>
            <?php if(empty($logs)):?>
            <tr>
              <td colspan="8" class="text-center text-muted py-5">
                <i class="bi bi-journal-x d-block fs-2 mb-2 opacity-25"></i>
                No activity logs for selected filters.
              </td>
            </tr>
            <?php endif;?>

            <?php
            $offset2 = ($page-1)*$perPage;
            foreach($logs as $i=>$log):
              $rowN   = $offset2+$i+1;
              $aCfg   = $actionColors[$log['action']] ?? ['bg-secondary','bi-dot',ucfirst($log['action'])];
              $mClr   = $moduleColors[$log['module']??''] ?? '#64748b';

              // User info
              $uName  = $log['user_name'] ?? 'System';
              $uUser  = $log['username']  ?? '';
              $initials= strtoupper(substr($uName,0,1)
                       .(strpos($uName,' ')!==false?substr(strrchr($uName,' '),1,1):''));

              // Time
              $ts     = strtotime($log['created_at']);
              $secAgo = time()-$ts;
              if($secAgo<60)       $ago='Just now';
              elseif($secAgo<3600) $ago=round($secAgo/60).'m ago';
              elseif($secAgo<86400)$ago=round($secAgo/3600).'h ago';
              else                 $ago=date('d M',  $ts);

              $hasChanges = !empty($log['old_value']) || !empty($log['new_value']);
            ?>
            <tr>
              <td class="ps-3 text-muted small"><?=$rowN?></td>

              <!-- Time -->
              <td>
                <div class="fw-semibold small">
                  <?=date('H:i:s',$ts)?>
                </div>
                <div style="font-size:.62rem;color:#94a3b8">
                  <?=$ago?> · <?=date('d M',$ts)?>
                </div>
              </td>

              <!-- User -->
              <td>
                <div class="d-flex align-items-center gap-2">
                  <div class="usr-init"
                       style="background:<?=$mClr?>18;color:<?=$mClr?>">
                    <?=e($initials)?>
                  </div>
                  <div>
                    <div class="fw-semibold small"><?=e($uName)?></div>
                    <?php if($uUser):?>
                    <div style="font-size:.62rem;color:#94a3b8">
                      @<?=e($uUser)?>
                    </div>
                    <?php endif;?>
                  </div>
                </div>
              </td>

              <!-- Module -->
              <td class="text-center">
                <span class="mod-badge"
                      style="background:<?=$mClr?>18;color:<?=$mClr?>">
                  <?=ucfirst(e($log['module']??'—'))?>
                </span>
              </td>

              <!-- Action -->
              <td class="text-center">
                <span class="badge <?=$aCfg[0]?> action-badge" style="font-size:.6rem">
                  <i class="bi <?=$aCfg[1]?>"></i>
                  <?=$aCfg[2]?>
                </span>
              </td>

              <!-- Description -->
              <td>
                <div style="max-width:280px;word-break:break-word;font-size:.74rem">
                  <?=e($log['description']??'—')?>
                </div>
              </td>

              <!-- IP -->
              <td class="text-center">
                <code style="font-size:.64rem;color:#475569">
                  <?=e($log['ip_address']??'—')?>
                </code>
              </td>

              <!-- Changes -->
              <td class="text-center">
                <?php if($hasChanges):?>
                <button class="btn btn-sm btn-outline-secondary py-0 px-2"
                        onclick="showDiff(<?=$log['id']?>,'<?=htmlspecialchars(json_encode(['old'=>$log['old_value'],'new'=>$log['new_value']]),ENT_QUOTES)?>')"
                        style="font-size:.65rem">
                  <i class="bi bi-eye"></i>
                </button>
                <?php else:?>
                <span class="text-muted small">—</span>
                <?php endif;?>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if($pages > 1):?>
      <div class="card-footer d-flex justify-content-between align-items-center py-2">
        <span class="text-muted small">
          Showing <?=number_format(($page-1)*$perPage+1)?>–<?=number_format(min($page*$perPage,$total))?>
          of <?=number_format($total)?>
        </span>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <li class="page-item <?=$page<=1?'disabled':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$page-1]))?>">‹</a>
            </li>
            <?php
            $range = range(max(1,$page-2), min($pages,$page+2));
            if($range[0]>1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
            foreach($range as $p):?>
            <li class="page-item <?=$p===$page?'active':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p]))?>"><?=$p?></a>
            </li>
            <?php endforeach;
            if(end($range)<$pages) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';?>
            <li class="page-item <?=$page>=$pages?'disabled':''?>">
              <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$page+1]))?>">›</a>
            </li>
          </ul>
        </nav>
      </div>
      <?php endif;?>
    </div>
  </div>

  <!-- Right: Module Breakdown -->
  <div class="col-lg-3">
    <div class="card mb-3">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-diagram-3 me-1 text-primary"></i>Activity by Module
      </div>
      <div class="card-body p-2">
        <?php
        $maxCnt = !empty($stats) ? max(array_column($stats,'cnt')) : 1;
        foreach($stats as $s):
          $mClr2 = $moduleColors[$s['module']]??'#64748b';
          $pct   = $maxCnt>0?round((int)$s['cnt']/$maxCnt*100):0;
        ?>
        <div class="mb-2">
          <div class="d-flex justify-content-between mb-1">
            <span class="small fw-semibold" style="color:<?=$mClr2?>">
              <?=ucfirst(e($s['module']))?>
            </span>
            <span class="badge" style="background:<?=$mClr2?>;font-size:.6rem">
              <?=number_format($s['cnt'])?>
            </span>
          </div>
          <div style="height:5px;background:<?=$mClr2?>18;border-radius:3px">
            <div style="height:5px;border-radius:3px;width:<?=$pct?>%;
                        background:<?=$mClr2?>"></div>
          </div>
        </div>
        <?php endforeach;?>
        <?php if(empty($stats)):?>
        <div class="text-center text-muted small py-2">No data</div>
        <?php endif;?>
      </div>
    </div>

    <div class="card">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-person-lines-fill me-1 text-success"></i>Top Users Today
      </div>
      <div class="card-body p-2">
        <?php
        $userStats = [];
        foreach($logs as $l) {
          $un = $l['user_name']??'System';
          $userStats[$un] = ($userStats[$un]??0)+1;
        }
        arsort($userStats);
        $maxU = max($userStats?:[1]);
        foreach(array_slice($userStats,0,6,true) as $uName=>$cnt):
          $u1  = strtoupper(substr($uName,0,1));
          $pct = $maxU>0?round($cnt/$maxU*100):0;
        ?>
        <div class="mb-2 d-flex align-items-center gap-2">
          <div style="width:22px;height:22px;border-radius:50%;background:#eff6ff;
                      color:#1d4ed8;display:flex;align-items:center;
                      justify-content:center;font-size:.6rem;font-weight:700;flex-shrink:0">
            <?=$u1?>
          </div>
          <div class="flex-grow-1">
            <div class="d-flex justify-content-between mb-1">
              <span style="font-size:.7rem;font-weight:600"><?=e($uName)?></span>
              <span style="font-size:.65rem;color:#94a3b8"><?=$cnt?></span>
            </div>
            <div style="height:3px;background:#f1f5f9;border-radius:2px">
              <div style="height:3px;border-radius:2px;width:<?=$pct?>%;background:#1d4ed8"></div>
            </div>
          </div>
        </div>
        <?php endforeach;?>
      </div>
    </div>
  </div>

</div>

<!-- Diff Modal -->
<div class="modal fade" id="diffModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold">
          <i class="bi bi-eye me-2"></i>Change Details
        </h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <div class="small fw-semibold text-danger mb-1">
            <i class="bi bi-dash-circle me-1"></i>Before
          </div>
          <div class="diff-box text-danger" id="diffOld">—</div>
        </div>
        <div>
          <div class="small fw-semibold text-success mb-1">
            <i class="bi bi-plus-circle me-1"></i>After
          </div>
          <div class="diff-box text-success" id="diffNew">—</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary"
                data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
function showDiff(id, dataJson) {
  try {
    const d = JSON.parse(dataJson);
    document.getElementById('diffOld').textContent = d.old || '—';
    document.getElementById('diffNew').textContent = d.new || '—';
  } catch(e) {
    document.getElementById('diffOld').textContent = '—';
    document.getElementById('diffNew').textContent = '—';
  }
  new bootstrap.Modal(document.getElementById('diffModal')).show();
}
</script>