<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Audit Trail Report
 * 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('reports.view');

// Set page title
$page_title = 'Audit Trail Report';

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

// Get filter parameters
$user_id = isset($_GET['user_id']) && $_GET['user_id'] !== '' ? (int)$_GET['user_id'] : null;
$action = $_GET['action'] ?? '';
$table = $_GET['table'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$search = $_GET['search'] ?? '';
$export = $_GET['export'] ?? '';

// Get users for filter
$users = db_fetch_all("SELECT user_id, username, first_name, last_name FROM users ORDER BY username");

// Get distinct actions for filter
$actions = db_fetch_all("SELECT DISTINCT action FROM audit_logs ORDER BY action");

// Get distinct tables for filter
$tables = db_fetch_all("SELECT DISTINCT table_name FROM audit_logs WHERE table_name IS NOT NULL ORDER BY table_name");

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

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

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

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

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

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

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

// Get audit logs
$logs = db_fetch_all("
    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.created_at DESC
    LIMIT 1000
", $params);

// Calculate summary statistics
$summary = [
    'total' => count($logs),
    'unique_users' => count(array_unique(array_filter(array_column($logs, 'user_id')))),
    'actions' => [],
    'tables' => []
];

foreach ($logs as $log) {
    if ($log['action']) {
        $summary['actions'][$log['action']] = ($summary['actions'][$log['action']] ?? 0) + 1;
    }
    if ($log['table_name']) {
        $summary['tables'][$log['table_name']] = ($summary['tables'][$log['table_name']] ?? 0) + 1;
    }
}

// Handle export
if ($export === 'pdf') {
    export_pdf($logs, $summary, $date_from, $date_to);
} elseif ($export === 'excel') {
    export_excel($logs, $summary, $date_from, $date_to);
} elseif ($export === 'csv') {
    export_csv($logs, $summary, $date_from, $date_to);
}

// 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 Trail Report</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="dashboard.php">Reports</a></li>
                    <li class="breadcrumb-item active">Audit Trail</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Report Controls -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <label for="user_id" class="mr-2">User:</label>
                        <select class="form-control" id="user_id" 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']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="action" class="mr-2">Action:</label>
                        <select class="form-control" id="action" 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">
                        <label for="table" class="mr-2">Table:</label>
                        <select class="form-control" id="table" 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">
                        <label for="date_from" class="mr-2">From:</label>
                        <input type="date" class="form-control" id="date_from" name="date_from" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="date_to" class="mr-2">To:</label>
                        <input type="date" class="form-control" id="date_to" 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..." 
                               value="<?php echo escape_html($search); ?>" style="min-width: 150px;">
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-search"></i> Filter
                    </button>
                    
                    <a href="?" class="btn btn-secondary mb-2 mr-2">
                        <i class="fas fa-times"></i> Clear
                    </a>
                    
                    <button type="button" class="btn btn-success mb-2 mr-2" onclick="exportReport('pdf')">
                        <i class="fas fa-file-pdf"></i> PDF
                    </button>
                    
                    <button type="button" class="btn btn-info mb-2 mr-2" onclick="exportReport('excel')">
                        <i class="fas fa-file-excel"></i> Excel
                    </button>
                    
                    <button type="button" class="btn btn-secondary mb-2" onclick="exportReport('csv')">
                        <i class="fas fa-file-csv"></i> CSV
                    </button>
                </form>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $summary['total']; ?></h3>
                        <p>Total Events</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 $summary['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 count($summary['actions']); ?></h3>
                        <p>Action Types</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tasks"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo count($summary['tables']); ?></h3>
                        <p>Tables Accessed</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-database"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Actions by Type
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="actionsChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Activity Timeline
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="timelineChart" style="height: 300px;"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Audit Log Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list mr-1"></i>
                            Audit Log Entries
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($logs)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-history fa-4x mb-3"></i>
                                <h5>No audit logs found</h5>
                                <p>Try adjusting your filters</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Timestamp</th>
                                            <th>User</th>
                                            <th>Action</th>
                                            <th>Table</th>
                                            <th>Record ID</th>
                                            <th>IP Address</th>
                                            <th>Changes</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($logs as $log): ?>
                                        <tr>
                                            <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>
                                                <?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' : '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']; ?>)">
                                                        View Changes
                                                    </button>
                                                    <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>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Audit Details Modal -->
<div class="modal fade" id="auditModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Change 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="oldValues" 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="newValues" 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>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<script>
$(document).ready(function() {
    // Actions Chart
    const actionsCtx = document.getElementById('actionsChart').getContext('2d');
    
    new Chart(actionsCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_keys($summary['actions'])); ?>,
            datasets: [{
                label: 'Action Count',
                data: <?php echo json_encode(array_values($summary['actions'])); ?>,
                backgroundColor: '#007bff',
                borderColor: '#0056b3',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
    
    // Timeline Chart
    const timelineCtx = document.getElementById('timelineChart').getContext('2d');
    
    <?php
    // Group by date
    $timeline = [];
    $current = strtotime($date_from);
    $end = strtotime($date_to);
    
    while ($current <= $end) {
        $date = date('Y-m-d', $current);
        $timeline[$date] = 0;
        $current = strtotime('+1 day', $current);
    }
    
    foreach ($logs as $log) {
        $date = date('Y-m-d', strtotime($log['created_at']));
        if (isset($timeline[$date])) {
            $timeline[$date]++;
        }
    }
    ?>
    
    new Chart(timelineCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_keys($timeline)); ?>,
            datasets: [{
                label: 'Events',
                data: <?php echo json_encode(array_values($timeline)); ?>,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
});

function showAuditDetails(logId) {
    const oldValues = $('#audit-data-' + logId + ' .old-values').text();
    const newValues = $('#audit-data-' + logId + ' .new-values').text();
    
    $('#oldValues').text(oldValues ? JSON.stringify(JSON.parse(oldValues), null, 2) : 'No old values');
    $('#newValues').text(newValues ? JSON.stringify(JSON.parse(newValues), null, 2) : 'No new values');
    
    $('#auditModal').modal('show');
}

function exportReport(format) {
    const url = new URL(window.location.href);
    url.searchParams.set('export', format);
    window.location.href = url.toString();
}
</script>

<?php
/**
 * Export as PDF
 */
function export_pdf($logs, $summary, $date_from, $date_to) {
    header('Location: export-pdf.php?report=audit&from=' . $date_from . '&to=' . $date_to);
    exit;
}

/**
 * Export as Excel
 */
function export_excel($logs, $summary, $date_from, $date_to) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="audit_report_' . $date_from . '_to_' . $date_to . '.xls"');
    
    echo "Audit Trail Report\n";
    echo "Period: " . format_date($date_from) . " to " . format_date($date_to) . "\n\n";
    
    echo "Summary\n";
    echo "Total Events\t" . $summary['total'] . "\n";
    echo "Unique Users\t" . $summary['unique_users'] . "\n\n";
    
    echo "Actions Breakdown\n";
    foreach ($summary['actions'] as $action => $count) {
        echo ucfirst($action) . "\t" . $count . "\n";
    }
    echo "\n";
    
    echo "Tables Accessed\n";
    foreach ($summary['tables'] as $table => $count) {
        echo str_replace('_', ' ', ucfirst($table)) . "\t" . $count . "\n";
    }
    echo "\n";
    
    echo "Audit Log Entries\n";
    echo "Timestamp\tUser\tAction\tTable\tRecord ID\tIP Address\n";
    
    foreach ($logs as $log) {
        $timestamp = date('Y-m-d H:i:s', strtotime($log['created_at']));
        $user = $log['username'] ?: ($log['user_id'] ? 'User #' . $log['user_id'] : 'System');
        
        echo $timestamp . "\t";
        echo $user . "\t";
        echo $log['action'] . "\t";
        echo ($log['table_name'] ?: '-') . "\t";
        echo ($log['record_id'] ?: '-') . "\t";
        echo ($log['ip_address'] ?: '-') . "\n";
    }
    
    exit;
}

/**
 * Export as CSV
 */
function export_csv($logs, $summary, $date_from, $date_to) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="audit_report_' . $date_from . '_to_' . $date_to . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Audit Trail Report']);
    fputcsv($output, ['Period:', format_date($date_from) . ' to ' . format_date($date_to)]);
    fputcsv($output, []);
    
    fputcsv($output, ['Summary']);
    fputcsv($output, ['Total Events', $summary['total']]);
    fputcsv($output, ['Unique Users', $summary['unique_users']]);
    fputcsv($output, []);
    
    fputcsv($output, ['Actions Breakdown']);
    fputcsv($output, ['Action', 'Count']);
    foreach ($summary['actions'] as $action => $count) {
        fputcsv($output, [$action, $count]);
    }
    fputcsv($output, []);
    
    fputcsv($output, ['Tables Accessed']);
    fputcsv($output, ['Table', 'Count']);
    foreach ($summary['tables'] as $table => $count) {
        fputcsv($output, [$table, $count]);
    }
    fputcsv($output, []);
    
    fputcsv($output, ['Audit Log Entries']);
    fputcsv($output, ['Timestamp', 'User', 'Action', 'Table', 'Record ID', 'IP Address']);
    
    foreach ($logs as $log) {
        fputcsv($output, [
            date('Y-m-d H:i:s', strtotime($log['created_at'])),
            $log['username'] ?: ($log['user_id'] ? 'User #' . $log['user_id'] : 'System'),
            $log['action'],
            $log['table_name'] ?: '',
            $log['record_id'] ?: '',
            $log['ip_address'] ?: ''
        ]);
    }
    
    fclose($output);
    exit;
}

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