<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Audit Logs Viewer
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('users.audit');

// Set page title
$page_title = 'Audit Logs';

// Get current user
$current_user = current_user();

// Get filter parameters
$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
$action = isset($_GET['action']) ? sanitize_input($_GET['action']) : '';
$table = isset($_GET['table']) ? sanitize_input($_GET['table']) : '';
$record_id = isset($_GET['record_id']) ? (int)$_GET['record_id'] : null;
$date_from = isset($_GET['date_from']) ? sanitize_input($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? sanitize_input($_GET['date_to']) : '';
$search = isset($_GET['search']) ? sanitize_input($_GET['search']) : '';
$sort = $_GET['sort'] ?? 'created_at';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : ITEMS_PER_PAGE;

// Build where clause
$where = "1=1";
$params = [];

if ($user_id) {
    $where .= " AND user_id = ?";
    $params[] = $user_id;
}

if ($action) {
    $where .= " AND action = ?";
    $params[] = $action;
}

if ($table) {
    $where .= " AND table_name = ?";
    $params[] = $table;
}

if ($record_id) {
    $where .= " AND record_id = ?";
    $params[] = $record_id;
}

if ($date_from) {
    $where .= " AND DATE(created_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where .= " AND DATE(created_at) <= ?";
    $params[] = $date_to;
}

if ($search) {
    $where .= " AND (ip_address LIKE ? OR user_agent LIKE ? OR request_uri LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term]);
}

// Validate sort
$allowed_sort = ['log_id', 'user_id', 'action', 'table_name', 'record_id', 'ip_address', 'created_at'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'created_at';
}

// Get audit logs with pagination and user info
$sql = "
    SELECT a.*, u.username, u.first_name, u.last_name 
    FROM audit_logs a
    LEFT JOIN users u ON a.user_id = u.user_id
    WHERE $where
    ORDER BY a.$sort $order
";

// Get total count
$count_sql = "SELECT COUNT(*) FROM audit_logs a WHERE $where";
$total = db_fetch_value($count_sql, $params);

// Get paginated data
$offset = ($page - 1) * $per_page;
$data_sql = $sql . " LIMIT $per_page OFFSET $offset";
$logs = db_fetch_all($data_sql, $params);

// Calculate pagination
$total_pages = ceil($total / $per_page);
$has_previous = $page > 1;
$has_next = $page < $total_pages;

// Get filter options
$users = db_fetch_all("SELECT user_id, username, first_name, last_name FROM users ORDER BY username");
$actions = db_fetch_all("SELECT DISTINCT action FROM audit_logs ORDER BY action");
$tables = db_fetch_all("SELECT DISTINCT table_name FROM audit_logs WHERE table_name IS NOT NULL ORDER BY table_name");

// Get summary statistics
$stats = [
    'total' => $total,
    'unique_users' => db_fetch_value("SELECT COUNT(DISTINCT user_id) FROM audit_logs"),
    'today' => db_fetch_value("SELECT COUNT(*) FROM audit_logs WHERE DATE(created_at) = CURDATE()"),
    'this_week' => db_fetch_value("SELECT COUNT(*) FROM audit_logs WHERE YEARWEEK(created_at) = YEARWEEK(NOW())")
];

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.php';
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Audit Logs</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/users/index.php'); ?>">Users</a></li>
                    <li class="breadcrumb-item active">Audit Logs</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Stats Row -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total']; ?></h3>
                        <p>Total Log Entries</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-history"></i>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['unique_users']; ?></h3>
                        <p>Active Users</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['today']; ?></h3>
                        <p>Today's Logs</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-day"></i>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['this_week']; ?></h3>
                        <p>This Week</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-week"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter mr-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="user_id">
                            <option value="">All Users</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['user_id']; ?>" <?php echo $user_id == $user['user_id'] ? 'selected' : ''; ?>>
                                    <?php echo escape_html($user['username'] . ' - ' . $user['first_name'] . ' ' . $user['last_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="action">
                            <option value="">All Actions</option>
                            <?php foreach ($actions as $act): ?>
                                <option value="<?php echo $act['action']; ?>" <?php echo $action == $act['action'] ? 'selected' : ''; ?>>
                                    <?php echo ucfirst($act['action']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="table">
                            <option value="">All Tables</option>
                            <?php foreach ($tables as $tbl): ?>
                                <option value="<?php echo $tbl['table_name']; ?>" <?php echo $table == $tbl['table_name'] ? 'selected' : ''; ?>>
                                    <?php echo str_replace('_', ' ', ucfirst($tbl['table_name'])); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <input type="number" class="form-control" name="record_id" placeholder="Record ID" 
                               value="<?php echo $record_id; ?>" style="width: 100px;">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <input type="text" class="form-control" name="search" placeholder="Search IP/Agent/URI" 
                               value="<?php echo escape_html($search); ?>" style="min-width: 200px;">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <select class="form-control" name="per_page">
                            <option value="25" <?php echo $per_page == 25 ? 'selected' : ''; ?>>25 per page</option>
                            <option value="50" <?php echo $per_page == 50 ? 'selected' : ''; ?>>50 per page</option>
                            <option value="100" <?php echo $per_page == 100 ? 'selected' : ''; ?>>100 per page</option>
                            <option value="250" <?php echo $per_page == 250 ? 'selected' : ''; ?>>250 per page</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filters
                    </button>
                    
                    <a href="?" class="btn btn-secondary mb-2">
                        <i class="fas fa-times mr-1"></i> Clear
                    </a>
                    
                    <button type="button" class="btn btn-success mb-2 ml-auto" onclick="exportLogs()">
                        <i class="fas fa-download mr-1"></i> Export
                    </button>
                </form>
            </div>
        </div>

        <!-- Logs Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-list mr-1"></i>
                    Audit Log Entries (<?php echo $total; ?> total)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>
                                    <a href="?sort=log_id&order=<?php echo $sort === 'log_id' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&user_id=<?php echo $user_id; ?>&action=<?php echo urlencode($action); ?>&table=<?php echo urlencode($table); ?>&record_id=<?php echo $record_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>&per_page=<?php echo $per_page; ?>">
                                                    ID
                                                    <?php if ($sort === 'log_id'): ?>
                                                        <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                                    <?php endif; ?>
                                </th>
                                <th>
                                    <a href="?sort=created_at&order=<?php echo $sort === 'created_at' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&user_id=<?php echo $user_id; ?>&action=<?php echo urlencode($action); ?>&table=<?php echo urlencode($table); ?>&record_id=<?php echo $record_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>&per_page=<?php echo $per_page; ?>">
                                                    Timestamp
                                                    <?php if ($sort === 'created_at'): ?>
                                                        <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                                    <?php endif; ?>
                                </th>
                                <th>User</th>
                                <th>Action</th>
                                <th>Table</th>
                                <th>Record</th>
                                <th>IP Address</th>
                                <th>Changes</th>
                                <th width="50"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($logs)): ?>
                                <tr>
                                    <td colspan="9" class="text-center text-muted py-4">
                                        <i class="fas fa-history fa-3x mb-3"></i>
                                        <p>No audit logs found</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($logs as $log): ?>
                                <tr>
                                    <td><?php echo $log['log_id']; ?></td>
                                    <td>
                                        <?php echo format_datetime($log['created_at']); ?>
                                        <br>
                                        <small class="text-muted"><?php echo time_ago($log['created_at']); ?></small>
                                    </td>
                                    <td>
                                        <?php if ($log['user_id']): ?>
                                            <a href="<?php echo base_url('admin/users/view.php?id=' . $log['user_id']); ?>">
                                                <?php echo escape_html($log['username'] ?: 'User#' . $log['user_id']); ?>
                                            </a>
                                            <br>
                                            <small class="text-muted"><?php echo escape_html($log['first_name'] . ' ' . $log['last_name']); ?></small>
                                        <?php else: ?>
                                            <span class="text-muted">System</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?php 
                                            echo $log['action'] == 'login' ? 'success' : 
                                                ($log['action'] == 'logout' ? 'warning' : 
                                                ($log['action'] == 'create' ? 'info' : 
                                                ($log['action'] == 'update' ? 'primary' : 
                                                ($log['action'] == 'delete' ? 'danger' : 
                                                ($log['action'] == 'login_failed' ? 'danger' : 'secondary')))));
                                        ?>">
                                            <?php echo ucfirst($log['action']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($log['table_name']): ?>
                                            <span class="badge badge-secondary">
                                                <?php echo str_replace('_', ' ', $log['table_name']); ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($log['record_id']): ?>
                                            <span class="badge badge-info">#<?php echo $log['record_id']; ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <code><?php echo $log['ip_address'] ?? 'N/A'; ?></code>
                                    </td>
                                    <td>
                                        <?php if ($log['old_values'] || $log['new_values']): ?>
                                            <button type="button" class="btn btn-sm btn-info" 
                                                    onclick="showAuditDetails(<?php echo $log['log_id']; ?>)">
                                                <i class="fas fa-code-branch"></i> View
                                            </button>
                                            
                                            <!-- Hidden data for modal -->
                                            <div id="audit-data-<?php echo $log['log_id']; ?>" style="display: none;">
                                                <div class="old-values"><?php echo escape_html($log['old_values']); ?></div>
                                                <div class="new-values"><?php echo escape_html($log['new_values']); ?></div>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="?record_id=<?php echo $log['record_id']; ?>&table=<?php echo urlencode($log['table_name']); ?>" 
                                           class="btn btn-sm btn-secondary" title="Filter by this record">
                                            <i class="fas fa-filter"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <div class="row">
                    <div class="col-sm-5">
                        <span class="text-muted">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> entries
                        </span>
                    </div>
                    <div class="col-sm-7">
                        <ul class="pagination pagination-sm m-0 float-right">
                            <?php if ($has_previous): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&user_id=<?php echo $user_id; ?>&action=<?php echo urlencode($action); ?>&table=<?php echo urlencode($table); ?>&record_id=<?php echo $record_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>&per_page=<?php echo $per_page; ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&user_id=<?php echo $user_id; ?>&action=<?php echo urlencode($action); ?>&table=<?php echo urlencode($table); ?>&record_id=<?php echo $record_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>&per_page=<?php echo $per_page; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($has_next): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&user_id=<?php echo $user_id; ?>&action=<?php echo urlencode($action); ?>&table=<?php echo urlencode($table); ?>&record_id=<?php echo $record_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>&per_page=<?php echo $per_page; ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Audit Details Modal -->
<div class="modal fade" id="auditDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Audit Details</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Old Values</h6>
                        <pre id="modalOldValues" class="bg-light p-3 rounded" style="max-height: 400px; overflow: auto;"></pre>
                    </div>
                    <div class="col-md-6">
                        <h6>New Values</h6>
                        <pre id="modalNewValues" class="bg-light p-3 rounded" style="max-height: 400px; overflow: auto;"></pre>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
function showAuditDetails(logId) {
    const auditData = document.getElementById('audit-data-' + logId);
    if (!auditData) return;
    
    const oldValues = auditData.querySelector('.old-values').textContent;
    const newValues = auditData.querySelector('.new-values').textContent;
    
    document.getElementById('modalOldValues').textContent = oldValues ? JSON.stringify(JSON.parse(oldValues), null, 2) : 'No old values';
    document.getElementById('modalNewValues').textContent = newValues ? JSON.stringify(JSON.parse(newValues), null, 2) : 'No new values';
    
    $('#auditDetailsModal').modal('show');
}

function exportLogs() {
    // Build current filter URL
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = '<?php echo base_url('admin/users/export-audit.php'); ?>?' + params.toString();
}

// Auto-refresh every 60 seconds (optional)
let autoRefresh = false;
function toggleAutoRefresh() {
    autoRefresh = !autoRefresh;
    if (autoRefresh) {
        setTimeout(function() {
            if (autoRefresh) location.reload();
        }, 60000);
    }
}
</script>

<!-- Add export button functionality -->
<style>
.table td {
    vertical-align: middle;
}
.badge {
    font-size: 0.85rem;
}
pre {
    font-size: 11px;
    white-space: pre-wrap;
    word-wrap: break-word;
}
</style>

<?php
// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>