<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$search = $_GET['search'] ?? '';
$action_filter = $_GET['action'] ?? '';
$module_filter = $_GET['module'] ?? '';
$user_filter = $_GET['user_id'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$sql = "SELECT al.*, u.username, u.full_name, u.email
        FROM activity_log al
        LEFT JOIN users u ON al.user_id = u.user_id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (al.action LIKE ? OR al.module LIKE ? OR u.username LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'sss';
}

if (!empty($action_filter)) {
    $sql .= " AND al.action = ?";
    $params[] = $action_filter;
    $types .= 's';
}

if (!empty($module_filter)) {
    $sql .= " AND al.module = ?";
    $params[] = $module_filter;
    $types .= 's';
}

if (!empty($user_filter)) {
    $sql .= " AND al.user_id = ?";
    $params[] = $user_filter;
    $types .= 'i';
}

if (!empty($start_date)) {
    $sql .= " AND DATE(al.logged_at) >= ?";
    $params[] = $start_date;
    $types .= 's';
}

if (!empty($end_date)) {
    $sql .= " AND DATE(al.logged_at) <= ?";
    $params[] = $end_date;
    $types .= 's';
}

$sql .= " ORDER BY al.logged_at DESC LIMIT 500";

// Get users for filter
$sql_users = "SELECT user_id, username, full_name FROM users ORDER BY full_name";
$result_users = $conn->query($sql_users);

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Audit Logs')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Audit Logs')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by action, module, or user">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Action</label>
                                            <select class="form-select" name="action">
                                                <option value="">All Actions</option>
                                                <option value="CREATE" <?php echo $action_filter == 'CREATE' ? 'selected' : ''; ?>>Create</option>
                                                <option value="UPDATE" <?php echo $action_filter == 'UPDATE' ? 'selected' : ''; ?>>Update</option>
                                                <option value="DELETE" <?php echo $action_filter == 'DELETE' ? 'selected' : ''; ?>>Delete</option>
                                                <option value="LOGIN" <?php echo $action_filter == 'LOGIN' ? 'selected' : ''; ?>>Login</option>
                                                <option value="LOGOUT" <?php echo $action_filter == 'LOGOUT' ? 'selected' : ''; ?>>Logout</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Module</label>
                                            <select class="form-select" name="module">
                                                <option value="">All Modules</option>
                                                <option value="PROPERTY" <?php echo $module_filter == 'PROPERTY' ? 'selected' : ''; ?>>Property</option>
                                                <option value="LEASE" <?php echo $module_filter == 'LEASE' ? 'selected' : ''; ?>>Lease</option>
                                                <option value="INVOICE" <?php echo $module_filter == 'INVOICE' ? 'selected' : ''; ?>>Invoice</option>
                                                <option value="PAYMENT" <?php echo $module_filter == 'PAYMENT' ? 'selected' : ''; ?>>Payment</option>
                                                <option value="MAINTENANCE" <?php echo $module_filter == 'MAINTENANCE' ? 'selected' : ''; ?>>Maintenance</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">User</label>
                                            <select class="form-select" name="user_id">
                                                <option value="">All Users</option>
                                                <?php while($user = $result_users->fetch_assoc()): ?>
                                                    <option value="<?php echo $user['user_id']; ?>" 
                                                            <?php echo $user_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($user['full_name'] ?? $user['username']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Date Range</label>
                                            <div class="input-group">
                                                <input type="date" class="form-control" name="start_date" 
                                                       value="<?php echo htmlspecialchars($start_date); ?>" 
                                                       placeholder="Start">
                                                <input type="date" class="form-control" name="end_date" 
                                                       value="<?php echo htmlspecialchars($end_date); ?>" 
                                                       placeholder="End">
                                            </div>
                                        </div>
                                    </form>
                                    <div class="mt-3">
                                        <button type="submit" form="filterForm" class="btn btn-primary">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                        <a href="audit_logs.php" class="btn btn-light ms-2">
                                            <i class="ri-refresh-line me-1"></i>Reset
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Activity Logs</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Timestamp</th>
                                                    <th>User</th>
                                                    <th>Action</th>
                                                    <th>Module</th>
                                                    <th>Record ID</th>
                                                    <th>IP Address</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($log = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <?php echo date('M d, Y H:i:s', strtotime($log['logged_at'])); ?>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($log['full_name'] ?? $log['username'] ?? 'System'); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($log['email'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $action_colors = [
                                                                    'CREATE' => 'success',
                                                                    'UPDATE' => 'info',
                                                                    'DELETE' => 'danger',
                                                                    'LOGIN' => 'primary',
                                                                    'LOGOUT' => 'secondary'
                                                                ];
                                                                $color = $action_colors[$log['action']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo htmlspecialchars($log['action']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-secondary text-secondary">
                                                                    <?php echo htmlspecialchars($log['module']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($log['record_id']): ?>
                                                                    <span class="fw-semibold">#<?php echo $log['record_id']; ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="font-monospace small"><?php echo htmlspecialchars($log['ip_address'] ?? 'N/A'); ?></span>
                                                            </td>
                                                            <td>
                                                                <button class="btn btn-soft-secondary btn-sm" 
                                                                        onclick="viewLogDetails(<?php echo $log['log_id']; ?>)">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No logs found</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        function viewLogDetails(logId) {
            // Open modal or redirect to log details page
            window.location.href = 'log_details.php?id=' + logId;
        }
    </script>
</body>
</html>
