<?php
/**
 * GT BOGO Engine — Audit Log (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;

if (!function_exists('gt_bogo_log')) {
    function gt_bogo_log($action, $detail = '', $level = 'info') {
        $log   = get_option('gtbogo_audit_log', []);
        $log[] = [
            'time'   => current_time('Y-m-d H:i:s'),
            'user'   => wp_get_current_user()->user_login ?? 'system',
            'action' => sanitize_text_field($action),
            'detail' => sanitize_text_field($detail),
            'level'  => in_array($level,['info','warn','error','success'])?$level:'info',
        ];
        if (count($log) > 1000) $log = array_slice($log, -1000);
        update_option('gtbogo_audit_log', $log);
    }
}

$message = ''; $message_type = '';

// Clear all log
if ($is_pro && isset($_POST['gtbogo_clear_log']) && check_admin_referer('gtbogo_clear_log')) {
    update_option('gtbogo_audit_log', []);
    gt_bogo_log('Audit log cleared', 'All entries manually cleared by admin', 'warn');
    $message = 'Audit log cleared.'; $message_type = 'success';
}

// Clear by date range
if ($is_pro && isset($_POST['gtbogo_clear_before']) && check_admin_referer('gtbogo_clear_before')) {
    $before = sanitize_text_field($_POST['clear_before_date'] ?? '');
    if ($before) {
        $log = get_option('gtbogo_audit_log', []);
        $filtered = array_filter($log, fn($e) => strcmp($e['time'], $before . ' 00:00:00') >= 0);
        update_option('gtbogo_audit_log', array_values($filtered));
        gt_bogo_log('Audit log partial clear', 'Entries before ' . $before . ' removed', 'warn');
        $message = 'Log entries before ' . esc_html($before) . ' removed.'; $message_type = 'success';
    }
}

// Export CSV
if ($is_pro && isset($_GET['gtbogo_export_log']) && check_admin_referer('gtbogo_export_log')) {
    $log = get_option('gtbogo_audit_log', []);
    $log = array_reverse($log);
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="gt-bogo-audit-log-' . date('Y-m-d') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Time', 'User', 'Action', 'Detail', 'Level']);
    foreach ($log as $e) fputcsv($out, [$e['time'], $e['user'], $e['action'], $e['detail'], $e['level']]);
    fclose($out);
    exit;
}

// Save settings
if ($is_pro && isset($_POST['gtbogo_save_log_settings']) && check_admin_referer('gtbogo_log_settings')) {
    update_option('gtbogo_log_enabled',         isset($_POST['log_enabled']));
    update_option('gtbogo_log_max_entries',     intval($_POST['log_max_entries'] ?? 500));
    update_option('gtbogo_log_levels',          array_map('sanitize_text_field', (array)($_POST['log_levels'] ?? ['info','warn','error','success'])));
    update_option('gtbogo_log_notify_errors',   isset($_POST['log_notify_errors']));
    update_option('gtbogo_log_notify_email',    sanitize_email($_POST['log_notify_email'] ?? get_option('admin_email')));
    gt_bogo_log('Log settings updated', 'Max entries and level filters saved', 'info');
    $message = 'Log settings saved.'; $message_type = 'success';
}

$log_enabled      = get_option('gtbogo_log_enabled', true);
$log_max          = get_option('gtbogo_log_max_entries', 500);
$log_levels_watch = get_option('gtbogo_log_levels', ['info','warn','error','success']);
$log_notify       = get_option('gtbogo_log_notify_errors', false);
$log_email        = get_option('gtbogo_log_notify_email', get_option('admin_email'));

// Build filtered log view
$log     = get_option('gtbogo_audit_log', []);
$log_rev = array_reverse($log);

// Filters
$f_level  = isset($_GET['f_level'])  ? sanitize_text_field($_GET['f_level'])  : '';
$f_user   = isset($_GET['f_user'])   ? sanitize_text_field($_GET['f_user'])   : '';
$f_action = isset($_GET['f_action']) ? sanitize_text_field($_GET['f_action']) : '';
$f_search = isset($_GET['f_search']) ? sanitize_text_field($_GET['f_search']) : '';

$filtered = $log_rev;
if ($f_level)  $filtered = array_filter($filtered, fn($e) => $e['level']  === $f_level);
if ($f_user)   $filtered = array_filter($filtered, fn($e) => $e['user']   === $f_user);
if ($f_search) $filtered = array_filter($filtered, fn($e) => str_contains(strtolower($e['action'].$e['detail']), strtolower($f_search)));
$filtered = array_values($filtered);

$per_page = 50;
$page_num = max(1, intval($_GET['log_page'] ?? 1));
$total    = count($filtered);
$paged    = array_slice($filtered, ($page_num - 1) * $per_page, $per_page);
$pages    = max(1, ceil($total / $per_page));

// Stats
$all_levels = array_count_values(array_column($log, 'level'));
$all_users  = array_unique(array_column($log, 'user'));
$recent_errors = array_filter($log_rev, fn($e) => $e['level']==='error');

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
  <div>
    <h1 class="gt-page-title">🔍 Audit Log</h1>
    <p class="gt-page-subtitle">Complete timestamped record of every rule change, activation, import, and system event</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <?php if ($is_pro && !empty($log)): ?>
    <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['gtbogo_export_log'=>1,'page'=>'gt-bogo-engine','tab'=>'audit-log'], admin_url('admin.php')), 'gtbogo_export_log')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">⬇ Export CSV</a>
    <form method="post" action="" style="margin:0">
      <?php wp_nonce_field('gtbogo_clear_log'); ?>
      <button type="submit" name="gtbogo_clear_log" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="return confirm('Clear all log entries? This cannot be undone.')">🗑 Clear All</button>
    </form>
    <?php endif; ?>
  </div>
</div>
<?php if ($message): ?><div class="gt-notice gt-notice-<?php echo esc_attr($message_type); ?> gt-animate-in">✓ <?php echo esc_html($message); ?></div><?php endif; ?>

<?php if (!$is_pro): ?>
<div class="gt-pro-gate gt-animate-in">
  <span class="gt-pro-gate-icon">🔍</span>
  <h2>PRO License Required</h2>
  <p>The Audit Log tracks every rule change, activation, pack import, and settings update — essential for multi-admin stores, agencies, and compliance.</p>
  <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
    <?php foreach(['Complete change history with timestamps','Filter by user, level, or action type','Export full log to CSV for compliance','Error alerting via email notification'] as $f): ?>
    <div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($f); ?></span></div>
    <?php endforeach; ?>
  </div>
  <div style="margin-top:24px;display:flex;justify-content:center;gap:12px;flex-wrap:wrap">
    <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $19.99/yr</a>
    <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" class="gt-btn gt-btn-ghost">Activate License</a>
  </div>
</div>
<?php else: ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
  <?php foreach ([
    ['info',   'ℹ️','Info Events',  '#3b82f6'],
    ['success','✅','Successes',    '#22c55e'],
    ['warn',   '⚠️','Warnings',     '#f59e0b'],
    ['error',  '🚨','Errors',       '#e10000'],
  ] as $lv): ?>
  <div class="gt-metric" style="--gt-metric-c:<?php echo $lv[3]; ?>">
    <span class="gt-metric-icon"><?php echo $lv[1]; ?></span>
    <div class="gt-metric-label"><?php echo esc_html($lv[2]); ?></div>
    <div class="gt-metric-value"><?php echo intval($all_levels[$lv[0]] ?? 0); ?></div>
    <div class="gt-metric-trend">Total in log</div>
  </div>
  <?php endforeach; ?>
  <div class="gt-metric" style="--gt-metric-c:#64748b">
    <span class="gt-metric-icon">📋</span>
    <div class="gt-metric-label">Total Events</div>
    <div class="gt-metric-value"><?php echo count($log); ?></div>
    <div class="gt-metric-trend">Max: <?php echo $log_max; ?></div>
  </div>
</div>

<?php if (!empty($recent_errors)): ?>
<div class="gt-notice gt-animate-in" style="background:rgba(225,0,0,0.07);border-color:rgba(225,0,0,0.3);color:#fca5a5;margin-bottom:20px">
  🚨 <strong><?php echo count($recent_errors); ?> error<?php echo count($recent_errors)>1?'s':''; ?> in log.</strong>
  Most recent: <strong><?php echo esc_html(array_values($recent_errors)[0]['action'] ?? ''); ?></strong> —
  <?php echo esc_html(array_values($recent_errors)[0]['detail'] ?? ''); ?>
  (<a href="?page=gt-bogo-engine&tab=audit-log&f_level=error" style="color:#fca5a5">view all errors</a>)
</div>
<?php endif; ?>

<!-- FILTERS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">🔎 Filter Log</h2></div>
  <form method="get" action="">
    <input type="hidden" name="page" value="gt-bogo-engine">
    <input type="hidden" name="tab" value="audit-log">
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;align-items:end">
      <div class="gt-form-group" style="margin:0">
        <label class="gt-form-label">Search</label>
        <input type="text" name="f_search" class="gt-input" placeholder="Action or detail..." value="<?php echo esc_attr($f_search); ?>">
      </div>
      <div class="gt-form-group" style="margin:0">
        <label class="gt-form-label">Level</label>
        <select name="f_level" class="gt-select">
          <option value="">All Levels</option>
          <?php foreach (['info'=>'Info','success'=>'Success','warn'=>'Warning','error'=>'Error'] as $k=>$v): ?>
          <option value="<?php echo $k; ?>" <?php selected($f_level,$k); ?>><?php echo esc_html($v); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="gt-form-group" style="margin:0">
        <label class="gt-form-label">User</label>
        <select name="f_user" class="gt-select">
          <option value="">All Users</option>
          <?php foreach ($all_users as $u): ?>
          <option value="<?php echo esc_attr($u); ?>" <?php selected($f_user,$u); ?>><?php echo esc_html($u); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div style="display:flex;gap:8px">
        <button type="submit" class="gt-btn gt-btn-primary" style="flex:1;padding:10px">Filter</button>
        <a href="?page=gt-bogo-engine&tab=audit-log" class="gt-btn gt-btn-ghost" style="padding:10px 14px">✕</a>
      </div>
    </div>
  </form>
</div>

<!-- LOG TABLE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header">
    <h2 class="gt-card-title">Event Log</h2>
    <span class="gt-text-soft gt-text-sm">
      <?php if ($f_level || $f_user || $f_search): ?>
        <strong style="color:var(--gt-white)"><?php echo $total; ?></strong> filtered of <?php echo count($log); ?> total
      <?php else: ?>
        Showing <?php echo min($per_page, $total); ?> of <?php echo $total; ?> events
      <?php endif; ?>
    </span>
  </div>
  <?php if ($paged): ?>
  <div style="overflow-x:auto">
    <table class="gt-table">
      <thead><tr><th>Time</th><th>User</th><th>Action</th><th>Detail</th><th>Level</th></tr></thead>
      <tbody>
      <?php
      $lv_styles = [
        'info'    => ['bg'=>'rgba(59,130,246,0.1)',  'border'=>'rgba(59,130,246,0.2)',  'color'=>'#93c5fd'],
        'success' => ['bg'=>'rgba(34,197,94,0.1)',   'border'=>'rgba(34,197,94,0.2)',   'color'=>'#86efac'],
        'warn'    => ['bg'=>'rgba(245,158,11,0.1)',  'border'=>'rgba(245,158,11,0.2)',  'color'=>'#fcd34d'],
        'error'   => ['bg'=>'rgba(225,0,0,0.1)',     'border'=>'rgba(225,0,0,0.2)',     'color'=>'#fca5a5'],
      ];
      foreach ($paged as $entry):
        $lvc = $lv_styles[$entry['level']] ?? $lv_styles['info'];
      ?>
      <tr style="<?php echo $entry['level']==='error'?'background:rgba(225,0,0,0.03)':''; ?>">
        <td style="color:var(--gt-soft);font-family:'DM Mono',monospace;font-size:11px;white-space:nowrap"><?php echo esc_html($entry['time']); ?></td>
        <td style="color:var(--gt-white);font-size:13px"><?php echo esc_html($entry['user']); ?></td>
        <td style="color:var(--gt-white);font-weight:600;font-size:13px"><?php echo esc_html($entry['action']); ?></td>
        <td style="color:var(--gt-soft);font-size:12px;max-width:300px"><?php echo esc_html($entry['detail']); ?></td>
        <td><span style="background:<?php echo $lvc['bg']; ?>;border:1px solid <?php echo $lvc['border']; ?>;color:<?php echo $lvc['color']; ?>;padding:2px 8px;border-radius:50px;font-size:10px;font-weight:700;text-transform:uppercase;white-space:nowrap"><?php echo esc_html($entry['level']); ?></span></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pages > 1): ?>
  <div style="display:flex;justify-content:center;gap:6px;margin-top:16px;flex-wrap:wrap">
    <?php for ($p = 1; $p <= $pages; $p++): ?>
    <a href="?page=gt-bogo-engine&tab=audit-log&log_page=<?php echo $p; ?>&f_level=<?php echo urlencode($f_level); ?>&f_user=<?php echo urlencode($f_user); ?>&f_search=<?php echo urlencode($f_search); ?>"
       class="gt-btn <?php echo $p===$page_num?'gt-btn-primary':'gt-btn-ghost'; ?> gt-btn-sm"><?php echo $p; ?></a>
    <?php endfor; ?>
  </div>
  <?php endif; ?>
  <?php else: ?>
  <div style="text-align:center;padding:40px 24px">
    <div style="font-size:48px;margin-bottom:16px">📋</div>
    <h3 style="color:var(--gt-white);margin:0 0 8px">No Matching Events</h3>
    <p class="gt-text-soft gt-text-sm"><?php echo ($f_level||$f_user||$f_search) ? 'Try adjusting your filters.' : 'Events appear as you create, edit, and activate rules.'; ?></p>
    <?php if ($f_level||$f_user||$f_search): ?>
    <a href="?page=gt-bogo-engine&tab=audit-log" class="gt-btn gt-btn-ghost gt-btn-sm" style="margin-top:12px">Clear Filters</a>
    <?php endif; ?>
  </div>
  <?php endif; ?>
</div>

<!-- PARTIAL CLEAR -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">🗑 Partial Clear</h2><span class="gt-text-soft gt-text-sm">Remove entries before a specific date</span></div>
  <form method="post" action="">
    <?php wp_nonce_field('gtbogo_clear_before'); ?>
    <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
      <div class="gt-form-group" style="margin:0;flex:1;min-width:200px">
        <label class="gt-form-label">Remove all entries before</label>
        <input type="date" name="clear_before_date" class="gt-input" value="<?php echo date('Y-m-d', strtotime('-90 days')); ?>">
      </div>
      <div style="padding-top:24px">
        <button type="submit" name="gtbogo_clear_before" class="gt-btn gt-btn-ghost" onclick="return confirm('Remove all log entries before the selected date?')">🗑 Remove Old Entries</button>
      </div>
    </div>
  </form>
</div>

<!-- LOG SETTINGS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Log Settings</h2></div>
  <form method="post" action="">
    <?php wp_nonce_field('gtbogo_log_settings'); ?>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Enable Audit Logging</div><div class="gt-setting-desc">Record all rule and settings changes. Disabling this stops logging but does not clear existing entries.</div></div>
      <label class="gt-toggle"><input type="checkbox" name="log_enabled" value="1" <?php checked($log_enabled); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Maximum Log Entries</div><div class="gt-setting-desc">Oldest entries are automatically pruned when this limit is reached. Recommended: 500–1000.</div></div>
      <input type="number" name="log_max_entries" class="gt-input" style="width:100px" value="<?php echo esc_attr($log_max); ?>" min="100" max="5000">
    </div>
    <div class="gt-setting-row">
      <div><div class="gt-setting-label">Email Alert on Errors</div><div class="gt-setting-desc">Send an email notification whenever an error-level event is logged. Useful for catching issues in production without monitoring the log manually.</div></div>
      <label class="gt-toggle"><input type="checkbox" name="log_notify_errors" value="1" <?php checked($log_notify); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-setting-row" style="border:none">
      <div><div class="gt-setting-label">Alert Email Address</div><div class="gt-setting-desc">Where error alerts are sent. Defaults to WordPress admin email.</div></div>
      <input type="email" name="log_notify_email" class="gt-input" style="width:280px" value="<?php echo esc_attr($log_email); ?>">
    </div>
    <div style="margin-top:20px;text-align:right">
      <button type="submit" name="gtbogo_save_log_settings" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Log Settings</button>
    </div>
  </form>
</div>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
  <div class="gt-card-header"><h2 class="gt-card-title">🧠 Audit Log Best Practices</h2></div>
  <div class="gt-feature-grid gt-feature-grid--2col">
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Pre-Campaign Checkpoint</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Before enabling any major campaign rule, scan the log for the last 7 days. Confirm no conflicting rule was quietly left active by another admin, and no accidental import changed your priority stack since your last review.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Agency Compliance Reporting</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Export the CSV monthly and attach it to your client reports. The timestamped record shows exactly what was changed, when, and by whom — eliminating disputes about who made a change that affected a promotion.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Error Alerting for Production Stores</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Enable error email alerts on any store running Black Friday or high-traffic campaigns. A rule conflict or database error during peak traffic can silently cost significant revenue before you notice it in the analytics dashboard.</div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Retention Strategy</div>
      <div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Keep 12 months of log data for stores that run annual campaigns — you may want to compare this year's Black Friday setup against last year's. Use partial clear to remove very old noise entries while preserving recent campaign history.</div>
    </div>
  </div>
</div>

<?php endif; ?>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
