<?php
// Prevent direct access
if (!defined('LUNA_APP')) {
    http_response_code(403);
    exit('Forbidden');
}

require_once __DIR__ . '/config/messages.php';
require_once __DIR__ . '/config/database.php';
$messages = load_messages();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Log file settings
$logFile = __DIR__ . '/modules/incoming/log.txt';
$lines = isset($_GET['lines']) ? (int)$_GET['lines'] : 100;
$level = isset($_GET['level']) ? $_GET['level'] : 'ALL';
$filterValue = isset($_GET['filter_value']) ? trim($_GET['filter_value']) : '';
// Parse log file
$stats = [
    'total' => 0,
    'update' => 0,
    'export' => 0,
    'import' => 0,
    'debug' => 0
];

$parsedLogs = [];
$fileExists = file_exists($logFile);
$fileSize = 0;
$lastModified = '';

if ($fileExists) {
    $fileSize = filesize($logFile);
    $lastModified = date('Y-m-d H:i:s', filemtime($logFile));
    
    $logContent = file_get_contents($logFile);
    $logLines = array_filter(explode("\n", $logContent));
    
    foreach ($logLines as $line) {
        if (strpos($line, '#') === 0 || trim($line) === '') continue;
        
        if (preg_match('/\[(.*?)\]\s*\[(.*?)\]\s*(.*)/', $line, $matches)) {
            $logLevel = strtoupper(trim($matches[2]));
             
            // Map old logs to new levels
            if ($logLevel === 'SUCCESS') {
                $logLevel = 'EXPORT';
            }
            if ($logLevel === 'ERROR') {
                $logLevel = 'IMPORT';
            }
            if ($logLevel === 'INFO') {
                $logLevel = 'UPDATE';
            }
            
            $stats['total']++;
            $statKey = strtolower($logLevel);
            if (isset($stats[$statKey])) {
                $stats[$statKey]++;
            }
            
            $parsedLogs[] = [
                'timestamp' => $matches[1],
                'level' => $logLevel,
                'message' => $matches[3]
            ];
        }
    }

    // Filter and limit
    $filteredLogs = $parsedLogs;
    
    // Filter by level or ID
    if ($level === 'ID' && $filterValue !== '') {
        // Filter by ID only
        $filteredLogs = array_filter($parsedLogs, function($log) use ($filterValue) {
            return strpos($log['message'], "ID: {$filterValue}") !== false || 
                   strpos($log['message'], "ID:{$filterValue}") !== false;
        });
    } elseif ($level !== 'ALL' && $level !== 'ID') {
        // Filter by level
        $filteredLogs = array_filter($parsedLogs, function($log) use ($level) {
            return $log['level'] === $level;
        });
    }
    
    // Get last N lines
    $filteredLogs = array_slice(array_reverse($filteredLogs), 0, $lines);
}
?>

<style>
/* Incoming Log Viewer Styles */
.incoming-log-controls {
    background: rgba(255, 255, 255, 0.02);
    padding: 15px 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: flex-end;
    flex-wrap: wrap;
    justify-content: center;
}

.incoming-log-controls .control-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.incoming-log-controls label {
    color: #7adcc9;
    font-weight: 600;
    font-size: 14px;
}

.incoming-log-controls .custom-select {
    position: relative;
    width: 100%;
    z-index: 1; /* Lower than sidebar menu */
}

.incoming-log-controls .custom-select-toggle {
    width: 100%;
    background: rgba(11, 31, 34, 0.65);
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 16px;
    color: var(--text-main);
    padding: 10px 14px;
    padding-right: 38px;
    text-align: left;
    cursor: pointer;
    box-shadow: inset 0 1px 2px rgba(3, 12, 16, 0.4);
    transition: border-color .2s ease, box-shadow .2s ease, background .2s ease;
    font-size: 14px;
    position: relative;
}

.incoming-log-controls .custom-select-toggle::after {
    content: '';
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    width: 18px;
    height: 18px;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='18' height='18' viewBox='0 0 24 24' fill='none' stroke='%23bfeee3' stroke-width='1.8'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
    background-size: 18px 18px;
    background-repeat: no-repeat;
    pointer-events: none;
}

.incoming-log-controls .custom-select-toggle:hover,
.incoming-log-controls .custom-select-toggle:focus {
    border-color: rgba(122, 220, 201, 0.45);
    box-shadow: 0 0 0 2px rgba(122, 220, 201, 0.15);
    outline: none;
}

.incoming-log-controls .custom-select-menu {
    display: none;
    position: absolute;
    left: 0;
    right: 0;
    z-index: 100;
    background: rgba(12, 38, 43, 0.96);
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 12px;
    margin-top: 6px;
    max-height: 240px;
    overflow: auto;
    box-shadow: 0 18px 38px rgba(3, 15, 21, 0.55);
}

.incoming-log-controls .custom-select.open .custom-select-menu {
    display: block;
}

.incoming-log-controls .custom-select.open {
    z-index: 10; /* Still lower than sidebar */
}

.incoming-log-controls .custom-select-option {
    padding: 8px 12px;
    cursor: pointer;
    color: #e8fbf6;
    border-bottom: 1px solid rgba(122, 220, 201, 0.12);
}

.incoming-log-controls .custom-select-option:last-child {
    border-bottom: none;
}

.incoming-log-controls .custom-select-option:hover {
    background: rgba(122, 220, 201, 0.12);
}

.incoming-log-controls .custom-select-option.is-selected {
    background: rgba(122, 220, 201, 0.18);
}

.incoming-log-controls input[type="text"] {
    width: 100%;
    background: rgba(11, 31, 34, 0.65);
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 16px;
    color: var(--text-main);
    padding: 10px 14px;
    box-shadow: inset 0 1px 2px rgba(3, 12, 16, 0.4);
    transition: border-color .2s ease, box-shadow .2s ease;
    font-size: 14px;
    line-height: 1.5;
    box-sizing: border-box;
    height: 42px;
}

.incoming-log-controls input[type="text"]:hover,
.incoming-log-controls input[type="text"]:focus {
    border-color: rgba(122, 220, 201, 0.45);
    box-shadow: 0 0 0 2px rgba(122, 220, 201, 0.15);
    outline: none;
}

.incoming-log-controls input[type="text"]::placeholder {
    color: rgba(232, 251, 246, 0.4);
}

.incoming-log-controls input[type="text"]:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background: rgba(11, 31, 34, 0.4);
}

.incoming-log-controls button,
.incoming-log-controls a.btn-link {
    background: linear-gradient(135deg, #7adcc9, #4a9e95);
    border: none;
    color: #0c161c;
    padding: 13px 20px;
    border-radius: 6px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-block;
}

.incoming-log-controls button:hover,
.incoming-log-controls a.btn-link:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(122, 220, 201, 0.3);
}

.incoming-log-controls .btn-back {
    background: rgba(122, 220, 201, 0.1);
    color: #7adcc9;
    margin-left: auto;
}

.incoming-log-container {
    background: rgba(3, 12, 16, 0.8);
    border: 1px solid rgba(122, 220, 201, 0.2);
    border-radius: 10px;
    padding: 20px;
    font-family: 'Inter', Courier, 'Lucida Console', Monaco, Consolas, 'Liberation Mono', monospace;
    font-size: 10px;
    line-height: 1.6;
    max-height: 60vh;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

.incoming-log-line {
    padding: 8px 12px;
    margin-bottom: 4px;
    border-radius: 4px;
    border-left: 4px solid transparent;
}

.incoming-log-line.UPDATE {
    background: rgba(59, 130, 246, 0.1);
    border-left-color: #3b82f6;
}

.incoming-log-line.EXPORT {
    background: rgba(168, 85, 247, 0.1);
    border-left-color: #a855f7;
}

.incoming-log-line.IMPORT {
    background: rgba(34, 197, 94, 0.1);
    border-left-color: #22c55e;
}

.incoming-log-line.DEBUG {
    background: rgba(168, 85, 247, 0.1);
    border-left-color: #a855f7;
}

.incoming-log-timestamp {
    color: rgba(232, 251, 246, 0.5);
    font-weight: 600;
}

.incoming-log-level {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-weight: 700;
    font-size: 11px;
    margin: 0 8px;
}

.incoming-log-level.UPDATE { background: #3b82f6; color: white; }
.incoming-log-level.EXPORT { background: #a855f7; color: white; }
.incoming-log-level.IMPORT { background: #22c55e; color: white; }
.incoming-log-level.DEBUG { background: #a855f7; color: white; }

.incoming-log-message {
    color: #e8fbf6;
}

.incoming-log-empty {
    text-align: center;
    padding: 40px;
    color: rgba(232, 251, 246, 0.5);
}

.log-panel-controls {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.log-panel-controls .log-back-btn {
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none !important;
    background: rgba(17, 46, 51, 0.6);
    color: #7adcc9;
    border: 1px solid rgba(122, 220, 201, 0.3);
    transition: all 0.2s ease;
}

.log-panel-controls .log-back-btn:hover {
    background: rgba(17, 46, 51, 0.8);
    border-color: rgba(122, 220, 201, 0.5);
    color: #e8fbf6;
    transform: translateY(-1px);
}

.log-panel-controls .btn-icon-wrapper {
    display: inline-grid;
    place-items: center;
    width: 14px;
    height: 14px;
}

.log-panel-controls .btn-text-wrapper {
    font-size: 13px;
}

.log-panel-controls .log-back-btn:focus-visible {
    outline: 2px solid rgba(122, 220, 201, 0.6);
    outline-offset: 2px;
}

.incoming-log-footer {
    text-align: center;
    margin-top: 20px;
    color: rgba(232, 251, 246, 0.5);
    font-size: 12px;
}

#incoming-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    width: 100%;
    max-width: 100%;
    margin-bottom: 20px;
}

.incoming-stat-card {
    background: linear-gradient(135deg, rgba(26, 67, 74, 0.85), rgba(17, 46, 51, 0.95));
    border: 1px solid rgba(122, 220, 201, 0.28);
    border-radius: 14px;
    padding: 24px;
    box-shadow: 0 8px 16px rgba(3, 15, 21, 0.35);
}

.incoming-stat-total {
    border-left: 4px solid #7adcc9;
}

.incoming-stat-update {
    border: 1px solid rgba(59, 130, 246, 0.28);
    border-left: 4px solid #3b82f6;
}

.incoming-stat-export {
    border: 1px solid rgba(168, 85, 247, 0.28);
    border-left: 4px solid #a855f7;
}

.incoming-stat-import {
    border: 1px solid rgba(34, 197, 94, 0.28);
    border-left: 4px solid #22c55e;
}

.stat-label {
    font-size: 13px;
    color: rgba(232, 251, 246, 0.7);
    margin-bottom: 10px;
    font-weight: 500;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
}

.incoming-stat-total .stat-value {
    color: #7adcc9;
}

.incoming-stat-update .stat-value {
    color: #3b82f6;
}

.incoming-stat-export .stat-value {
    color: #a855f7;
}

.incoming-stat-import .stat-value {
    color: #22c55e;
}

/* Mobile responsive */
@media (max-width: 768px) {
    /* Only affect content area, not sidebar */
    .panel-grid {
        padding: 0 !important;
        margin: 0 !important;
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: hidden !important;
        overflow-y: visible !important;
        min-height: auto !important;
        height: auto !important;
    }
    
    .panel.wide {
        padding: 12px !important;
        margin: 0 !important;
        border-radius: 12px !important;
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        overflow-x: hidden !important;
        overflow-y: visible !important;
    }
    
    .panel-header {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 10px;
        padding: 0 0 12px 0 !important;
        width: 100% !important;
        box-sizing: border-box !important;
    }
    
    .panel-header h3 {
        font-size: 16px !important;
        width: 100%;
    }
    
    .panel-controls {
        width: 100% !important;
        box-sizing: border-box !important;
    }
    
    .panel-controls .btn,
    .panel-controls .btn-secondary {
        width: 100% !important;
        justify-content: center;
        display: flex;
        align-items: center;
        box-sizing: border-box !important;
    }
    
    #incoming-stats-grid {
        grid-template-columns: repeat(2, 1fr) !important;
        gap: 10px !important;
        width: 100% !important;
        max-width: 100% !important;
        margin-bottom: 12px !important;
        box-sizing: border-box !important;
    }
    
    .incoming-stat-card {
        padding: 12px !important;
        width: 100% !important;
        box-sizing: border-box !important;
    }
    
    .stat-label {
        font-size: 10px !important;
        margin-bottom: 4px !important;
    }
    
    .stat-value {
        font-size: 20px !important;
    }
    
    .incoming-log-controls {
        display: grid !important;
        grid-template-columns: repeat(2, 1fr) !important;
        gap: 10px !important;
        padding: 12px !important;
        width: 100% !important;
        box-sizing: border-box !important;
        margin-bottom: 12px !important;
    }
    
    .incoming-log-controls .control-group {
        width: 100% !important;
        box-sizing: border-box !important;
    }
    
    .incoming-log-controls .control-group:nth-child(4) {
        grid-column: 1 / -1 !important;
    }
    
    .incoming-log-controls input[type="text"] {
        width: 100% !important;
        font-size: 13px !important;
        padding: 8px 10px !important;
        box-sizing: border-box !important;
        height: 38px !important;
    }
    
    .incoming-log-controls input[type="text"]:disabled {
        opacity: 0.5 !important;
    }
    .incoming-log-controls button {
        grid-column: 1 / -1 !important;
    }
    
    .incoming-log-controls label {
        font-size: 11px;
        margin-bottom: 4px;
        display: block;
    }
    
    .incoming-log-controls .custom-select-toggle {
        width: 100% !important;
        font-size: 13px;
        padding: 8px 10px;
        padding-right: 38px !important;
        box-sizing: border-box !important;
    }
    
    .incoming-log-controls button {
        width: 100% !important;
        font-size: 14px;
        padding: 10px 12px;
        box-sizing: border-box !important;
        margin-top: 0 !important;
    }
    
    .incoming-log-container {
        min-height: 300px;
        max-height: calc(100vh - 480px);
        padding: 10px;
        font-size: 12px;
        width: 100% !important;
        box-sizing: border-box !important;
        overflow-x: hidden !important;
        overflow-y: auto !important;
    }
    
    .incoming-log-line {
        padding: 8px;
        font-size: 11px;
        word-wrap: break-word;
        overflow-wrap: break-word;
    }
    
    .incoming-log-timestamp {
        display: block;
        margin-bottom: 4px;
        font-size: 10px;
    }
    
    .incoming-log-level {
        font-size: 9px;
        padding: 2px 6px;
        margin: 0 4px 4px 0;
        display: inline-block;
    }
    
    .incoming-log-message {
        display: block;
        word-wrap: break-word;
        overflow-wrap: break-word;
    }
    
    .incoming-log-footer {
        font-size: 9px;
        padding: 8px 0;
        word-wrap: break-word;
    }
    
    .incoming-log-empty {
        font-size: 13px;
        padding: 30px 10px;
    }

    .log-panel-controls {
        justify-content: center;
    }

    .log-panel-controls .log-back-btn {
        width: 100%;
        justify-content: center;
        font-size: 12px;
    }

    .log-panel-controls .btn-text-wrapper {
        font-size: 12px;
    }
}
</style>

<section class="panel-grid">
    <div class="panel wide">
        <header class="panel-header">
            <h3>
                <span class="panel-title-icon" aria-hidden="true" style="display:inline-grid;place-items:center;width:22px;height:22px;margin-right:8px;vertical-align:middle;color:#7adcc9;">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="5" width="18" height="14" rx="2" />
                        <path d="m3 7 9 6 9-6" />
                    </svg>
                </span>
                <?= htmlspecialchars($messages['log_page_title_incoming'], ENT_QUOTES, 'UTF-8') ?>
            </h3>
            <div class="panel-controls log-panel-controls">
                <a href="index.php?incoming" class="btn btn-secondary log-back-btn">
                    <span aria-hidden="true" class="btn-icon-wrapper">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="15 18 9 12 15 6" />
                            <line x1="9" y1="12" x2="21" y2="12" />
                        </svg>
                    </span>
                    <span class="btn-text-wrapper"><?= htmlspecialchars($messages['back_to_list'] ?? 'Quay lại', ENT_QUOTES, 'UTF-8') ?></span>
                </a>
            </div>
        </header>

        <!-- Statistics Cards -->
        <div id="incoming-stats-grid">
            <div class="incoming-stat-card incoming-stat-total">
                <div class="stat-label"><?= htmlspecialchars($messages['log_total_logs'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['total'] ?></div>
            </div>
            
            <div class="incoming-stat-card incoming-stat-update">
                <div class="stat-label"><?= htmlspecialchars($messages['log_update'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['update'] ?></div>
            </div>
            
            <div class="incoming-stat-card incoming-stat-export">
                <div class="stat-label"><?= htmlspecialchars($messages['log_export'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['export'] ?></div>
            </div>
            
            <div class="incoming-stat-card incoming-stat-import">
                <div class="stat-label"><?= htmlspecialchars($messages['log_import'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['import'] ?></div>
            </div>
        </div>

        <?php if (!$fileExists): ?>
            <div class="incoming-log-empty">
                📝 <?= htmlspecialchars($messages['log_file_not_exists_incoming'], ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php else: ?>
            <!-- Controls -->
            <form class="incoming-log-controls" method="GET">
                <input type="hidden" name="incoming" value="log">
                
                <div class="control-group">
                    <label><?= htmlspecialchars($messages['log_display_label'], ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="custom-select" id="lines-custom-select">
                        <button type="button" class="custom-select-toggle">
                            <?php
                            $linesOptions = [
                                50 => $messages['log_lines_50'], 
                                100 => $messages['log_lines_100'], 
                                200 => $messages['log_lines_200'], 
                                500 => $messages['log_lines_500'], 
                                1000 => $messages['log_lines_1000']
                            ];
                            echo htmlspecialchars($linesOptions[$lines] ?? $messages['log_lines_100'], ENT_QUOTES, 'UTF-8');
                            ?>
                        </button>
                        <div class="custom-select-menu" role="listbox">
                            <div class="custom-select-option" role="option" data-value="50"><?= htmlspecialchars($messages['log_lines_50'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="100"><?= htmlspecialchars($messages['log_lines_100'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="200"><?= htmlspecialchars($messages['log_lines_200'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="500"><?= htmlspecialchars($messages['log_lines_500'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="1000"><?= htmlspecialchars($messages['log_lines_1000'], ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                        <input type="hidden" name="lines" id="lines-value" value="<?= htmlspecialchars((string)$lines, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="control-group">
                    <label><?= htmlspecialchars($messages['log_level_label'], ENT_QUOTES, 'UTF-8') ?></label>
                    <div class="custom-select" id="level-custom-select">
                        <button type="button" class="custom-select-toggle">
                            <?php
                            $levelOptions = [
                                'ALL' => $messages['log_all_levels'], 
                                'UPDATE' => $messages['log_update'], 
                                'EXPORT' => $messages['log_export'], 
                                'IMPORT' => $messages['log_import'], 
                                'DEBUG' => $messages['log_debug'], 
                                'ID' => 'ID'
                            ];
                            echo htmlspecialchars($levelOptions[$level] ?? $messages['log_all_levels'], ENT_QUOTES, 'UTF-8');
                            ?>
                        </button>
                        <div class="custom-select-menu" role="listbox">
                        <div class="custom-select-option" role="option" data-value="ALL"><?= htmlspecialchars($messages['log_all_levels'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="UPDATE"><?= htmlspecialchars($messages['log_update'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="EXPORT"><?= htmlspecialchars($messages['log_export'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="IMPORT"><?= htmlspecialchars($messages['log_import'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="DEBUG"><?= htmlspecialchars($messages['log_debug'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="ID">ID</div>
                        </div>
                        <input type="hidden" name="level" id="level-value" value="<?= htmlspecialchars($level, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </div>

                <div class="control-group">
                    <label><?= htmlspecialchars($messages['log_filter_value_label'], ENT_QUOTES, 'UTF-8') ?></label>
                    <input type="text" name="filter_value" id="filter-value-input" 
                           value="<?= htmlspecialchars($filterValue, ENT_QUOTES, 'UTF-8') ?>" 
                           placeholder="<?= $level === 'ID' ? htmlspecialchars($messages['log_filter_id_placeholder'], ENT_QUOTES, 'UTF-8') : htmlspecialchars($messages['log_filter_placeholder'], ENT_QUOTES, 'UTF-8') ?>"
                           <?= ($level !== 'ID') ? 'disabled' : '' ?>>
                </div>
                <button type="submit">
                    <span aria-hidden="true" style="display:inline-grid;place-items:center;width:18px;height:18px;margin-right:8px;vertical-align:middle;">
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="23 4 23 10 17 10" />
                            <polyline points="1 20 1 14 7 14" />
                            <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10" />
                            <path d="M20.49 15a9 9 0 0 1-14.13 3.36L1 14" />
                        </svg>
                    </span>
                    <?= htmlspecialchars($messages['log_refresh_button'], ENT_QUOTES, 'UTF-8') ?>
                </button>
                
            </form>

            <!-- Log Container -->
            <div class="incoming-log-container">
                <?php if (empty($filteredLogs)): ?>
                    <div class="incoming-log-empty"><?= htmlspecialchars($messages['log_no_logs_found'], ENT_QUOTES, 'UTF-8') ?></div>
                <?php else: ?>
                    <?php foreach ($filteredLogs as $log): ?>
                        <div class="incoming-log-line <?= $log['level'] ?>">
                            <span class="incoming-log-timestamp"><?= htmlspecialchars($log['timestamp']) ?></span>
                            <span class="incoming-log-level <?= $log['level'] ?>"><?php
                                $levelLabels = [
                                    'UPDATE' => $messages['log_update'],
                                    'EXPORT' => $messages['log_export'],
                                    'IMPORT' => $messages['log_import'],
                                    'DEBUG' => $messages['log_debug']
                                ];
                                echo htmlspecialchars($levelLabels[$log['level']] ?? $log['level'], ENT_QUOTES, 'UTF-8');
                            ?></span>
                            <span class="incoming-log-message"><?= htmlspecialchars($log['message']) ?></span>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="incoming-log-footer">

                <?= htmlspecialchars($messages['log_file_size'], ENT_QUOTES, 'UTF-8') ?> <?= number_format($fileSize / 1024, 2) ?> KB |
                <?= htmlspecialchars($messages['log_file_last_modified'], ENT_QUOTES, 'UTF-8') ?> <?= $lastModified ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<script>
// Custom Select for Incomming Log Controls
(function() {
    const customSelects = document.querySelectorAll('.incoming-log-controls .custom-select');
    
    customSelects.forEach(select => {
        const toggle = select.querySelector('.custom-select-toggle');
        const menu = select.querySelector('.custom-select-menu');
        const options = select.querySelectorAll('.custom-select-option');
        const hiddenInput = select.querySelector('input[type="hidden"]');
        
        // Toggle dropdown
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // Close other dropdowns
            customSelects.forEach(otherSelect => {
                if (otherSelect !== select) {
                    otherSelect.classList.remove('open');
                }
            });
            
            select.classList.toggle('open');
        });
        
        // Select option
        options.forEach(option => {
            const value = option.getAttribute('data-value');
            
            // Mark current selection
            if (hiddenInput.value === value) {
                option.classList.add('is-selected');
            }
            
            option.addEventListener('click', function() {
                const selectedValue = this.getAttribute('data-value');
                const selectedText = this.textContent;
                
                // Update toggle text
                toggle.textContent = selectedText;
                
                // Update hidden input
                hiddenInput.value = selectedValue;
                
                // Update selected class
                options.forEach(opt => opt.classList.remove('is-selected'));
                this.classList.add('is-selected');
                
                // Update filter value input placeholder based on level selection
                if (hiddenInput.name === 'level') {
                    const filterInput = document.getElementById('filter-value-input');
                    if (filterInput) {
                        if (selectedValue === 'ID') {
                            filterInput.placeholder = '<?= htmlspecialchars($messages['log_filter_id_placeholder'], ENT_QUOTES, 'UTF-8') ?>';
                            filterInput.disabled = false;
                        } else if (selectedValue === 'ALL') {
                            filterInput.placeholder = '<?= htmlspecialchars($messages['log_filter_placeholder'], ENT_QUOTES, 'UTF-8') ?>';
                            filterInput.disabled = true;
                            filterInput.value = '';
                        } else {
                            filterInput.placeholder = '<?= htmlspecialchars($messages['log_filter_placeholder'], ENT_QUOTES, 'UTF-8') ?>';
                            filterInput.disabled = true;
                            filterInput.value = '';
                        }
                    }
                }
                // Close dropdown
                select.classList.remove('open');
            });
        });
    });
    
    // Close dropdowns when clicking outside
    document.addEventListener('click', function(e) {
        // Don't interfere with sidebar menu interactions
        if (e.target.closest('.dashboard-sidebar') || e.target.closest('.submenu')) {
            return;
        }
        
        if (!e.target.closest('.incoming-log-controls .custom-select')) {
            customSelects.forEach(select => {
                select.classList.remove('open');
            });
        }
    });
})();
</script>