<?php
require_once 'includes/db.php';

if (!hasRole('owner')) {
    header("Location: " . url('dashboard', ['error' => 'unauthorized']));
    exit;
}

$search = $_GET['search'] ?? '';
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';

$perPage = 20;
$page = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
$offset = ($page - 1) * $perPage;

$company_id = $_SESSION['company_id'];

$query = "SELECT * FROM audit_logs";
$countQuery = "SELECT COUNT(*) as total FROM audit_logs";
$params = [$company_id];
$conditions = ["company_id = ?"];

if ($search) {
    $conditions[] = "(user_name LIKE ? OR action LIKE ? OR details LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($from) {
    $conditions[] = "created_at >= ?";
    $params[] = $from . " 00:00:00";
}

if ($to) {
    $conditions[] = "created_at <= ?";
    $params[] = $to . " 23:59:59";
}

if (!empty($conditions)) {
    $where = " WHERE " . implode(" AND ", $conditions);
    $query .= $where;
    $countQuery .= $where;
}

$totalRecords = fetch($countQuery, $params)['total'];
$totalPages = ceil($totalRecords / $perPage);

$query .= " ORDER BY created_at DESC LIMIT $perPage OFFSET $offset";
$logs = fetchAll($query, $params);

// Helper function to get action badge color
function getActionColor($action) {
    $action = strtoupper($action);
    if (strpos($action, 'DELETE') !== false) return 'var(--danger)';
    if (strpos($action, 'LOGIN') !== false) return 'var(--success)';
    if (strpos($action, 'UPDATE') !== false || strpos($action, 'EDIT') !== false) return 'var(--warning)';
    if (strpos($action, 'CREATE') !== false || strpos($action, 'ADD') !== false) return 'var(--primary)';
    return 'var(--text-muted)';
}
?>

<div style="background: var(--bg-card); border-radius: 24px; border: 1px solid var(--border); overflow: hidden; box-shadow: var(--shadow-sm);">
    <!-- Header & Filters -->
    <div style="padding: 2rem; border-bottom: 1px solid var(--border); background: var(--bg-dark);">
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem;">
            <div>
                <h2 style="font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin-bottom: 0.25rem;">System Audit Logs</h2>
                <p style="color: var(--text-muted); font-size: 0.9rem;">Monitoring critical security events and user activities across the platform.</p>
            </div>
            <div style="background: var(--primary); color: white; padding: 0.5rem 1rem; border-radius: 12px; font-size: 0.8rem; font-weight: 700; box-shadow: 0 4px 12px rgba(124, 58, 237, 0.2);">
                <i class="fas fa-shield-alt"></i> Secure Audit
            </div>
        </div>

        <form action="<?php echo url('audit-logs'); ?>" method="GET" style="display: grid; grid-template-columns: 2fr 1fr 1fr auto; gap: 1rem; align-items: flex-end;">
            <div class="form-group" style="margin-bottom: 0;">
                <label class="form-label" style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700;">Search Logs</label>
                <div style="position: relative;">
                    <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted);"></i>
                    <input type="text" name="search" class="form-control" placeholder="User, action, or details..." value="<?php echo htmlspecialchars($search); ?>" style="padding-left: 2.75rem; border-radius: 12px; border-color: var(--border);">
                </div>
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label class="form-label" style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700;">From</label>
                <input type="date" name="from" class="form-control" value="<?php echo htmlspecialchars($from); ?>" style="border-radius: 12px; border-color: var(--border);">
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label class="form-label" style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700;">To</label>
                <input type="date" name="to" class="form-control" value="<?php echo htmlspecialchars($to); ?>" style="border-radius: 12px; border-color: var(--border);">
            </div>
            <div style="display: flex; gap: 0.5rem;">
                <button type="submit" class="btn btn-primary" style="height: 45px; border-radius: 12px; padding: 0 1.5rem; font-weight: 700; flex: 1;">
                    <i class="fas fa-filter"></i> Apply
                </button>
                <a href="<?php echo url('audit-logs'); ?>" class="btn" style="height: 45px; border-radius: 12px; padding: 0 1rem; display: flex; align-items: center; justify-content: center; background: var(--bg-card); border: 1px solid var(--border); color: var(--text-muted);">
                    <i class="fas fa-times-circle"></i>
                </a>
            </div>
        </form>
    </div>

    <!-- Table Section -->
    <div style="overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr style="background: rgba(255,255,255,0.02);">
                    <th style="padding: 1.25rem 1.5rem; text-align: left; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border);">Timestamp</th>
                    <th style="padding: 1.25rem 1.5rem; text-align: left; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border);">User Account</th>
                    <th style="padding: 1.25rem 1.5rem; text-align: left; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border);">Action</th>
                    <th style="padding: 1.25rem 1.5rem; text-align: left; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border);">Level</th>
                    <th style="padding: 1.25rem 1.5rem; text-align: left; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--border);">Activity Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): 
                    $timestamp = $log['created_at'] ? strtotime($log['created_at']) : time();
                    $actionColor = getActionColor($log['action']);
                ?>
                <tr class="audit-row" style="border-bottom: 1px solid var(--border); transition: all 0.2s;">
                    <td style="padding: 1.25rem 1.5rem;">
                        <div style="font-weight: 700; color: var(--text-main); font-size: 0.9rem;"><?php echo date('M d, Y', $timestamp); ?></div>
                        <div style="font-size: 0.75rem; color: var(--text-muted); font-family: monospace;"><?php echo date('h:i:s A', $timestamp); ?></div>
                    </td>
                    <td style="padding: 1.25rem 1.5rem;">
                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                            <div class="user-avatar" style="width: 32px; height: 32px; font-size: 0.85rem; background: var(--bg-dark); border: 1px solid var(--border); color: var(--primary);">
                                <?php echo strtoupper(substr($log['user_name'], 0, 1)); ?>
                            </div>
                            <div>
                                <div style="font-weight: 700; color: var(--text-main); font-size: 0.9rem;"><?php echo $log['user_name']; ?></div>
                                <div style="font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em;"><?php echo $log['user_role'] ?: 'Unknown'; ?></div>
                            </div>
                        </div>
                    </td>
                    <td style="padding: 1.25rem 1.5rem;">
                        <span style="font-size: 0.65rem; padding: 0.4rem 0.8rem; border-radius: 50px; background: <?php echo $actionColor; ?>15; color: <?php echo $actionColor; ?>; border: 1px solid <?php echo $actionColor; ?>30; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em;">
                            <?php echo $log['action']; ?>
                        </span>
                    </td>
                    <td style="padding: 1.25rem 1.5rem;">
                        <div style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.8rem; font-weight: 600; color: var(--text-muted);">
                            <div style="width: 6px; height: 6px; border-radius: 50%; background: <?php echo $actionColor; ?>;"></div>
                            <?php echo strtoupper($log['user_role'] ?: 'SYS'); ?>
                        </div>
                    </td>
                    <td style="padding: 1.25rem 1.5rem; max-width: 450px;">
                        <div style="font-size: 0.875rem; color: var(--text-muted); line-height: 1.5; font-style: italic;">
                            "<?php echo htmlspecialchars($log['details']); ?>"
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($logs)): ?>
                <tr>
                    <td colspan="5" style="padding: 5rem; text-align: center;">
                        <i class="fas fa-history fa-3x" style="opacity: 0.1; margin-bottom: 1rem; display: block;"></i>
                        <h3 style="color: var(--text-main);">No activity found</h3>
                        <p style="color: var(--text-muted);">Adjust your filters or try a different search term.</p>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination Footer -->
    <div style="padding: 1.5rem 2rem; background: var(--bg-dark); border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center;">
        <div style="font-size: 0.85rem; color: var(--text-muted);">
            Showing <span style="font-weight: 700; color: var(--text-main);"><?php echo $offset + 1; ?></span> to 
            <span style="font-weight: 700; color: var(--text-main);"><?php echo min($offset + $perPage, $totalRecords); ?></span> of 
            <span style="font-weight: 700; color: var(--text-main);"><?php echo $totalRecords; ?></span> events
        </div>
        
        <?php if ($totalPages > 1): ?>
        <div style="display: flex; gap: 0.5rem; align-items: center;">
            <?php 
            $baseUrl = url('audit-logs', ['search' => $search, 'from' => $from, 'to' => $to]);
            ?>
            
            <?php if ($page > 1): ?>
                <a href="<?php echo $baseUrl; ?>&p=<?php echo $page - 1; ?>" class="btn-p">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>

            <?php
            $start = max(1, $page - 2);
            $end = min($totalPages, $page + 2);
            
            if ($start > 1) {
                echo '<a href="'.$baseUrl.'&p=1" class="btn-p">1</a>';
                if ($start > 2) echo '<span style="color: var(--text-muted); padding: 0 0.5rem;">...</span>';
            }

            for ($i = $start; $i <= $end; $i++) {
                $activeClass = ($i == $page) ? 'active' : '';
                echo '<a href="'.$baseUrl.'&p='.$i.'" class="btn-p '.$activeClass.'">'.$i.'</a>';
            }

            if ($end < $totalPages) {
                if ($end < $totalPages - 1) echo '<span style="color: var(--text-muted); padding: 0 0.5rem;">...</span>';
                echo '<a href="'.$baseUrl.'&p='.$totalPages.'" class="btn-p">'.$totalPages.'</a>';
            }
            ?>

            <?php if ($page < $totalPages): ?>
                <a href="<?php echo $baseUrl; ?>&p=<?php echo $page + 1; ?>" class="btn-p">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
    .audit-row:hover { background: rgba(255,255,255,0.01); }
    .btn-p {
        min-width: 38px;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 10px;
        border: 1px solid var(--border);
        background: var(--bg-card);
        color: var(--text-main);
        font-weight: 700;
        text-decoration: none;
        font-size: 0.85rem;
        transition: all 0.2s;
    }
    .btn-p:hover {
        border-color: var(--primary);
        color: var(--primary);
        background: rgba(124, 58, 237, 0.05);
    }
    .btn-p.active {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.3);
    }
</style>
