<?php
require_once __DIR__ . '/../includes/config.php';

// Check admin permission
if (!hasPermission('admin')) {
    redirectToLogin();
}

$page_title = 'Audit Log';

require_once __DIR__ . '/../includes/header.php';

// Get users for filter
$users_result = $db->query("SELECT id, name FROM users ORDER BY name");
$users = [];
while ($u = $users_result->fetch_assoc()) {
    $users[] = $u;
}

// Get filters
$entity_filter = $_GET['entity'] ?? '';
$action_filter = $_GET['action'] ?? '';
$user_filter = $_GET['user'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 30;

// Build query
$where = "WHERE 1=1";

if (!empty($entity_filter)) {
    $entity_filter_esc = escape($entity_filter);
    $where .= " AND entity_type = '$entity_filter_esc'";
}

if (!empty($action_filter)) {
    $action_filter_esc = escape($action_filter);
    $where .= " AND action = '$action_filter_esc'";
}

if (!empty($user_filter)) {
    $user_filter = (int)$user_filter;
    $where .= " AND user_id = $user_filter";
}

if (!empty($date_from)) {
    $date_from_esc = escape($date_from);
    $where .= " AND DATE(created_at) >= '$date_from_esc'";
}

if (!empty($date_to)) {
    $date_to_esc = escape($date_to);
    $where .= " AND DATE(created_at) <= '$date_to_esc'";
}

// Count total
$count_result = $db->query("SELECT COUNT(*) as cnt FROM audit_logs $where");
$total = $count_result->fetch_assoc()['cnt'];
$pages = ceil($total / $per_page);
$offset = ($page - 1) * $per_page;

// Get logs
$query = "SELECT al.*, u.name as user_name FROM audit_logs al
          LEFT JOIN users u ON al.user_id = u.id
          $where
          ORDER BY al.created_at DESC
          LIMIT $offset, $per_page";

$result = $db->query($query);
$logs = [];
while ($log = $result->fetch_assoc()) {
    $logs[] = $log;
}

// Get available entity types and actions
$entity_types_result = $db->query("SELECT DISTINCT entity_type FROM audit_logs ORDER BY entity_type");
$entity_types = [];
while ($et = $entity_types_result->fetch_assoc()) {
    $entity_types[] = $et['entity_type'];
}

$actions_result = $db->query("SELECT DISTINCT action FROM audit_logs ORDER BY action");
$actions = [];
while ($a = $actions_result->fetch_assoc()) {
    $actions[] = $a['action'];
}
?>

<style>
@media (max-width: 768px) {
    .filter-grid { display: grid; grid-template-columns: 1fr; gap: 10px; }
    .filter-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
    .filter-row.full { grid-column: 1 / -1; }
    .table-wrap { display: none; }
    .logs-mobile { display: block; }
}
@media (min-width: 769px) {
    .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; align-items: end; }
    .filter-row { display: contents; }
    .table-wrap { display: block; }
    .logs-mobile { display: none; }
}
.log-card { background: var(--bg2); border: 1px solid var(--border); border-radius: 10px; padding: 14px; margin-bottom: 12px; }
.log-card-header { display: flex; justify-content: space-between; align-items: start; gap: 10px; }
.log-card-title { font-weight: 600; font-size: 13px; color: var(--text); }
.log-card-sub { font-size: 12px; color: var(--text2); margin-top: 4px; }
.log-card-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; font-size: 12px; }
.log-card-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; }
.log-card-details { margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
.log-card-details-row { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 6px; }
.log-card-json { background: var(--bg3); padding: 10px; border-radius: 6px; font-size: 11px; font-family: monospace; overflow-x: auto; margin-top: 8px; color: var(--text2); }
</style>

<div class="filter-grid">
    <form method="GET" style="display: contents">
        <div class="filter-row">
            <div>
                <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Entitate</label>
                <select name="entity" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
                    <option value="">Toate</option>
                    <?php foreach ($entity_types as $et): ?>
                        <option value="<?php echo htmlspecialchars($et); ?>" <?php echo ($_GET['entity'] ?? '') == $et ? 'selected' : ''; ?>><?php echo htmlspecialchars(ucfirst($et)); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Acțiune</label>
                <select name="action" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
                    <option value="">Toate</option>
                    <?php foreach ($actions as $a): ?>
                        <option value="<?php echo htmlspecialchars($a); ?>" <?php echo ($_GET['action'] ?? '') == $a ? 'selected' : ''; ?>><?php echo htmlspecialchars(ucfirst($a)); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <div class="filter-row">
            <div>
                <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Utilizator</label>
                <select name="user" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
                    <option value="">Toți</option>
                    <?php foreach ($users as $u): ?>
                        <option value="<?php echo $u['id']; ?>" <?php echo ($_GET['user'] ?? '') == $u['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($u['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">De la</label>
                <input type="date" name="date_from" value="<?php echo htmlspecialchars($_GET['date_from'] ?? ''); ?>" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
            </div>
        </div>
        
        <div class="filter-row full">
            <div style="grid-column: 1">
                <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Până la</label>
                <input type="date" name="date_to" value="<?php echo htmlspecialchars($_GET['date_to'] ?? ''); ?>" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
            </div>
            
            <div style="display:flex;gap:6px;grid-column: 1 / -1">
                <button type="submit" class="btn btn-primary" style="flex:1">🔍 Filtreaza</button>
                <a href="<?php echo APP_URL; ?>/admin/audit.php" class="btn btn-ghost" style="text-decoration:none;text-align:center;flex:1">↻ Reset</a>
            </div>
        </div>
    </form>
</div>

<div style="display:flex;justify-content:space-between;align-items:center;margin:16px 0">
    <div style="color:var(--text2);font-size:13px">
        <?php echo $total; ?> loguri
    </div>
</div>

<!-- DESKTOP TABLE VIEW -->
<div class="card table-wrap">
    <div style="overflow-x:auto">
        <table>
            <thead>
                <tr>
                    <th>Data/Ora</th>
                    <th>Utilizator</th>
                    <th>Acțiune</th>
                    <th>Entitate</th>
                    <th>Cine/Ce</th>
                    <th>IP</th>
                    <th style="text-align:right">Detalii</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="7">
                            <div class="empty-state">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/></svg>
                                <h3>Niciun log</h3>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): 
                        $action_colors = [
                            'create' => '#3DB87A',
                            'update' => '#E8C24A',
                            'delete' => '#E05252',
                            'view' => '#4A8FD4'
                        ];
                        $action_color = $action_colors[$log['action']] ?? '#9A9590';
                    ?>
                        <tr style="cursor:pointer" onclick="toggleDetails(<?php echo $log['id']; ?>)">
                            <td style="font-size:12px;color:var(--text3)"><?php echo date('d.m H:i', strtotime($log['created_at'])); ?></td>
                            <td style="font-size:12px"><?php echo htmlspecialchars($log['user_name'] ?: 'Sistema'); ?></td>
                            <td>
                                <span class="badge" style="background:<?php echo $action_color; ?>22;color:<?php echo $action_color; ?>">
                                    <span style="background:<?php echo $action_color; ?>;width:5px;height:5px;border-radius:50%;display:inline-block;margin-right:4px"></span>
                                    <?php echo htmlspecialchars(ucfirst($log['action'])); ?>
                                </span>
                            </td>
                            <td style="font-size:12px;color:var(--text2)"><?php echo htmlspecialchars(ucfirst($log['entity_type'])); ?></td>
                            <td style="font-size:12px;color:var(--text3);max-width:200px;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($log['entity_name'] ?: '—'); ?></td>
                            <td style="font-size:11px;color:var(--text3)"><?php echo htmlspecialchars($log['ip_address']); ?></td>
                            <td style="text-align:right">
                                <button type="button" class="btn btn-ghost btn-sm" onclick="event.stopPropagation(); toggleDetails(<?php echo $log['id']; ?>)">⬇</button>
                            </td>
                        </tr>
                        <tr id="details-<?php echo $log['id']; ?>" style="display:none;background:var(--bg3)">
                            <td colspan="7" style="padding:16px">
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                                    <?php if (!empty($log['old_values'])): ?>
                                        <div>
                                            <h4 style="font-size:12px;font-weight:700;color:var(--text2);margin-bottom:8px;text-transform:uppercase">Valori vechi</h4>
                                            <pre style="background:var(--bg2);padding:12px;border-radius:8px;font-size:11px;overflow-x:auto;color:var(--text2)"><?php echo htmlspecialchars(json_encode(json_decode($log['old_values']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($log['new_values'])): ?>
                                        <div>
                                            <h4 style="font-size:12px;font-weight:700;color:var(--text2);margin-bottom:8px;text-transform:uppercase">Valori noi</h4>
                                            <pre style="background:var(--bg2);padding:12px;border-radius:8px;font-size:11px;overflow-x:auto;color:var(--text2)"><?php echo htmlspecialchars(json_encode(json_decode($log['new_values']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div style="margin-top:12px;padding-top:12px;border-top:1px solid var(--border);font-size:11px;color:var(--text3)">
                                    User Agent: <?php echo htmlspecialchars(substr($log['user_agent'], 0, 80)); ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- MOBILE CARD VIEW -->
<div class="logs-mobile">
    <?php if (empty($logs)): ?>
        <div class="empty-state">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/></svg>
            <h3>Niciun log</h3>
        </div>
    <?php else: ?>
        <?php foreach ($logs as $log): 
            $action_colors = [
                'create' => '#3DB87A',
                'update' => '#E8C24A',
                'delete' => '#E05252',
                'view' => '#4A8FD4'
            ];
            $action_color = $action_colors[$log['action']] ?? '#9A9590';
        ?>
            <div class="log-card" onclick="toggleDetailsMobile(<?php echo $log['id']; ?>)">
                <div class="log-card-header">
                    <div>
                        <div class="log-card-title"><?php echo htmlspecialchars($log['entity_name'] ?: 'Log'); ?></div>
                        <div class="log-card-sub"><?php echo htmlspecialchars(ucfirst($log['entity_type'])); ?> #<?php echo $log['entity_id']; ?></div>
                    </div>
                    <span class="log-card-badge" style="background:<?php echo $action_color; ?>22;color:<?php echo $action_color; ?>">
                        <?php echo htmlspecialchars(ucfirst($log['action'])); ?>
                    </span>
                </div>
                
                <div class="log-card-meta">
                    <div>
                        <div style="color:var(--text3);font-size:11px">Data</div>
                        <div><?php echo date('d.m.Y H:i', strtotime($log['created_at'])); ?></div>
                    </div>
                    <div>
                        <div style="color:var(--text3);font-size:11px">Utilizator</div>
                        <div><?php echo htmlspecialchars($log['user_name'] ?: 'Sistema'); ?></div>
                    </div>
                </div>
                
                <div id="mobile-details-<?php echo $log['id']; ?>" style="display:none" class="log-card-details">
                    <div class="log-card-details-row">
                        <span style="color:var(--text3)">IP:</span>
                        <span><?php echo htmlspecialchars($log['ip_address']); ?></span>
                    </div>
                    
                    <?php if (!empty($log['old_values'])): ?>
                        <div>
                            <div style="font-weight:600;font-size:12px;margin-top:8px">Valori vechi:</div>
                            <div class="log-card-json"><?php echo htmlspecialchars(json_encode(json_decode($log['old_values']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($log['new_values'])): ?>
                        <div>
                            <div style="font-weight:600;font-size:12px;margin-top:8px">Valori noi:</div>
                            <div class="log-card-json"><?php echo htmlspecialchars(json_encode(json_decode($log['new_values']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php if ($pages > 1): ?>
<div style="display:flex;justify-content:center;gap:8px;margin-top:20px;flex-wrap:wrap">
    <?php for ($i = 1; $i <= $pages; $i++): ?>
        <a href="<?php echo APP_URL; ?>/admin/audit.php?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
           class="btn <?php echo $i == $page ? 'btn-primary' : 'btn-ghost'; ?> btn-sm">
            <?php echo $i; ?>
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<script>
function toggleDetails(id) {
    const row = document.getElementById('details-' + id);
    if (row.style.display === 'none') {
        row.style.display = 'table-row';
    } else {
        row.style.display = 'none';
    }
}

function toggleDetailsMobile(id) {
    const details = document.getElementById('mobile-details-' + id);
    if (details.style.display === 'none') {
        details.style.display = 'block';
    } else {
        details.style.display = 'none';
    }
}
</script>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>

