<?php
// Disable/enable audit trail. Two modes:
//   - With ?id=N: per-site history (200 most-recent rows from site_disable_audit)
//   - Without an id: global feed of recent activity across BOTH the site-level
//     and account-level audit tables, interleaved by timestamp.
//
// Root-only.

require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/permission_checker.php');

if (!is_root_user()) {
    http_response_code(403);
    echo '<div class="alert alert-danger"><i class="fa fa-lock me-2"></i>Access denied: root only.</div>';
    return;
}

$site_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();
if (!$db) {
    echo '<div class="alert alert-danger">Database connection failed.</div>';
    return;
}

$mode = $site_id > 0 ? 'per_site' : 'global';

if ($mode === 'per_site') {
    $stmt = $db->prepare("SELECT site_name, username FROM whp.sites WHERE id = ? LIMIT 1");
    $stmt->execute([$site_id]);
    $site = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt2 = $db->prepare(
        "SELECT id, 'site' AS scope, action, reason, actor, note, created_at, site_id, NULL AS username
           FROM whp.site_disable_audit
          WHERE site_id = :id
          ORDER BY created_at DESC
          LIMIT 200"
    );
    $stmt2->execute(['id' => $site_id]);
    $rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);
} else {
    // Global feed: union site_disable_audit + account_disable_audit, sorted by time.
    // account_disable_audit might not exist on hosts that haven't run the v124+ migration
    // yet — guard with a try/catch and fall back to site-only.
    try {
        $rows = $db->query(
            "SELECT id, 'site' AS scope, action, reason, actor, note, created_at,
                    site_id, NULL AS username
               FROM whp.site_disable_audit
              UNION ALL
             SELECT id, 'account' AS scope, action, reason, actor, note, created_at,
                    NULL AS site_id, username
               FROM whp.account_disable_audit
              ORDER BY created_at DESC
              LIMIT 200"
        )->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $rows = $db->query(
            "SELECT id, 'site' AS scope, action, reason, actor, note, created_at,
                    site_id, NULL AS username
               FROM whp.site_disable_audit
              ORDER BY created_at DESC
              LIMIT 200"
        )->fetchAll(PDO::FETCH_ASSOC);
    }

    // Resolve site_id -> "site_name (username)" for site-scoped rows, one query
    $site_ids = array_values(array_unique(array_filter(array_column($rows, 'site_id'))));
    $site_labels = [];
    if (!empty($site_ids)) {
        $placeholders = implode(',', array_fill(0, count($site_ids), '?'));
        $stmt = $db->prepare("SELECT id, site_name, username FROM whp.sites WHERE id IN ($placeholders)");
        $stmt->execute($site_ids);
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $site_labels[(int)$r['id']] = $r['site_name'] . ' (' . $r['username'] . ')';
        }
    }
}
?>

<div class="row">
    <div class="col-12">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <div>
                <?php if ($mode === 'per_site'): ?>
                    <?php if (!empty($site)): ?>
                        <h4 class="mb-1">
                            Disable/Enable Audit &mdash;
                            <?php echo htmlspecialchars($site['site_name']); ?>
                            <small class="text-muted">(<?php echo htmlspecialchars($site['username']); ?>)</small>
                        </h4>
                    <?php else: ?>
                        <h4 class="mb-1">Disable/Enable Audit &mdash; Site #<?php echo $site_id; ?></h4>
                    <?php endif; ?>
                    <small class="text-muted">Showing up to 200 most recent entries, newest first.</small>
                <?php else: ?>
                    <h4 class="mb-1">Disable/Enable Audit &mdash; Recent Activity</h4>
                    <small class="text-muted">
                        Up to 200 most recent disable/enable events across all sites and accounts.
                        Filter to a single site via <code>?page=site-audit&amp;id=N</code>.
                    </small>
                <?php endif; ?>
            </div>
            <?php if ($mode === 'per_site'): ?>
                <a href="index.php?page=site-audit" class="btn btn-sm btn-outline-secondary me-2">
                    <i class="fa fa-list me-1"></i>All activity
                </a>
            <?php endif; ?>
            <a href="index.php?page=sites" class="btn btn-sm btn-outline-secondary">
                <i class="fa fa-arrow-left me-1"></i>Back to Sites
            </a>
        </div>

        <?php if (empty($rows)): ?>
        <div class="alert alert-info">
            <i class="fa fa-info-circle me-2"></i>No audit entries found.
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0" data-whp-table data-whp-page-size="25">
                        <thead>
                            <tr>
                                <th>When</th>
                                <th>Scope</th>
                                <th>Target</th>
                                <th>Action</th>
                                <th>Reason</th>
                                <th>Actor</th>
                                <th>Note</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($rows as $row):
                            $scope = $row['scope'] ?? 'site';
                            if ($scope === 'site') {
                                $sid = (int)($row['site_id'] ?? 0);
                                if ($mode === 'per_site') {
                                    $target = '#' . $sid;
                                } else {
                                    $target = $site_labels[$sid] ?? ('Site #' . $sid);
                                }
                            } else {
                                $target = $row['username'] ?? '';
                            }
                        ?>
                            <tr>
                                <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                                <td>
                                    <?php if ($scope === 'account'): ?>
                                        <span class="badge bg-info text-dark">account</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">site</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($target); ?></td>
                                <td>
                                    <?php if ($row['action'] === 'disable'): ?>
                                        <span class="badge bg-danger">disable</span>
                                    <?php elseif ($row['action'] === 'enable'): ?>
                                        <span class="badge bg-success">enable</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary"><?php echo htmlspecialchars($row['action']); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($row['reason'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($row['actor']); ?></td>
                                <td><?php echo htmlspecialchars($row['note'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
<script src="/js/whp-table.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
