<?php
require_once '../includes/config.php';
requireAdmin();

// Handle POST actions
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action']??'';
    if ($action==='clear_sessions') {
        $pdo->exec("DELETE FROM sessions WHERE expires < NOW()");
        jsonResponse(['success'=>true,'msg'=>'Expired sessions cleared.']);
    }
    if ($action==='clear_otps') {
        $pdo->exec("DELETE FROM otp_codes WHERE expires_at < NOW()");
        jsonResponse(['success'=>true,'msg'=>'Expired OTPs cleared.']);
    }
}

$logPage = max(1,(int)($_GET['page']??1));
$logLimit = 50;
$logOffset = ($logPage-1)*$logLimit;

// Admin logs
$logsExist = false;
try {
    $logs = $pdo->query("SELECT * FROM admin_logs ORDER BY created_at DESC LIMIT $logLimit OFFSET $logOffset")->fetchAll();
    $totalLogs = (int)$pdo->query("SELECT COUNT(*) FROM admin_logs")->fetchColumn();
    $logsExist = true;
} catch(Exception $e) { $logs = []; $totalLogs = 0; }

// Error log
$errorLog = '';
$errorLogFile = __DIR__ . '/error_log';
if (file_exists($errorLogFile)) {
    $lines = file($errorLogFile);
    $errorLog = implode('', array_slice($lines, -100));
}

require_once 'includes/header.php';
renderAdminHeader('Activity Log', 'activity-log');
?>
<style>
.log-tabs { display:flex; gap:4px; margin-bottom:20px; border-bottom:1px solid var(--border); }
.log-tab { padding:8px 20px; font-size:14px; font-weight:500; color:var(--text-muted); cursor:pointer; border-bottom:2px solid transparent; transition:.15s; background:none; border-top:none; border-left:none; border-right:none; }
.log-tab.active { color:var(--accent); border-bottom-color:var(--accent); }
.log-entry { padding:10px 14px; border-bottom:1px solid var(--border); font-size:13px; }
.log-entry:last-child { border-bottom:none; }
.log-entry .log-time { color:var(--text-muted); font-size:12px; margin-bottom:2px; }
.log-entry .log-action { color:var(--text-primary); }
.log-entry .log-admin { color:var(--accent); font-weight:500; }
.error-log-box { background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:16px; font-family:monospace; font-size:12px; color:var(--text-muted); max-height:500px; overflow-y:auto; white-space:pre-wrap; word-break:break-all; }
</style>

<div class="log-tabs">
  <button class="log-tab active" onclick="showTab('admin-log',this)">📋 Admin Actions</button>
  <button class="log-tab" onclick="showTab('error-log',this)">🐛 Error Log</button>
  <button class="log-tab" onclick="showTab('cleanup',this)">🧹 Cache / Cleanup</button>
</div>

<!-- Admin Log Tab -->
<div id="tab-admin-log">
<?php if(!$logsExist): ?>
<div class="card">
  <div style="padding:20px;color:var(--text-muted);text-align:center">
    <div style="font-size:32px;margin-bottom:8px">📋</div>
    <div>Admin action logging not yet set up.</div>
    <div style="font-size:13px;margin-top:4px">Run the SQL migration to create the <code>admin_logs</code> table.</div>
  </div>
</div>
<?php elseif(empty($logs)): ?>
<div class="card"><div style="padding:20px;color:var(--text-muted);text-align:center">No admin actions logged yet.</div></div>
<?php else: ?>
<div class="card">
  <div class="card-header">
    <div class="card-title">Admin Action History</div>
    <span style="font-size:13px;color:var(--text-muted)"><?= number_format($totalLogs) ?> total entries</span>
  </div>
  <div>
  <?php foreach($logs as $log): ?>
  <div class="log-entry">
    <div class="log-time"><?= date('M j, Y H:i:s', strtotime($log['created_at'])) ?></div>
    <div class="log-action">
      <span class="log-admin"><?= htmlspecialchars($log['admin_name']??'Admin') ?></span>
      — <?= htmlspecialchars($log['action']) ?>
      <?php if(!empty($log['target'])): ?> <span style="color:var(--text-muted)">→ <?= htmlspecialchars($log['target']) ?></span><?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
  </div>
  <?php if($totalLogs > $logLimit): ?>
  <div style="padding:12px 16px;display:flex;gap:8px;justify-content:center">
    <?php if($logPage>1): ?><a href="?page=<?= $logPage-1 ?>" class="btn btn-secondary btn-sm">← Prev</a><?php endif; ?>
    <span style="padding:6px 12px;font-size:13px;color:var(--text-muted)">Page <?= $logPage ?> / <?= ceil($totalLogs/$logLimit) ?></span>
    <?php if($logPage*$logLimit < $totalLogs): ?><a href="?page=<?= $logPage+1 ?>" class="btn btn-secondary btn-sm">Next →</a><?php endif; ?>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>
</div>

<!-- Error Log Tab -->
<div id="tab-error-log" style="display:none">
<div class="card">
  <div class="card-header">
    <div class="card-title">PHP Error Log <span style="font-size:12px;font-weight:400;color:var(--text-muted)">(Last 100 lines)</span></div>
    <button class="btn btn-secondary btn-sm" onclick="document.getElementById('errorLogBox').scrollTop=0">⬆ Top</button>
  </div>
  <?php if($errorLog): ?>
  <div class="error-log-box" id="errorLogBox"><?= htmlspecialchars($errorLog) ?></div>
  <?php else: ?>
  <div style="padding:20px;color:var(--text-muted);text-align:center">No error log found or it's empty.</div>
  <?php endif; ?>
</div>
</div>

<!-- Cleanup Tab -->
<div id="tab-cleanup" style="display:none">
<div class="card">
  <div class="card-header"><div class="card-title">🧹 Cache &amp; Session Cleanup</div></div>
  <div style="display:flex;flex-direction:column;gap:12px;padding:8px 0">
    <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-weight:500;color:var(--text-primary)">Clear Expired PHP Sessions</div>
        <div style="font-size:13px;color:var(--text-muted)">Removes expired session records from the database.</div>
      </div>
      <button class="btn btn-secondary" onclick="doClean('clear_sessions',this)">🗑️ Clear Sessions</button>
    </div>
    <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-weight:500;color:var(--text-primary)">Clear Expired OTP Codes</div>
        <div style="font-size:13px;color:var(--text-muted)">Purges old one-time passwords from the otp_codes table.</div>
      </div>
      <button class="btn btn-secondary" onclick="doClean('clear_otps',this)">🔑 Clear OTPs</button>
    </div>
  </div>
  <div id="cleanMsg" style="padding:10px 0;font-size:14px;color:#10b981"></div>
</div>
</div>

<script>
function showTab(id, btn) {
  document.querySelectorAll('[id^="tab-"]').forEach(t=>t.style.display='none');
  document.querySelectorAll('.log-tab').forEach(b=>b.classList.remove('active'));
  document.getElementById('tab-'+id).style.display='';
  btn.classList.add('active');
}
function doClean(action, btn) {
  btn.disabled=true; btn.textContent='...';
  fetch('', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'},body:'action='+action})
    .then(r=>r.json()).then(d=>{
      document.getElementById('cleanMsg').textContent = d.msg || (d.success ? '✅ Done!' : '❌ Failed');
      btn.disabled=false; btn.textContent='✅ Done';
    }).catch(()=>{ btn.disabled=false; });
}
</script>
<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
