<?php
$pageTitle = 'Activity Logs';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
$restaurants = $db->query("SELECT id, name FROM restaurants ORDER BY name ASC")->fetchAll();

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $sql = "SELECT al.*, u.name as user_name, r.name as restaurant_name
            FROM activity_logs al
            LEFT JOIN users u ON al.user_id = u.id
            LEFT JOIN restaurants r ON al.restaurant_id = r.id
            WHERE 1=1";
    $params = [];

    if (!empty($_GET['date_from'])) { $sql .= " AND al.created_at >= ?"; $params[] = $_GET['date_from'] . ' 00:00:00'; }
    if (!empty($_GET['date_to'])) { $sql .= " AND al.created_at <= ?"; $params[] = $_GET['date_to'] . ' 23:59:59'; }
    if (!empty($_GET['restaurant_id'])) { $sql .= " AND al.restaurant_id = ?"; $params[] = (int) $_GET['restaurant_id']; }
    if (!empty($_GET['module'])) { $sql .= " AND al.module = ?"; $params[] = $_GET['module']; }

    $sql .= " ORDER BY al.created_at DESC";
    $logs = $db->query($sql, $params)->fetchAll();

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=activity_logs_' . date('Y-m-d_His') . '.csv');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['ID', 'Date', 'User', 'Restaurant', 'Module', 'Action', 'Details', 'IP']);
    foreach ($logs as $log) {
        fputcsv($output, [
            $log['id'], $log['created_at'], $log['user_name'] ?? 'System',
            $log['restaurant_name'] ?? 'N/A', $log['module'], $log['action'],
            $log['details'], $log['ip_address']
        ]);
    }
    fclose($output);
    exit;
}

$modules = $db->query("SELECT DISTINCT module FROM activity_logs ORDER BY module ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <form class="d-flex gap-2 flex-wrap" method="GET">
        <input type="date" name="date_from" class="form-control form-control-sm" value="<?php echo sanitize($_GET['date_from'] ?? ''); ?>" style="width:150px;">
        <input type="date" name="date_to" class="form-control form-control-sm" value="<?php echo sanitize($_GET['date_to'] ?? ''); ?>" style="width:150px;">
        <select name="restaurant_id" class="form-select form-select-sm" style="width:160px;">
            <option value="">All Restaurants</option>
            <?php foreach ($restaurants as $r): ?>
                <option value="<?php echo $r['id']; ?>" <?php echo ($_GET['restaurant_id'] ?? '') == $r['id'] ? 'selected' : ''; ?>><?php echo sanitize($r['name']); ?></option>
            <?php endforeach; ?>
        </select>
        <select name="module" class="form-select form-select-sm" style="width:130px;">
            <option value="">All Modules</option>
            <?php foreach ($modules as $m): ?>
                <option value="<?php echo sanitize($m['module']); ?>" <?php echo ($_GET['module'] ?? '') === $m['module'] ? 'selected' : ''; ?>><?php echo ucfirst(sanitize($m['module'])); ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-filter"></i></button>
        <a href="activity_logs.php" class="btn btn-sm btn-outline-secondary">Reset</a>
    </form>
    <a href="?export=csv&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'export'; })); ?>" class="btn btn-sm btn-outline-success"><i class="fas fa-download me-1"></i>Export CSV</a>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable">
                <thead class="table-light">
                    <tr><th>ID</th><th>Date</th><th>User</th><th>Restaurant</th><th>Module</th><th>Action</th><th>Details</th><th>IP</th></tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT al.*, u.name as user_name, r.name as restaurant_name
                            FROM activity_logs al
                            LEFT JOIN users u ON al.user_id = u.id
                            LEFT JOIN restaurants r ON al.restaurant_id = r.id
                            WHERE 1=1";
                    $params = [];
                    if (!empty($_GET['date_from'])) { $sql .= " AND al.created_at >= ?"; $params[] = $_GET['date_from'] . ' 00:00:00'; }
                    if (!empty($_GET['date_to'])) { $sql .= " AND al.created_at <= ?"; $params[] = $_GET['date_to'] . ' 23:59:59'; }
                    if (!empty($_GET['restaurant_id'])) { $sql .= " AND al.restaurant_id = ?"; $params[] = (int) $_GET['restaurant_id']; }
                    if (!empty($_GET['module'])) { $sql .= " AND al.module = ?"; $params[] = $_GET['module']; }
                    $sql .= " ORDER BY al.created_at DESC LIMIT 500";
                    $logs = $db->query($sql, $params)->fetchAll();
                    ?>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?php echo $log['id']; ?></td>
                        <td style="white-space:nowrap;"><?php echo formatDateTime($log['created_at']); ?></td>
                        <td><?php echo sanitize($log['user_name'] ?? 'System'); ?></td>
                        <td><?php echo sanitize($log['restaurant_name'] ?? '-'); ?></td>
                        <td><span class="badge bg-secondary"><?php echo sanitize($log['module']); ?></span></td>
                        <td><span class="badge bg-info"><?php echo sanitize($log['action']); ?></span></td>
                        <td style="max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo sanitize($log['details']); ?>"><?php echo sanitize(truncate($log['details'], 60)); ?></td>
                        <td><code><?php echo sanitize($log['ip_address']); ?></code></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
