<?php
require_once '../config/config.php';
require_once '../includes/audit_trail.php';
requireLogin('admin');

$database = new Database();
$db = $database->getConnection();
$auditTrail = new AuditTrail($db);

// Get filter parameters
$filters = [
    'user_type' => isset($_GET['user_type']) ? $_GET['user_type'] : '',
    'email' => isset($_GET['email']) ? sanitize($_GET['email']) : '',
    'status' => isset($_GET['status']) ? $_GET['status'] : '',
    'action' => isset($_GET['action']) ? $_GET['action'] : '',
    'ip_address' => isset($_GET['ip_address']) ? sanitize($_GET['ip_address']) : '',
    'date_from' => isset($_GET['date_from']) ? $_GET['date_from'] : '',
    'date_to' => isset($_GET['date_to']) ? $_GET['date_to'] : ''
];

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50;

// Get audit trail data
$data = $auditTrail->getAuditTrail($filters, $page, $limit);
$records = $data['records'];
$total_records = $data['total'];
$total_pages = $data['pages'];

// Get login statistics
$stats = $auditTrail->getLoginStats(30);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audit Trail - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .audit-table {
            font-size: 0.9rem;
        }
        .status-success { color: #28a745; }
        .status-failed { color: #dc3545; }
        .status-blocked { color: #fd7e14; }
        .filter-section {
            background-color: #f8f9fa;
            border-radius: 8px;
        }
        .bright-header {
            background: #ff6600 !important;
            color: white !important;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.4);
        }
        .bright-header th {
            border: none !important;
            padding: 15px 10px !important;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-shield-alt me-2"></i>Admin Panel
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="dashboard.php">
                    <i class="fas fa-home me-1"></i>Dashboard
                </a>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-12">
                <h1><i class="fas fa-clipboard-list me-2"></i>Audit Trail</h1>
                <p class="text-muted">Monitor user login activities and system access</p>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h3><?php echo $total_records; ?></h3>
                        <p class="mb-0">Total Records</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <?php
                        $today_logins = 0;
                        foreach ($stats as $stat) {
                            if ($stat['date'] === date('Y-m-d') && $stat['status'] === 'success') {
                                $today_logins += $stat['count'];
                            }
                        }
                        ?>
                        <h3><?php echo $today_logins; ?></h3>
                        <p class="mb-0">Today's Logins</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <?php
                        $failed_today = 0;
                        foreach ($stats as $stat) {
                            if ($stat['date'] === date('Y-m-d') && $stat['status'] === 'failed') {
                                $failed_today += $stat['count'];
                            }
                        }
                        ?>
                        <h3><?php echo $failed_today; ?></h3>
                        <p class="mb-0">Failed Attempts Today</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <?php
                        $blocked_today = 0;
                        foreach ($stats as $stat) {
                            if ($stat['date'] === date('Y-m-d') && $stat['status'] === 'blocked') {
                                $blocked_today += $stat['count'];
                            }
                        }
                        ?>
                        <h3><?php echo $blocked_today; ?></h3>
                        <p class="mb-0">Blocked Attempts Today</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filters</h5>
            </div>
            <div class="card-body filter-section">
                <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label">User Type</label>
                        <select name="user_type" class="form-select">
                            <option value="">All Types</option>
                            <option value="admin" <?php echo $filters['user_type'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                            <option value="company" <?php echo $filters['user_type'] === 'company' ? 'selected' : ''; ?>>Company</option>
                            <option value="candidate" <?php echo $filters['user_type'] === 'candidate' ? 'selected' : ''; ?>>Candidate</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All Status</option>
                            <option value="success" <?php echo $filters['status'] === 'success' ? 'selected' : ''; ?>>Success</option>
                            <option value="failed" <?php echo $filters['status'] === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="blocked" <?php echo $filters['status'] === 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Action</label>
                        <select name="action" class="form-select">
                            <option value="">All Actions</option>
                            <option value="login" <?php echo $filters['action'] === 'login' ? 'selected' : ''; ?>>Login</option>
                            <option value="logout" <?php echo $filters['action'] === 'logout' ? 'selected' : ''; ?>>Logout</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($filters['email']); ?>" placeholder="Search email">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">From Date</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo $filters['date_from']; ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">To Date</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo $filters['date_to']; ?>">
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search me-1"></i>Filter
                        </button>
                        <a href="audit-trail.php" class="btn btn-secondary">
                            <i class="fas fa-undo me-1"></i>Reset
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Audit Trail Table -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-list me-2"></i>Audit Records</h5>
                <span class="badge bg-info">Total: <?php echo $total_records; ?> records</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped audit-table">
                        <thead class="bright-header">
                            <tr>
                                <th>Date/Time</th>
                                <th>User</th>
                                <th>User Type</th>
                                <th>Action</th>
                                <th>Status</th>
                                <th>IP Address</th>
                                <th>Failure Reason</th>
                                <th>User Agent</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($records)): ?>
                                <tr>
                                    <td colspan="8" class="text-center py-4">
                                        <i class="fas fa-search text-muted fa-3x mb-3"></i>
                                        <p class="text-muted">No audit records found matching your criteria</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($records as $record): ?>
                                    <tr>
                                        <td><?php echo formatDateTime($record['created_at']); ?></td>
                                        <td>
                                            <strong><?php echo htmlspecialchars($record['email']); ?></strong>
                                            <?php if ($record['user_id']): ?>
                                                <br><small class="text-muted">ID: <?php echo $record['user_id']; ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php 
                                                echo $record['user_type'] === 'admin' ? 'danger' : 
                                                    ($record['user_type'] === 'company' ? 'warning' : 'info'); 
                                            ?>">
                                                <?php echo ucfirst($record['user_type']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <i class="fas fa-<?php echo $record['action'] === 'login' ? 'sign-in-alt' : 'sign-out-alt'; ?> me-1"></i>
                                            <?php echo ucfirst($record['action']); ?>
                                        </td>
                                        <td>
                                            <span class="status-<?php echo $record['status']; ?>">
                                                <i class="fas fa-<?php 
                                                    echo $record['status'] === 'success' ? 'check-circle' : 
                                                        ($record['status'] === 'failed' ? 'times-circle' : 'ban'); 
                                                ?> me-1"></i>
                                                <?php echo ucfirst($record['status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($record['ip_address']); ?></td>
                                        <td>
                                            <?php if ($record['failure_reason']): ?>
                                                <span class="text-danger"><?php echo htmlspecialchars($record['failure_reason']); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="text-muted small" title="<?php echo htmlspecialchars($record['user_agent']); ?>">
                                                <?php echo substr(htmlspecialchars($record['user_agent']), 0, 50); ?>...
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Audit trail pagination">
                        <ul class="pagination justify-content-center mt-4">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                        <i class="fas fa-chevron-left"></i> Previous
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                        Next <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>