<?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/zalo/log.txt';
$lines = isset($_GET['lines']) ? (int)$_GET['lines'] : 100;
$level = isset($_GET['level']) ? $_GET['level'] : 'ALL';

// Parse log file
$stats = [
    'total' => 0,
    'info' => 0,
    'success' => 0,
    'error' => 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]));
            $stats['total']++;
            $stats[strtolower($logLevel)]++;
            
            $parsedLogs[] = [
                'timestamp' => $matches[1],
                'level' => $logLevel,
                'message' => $matches[3]
            ];
        }
    }

    // Filter and limit
    $filteredLogs = $parsedLogs;
    if ($level !== 'ALL') {
        $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>
/* Zalo Log Viewer Styles */
.zalo-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;
}

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

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

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

.zalo-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;
}

.zalo-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;
}

.zalo-log-controls .custom-select-toggle:hover,
.zalo-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;
}

.zalo-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);
}

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

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

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

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

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

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

.zalo-log-controls button,
.zalo-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;
}

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

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

.zalo-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: 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.6;
    max-height: 60vh;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

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

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

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

.zalo-log-line.ERROR {
    background: rgba(239, 68, 68, 0.1);
    border-left-color: #ef4444;
}

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

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

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

.zalo-log-level.INFO { background: #3b82f6; color: white; }
.zalo-log-level.SUCCESS { background: #22c55e; color: white; }
.zalo-log-level.ERROR { background: #ef4444; color: white; }
.zalo-log-level.DEBUG { background: #a855f7; color: white; }

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

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

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

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

.zalo-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);
}

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

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

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

.zalo-stat-error {
    border: 1px solid rgba(239, 68, 68, 0.28);
    border-left: 4px solid #ef4444;
}

.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;
}

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

.zalo-stat-info .stat-value {
    color: #3b82f6;
}

.zalo-stat-success .stat-value {
    color: #22c55e;
}

.zalo-stat-error .stat-value {
    color: #ef4444;
}

/* 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;
    }
    
    #zalo-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;
    }
    
    .zalo-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;
    }
    
    .zalo-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;
    }
    
    .zalo-log-controls .control-group {
        width: 100% !important;
        box-sizing: border-box !important;
    }
    
    .zalo-log-controls button {
        grid-column: 1 / -1 !important;
    }
    
    .zalo-log-controls label {
        font-size: 11px;
        margin-bottom: 4px;
        display: block;
    }
    
    .zalo-log-controls .custom-select-toggle {
        width: 100% !important;
        font-size: 13px;
        padding: 8px 10px;
        padding-right: 38px !important;
        box-sizing: border-box !important;
    }
    
    .zalo-log-controls button {
        width: 100% !important;
        font-size: 14px;
        padding: 10px 12px;
        box-sizing: border-box !important;
        margin-top: 0 !important;
    }
    
    .zalo-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;
    }
    
    .zalo-log-line {
        padding: 8px;
        font-size: 11px;
        word-wrap: break-word;
        overflow-wrap: break-word;
    }
    
    .zalo-log-timestamp {
        display: block;
        margin-bottom: 4px;
        font-size: 10px;
    }
    
    .zalo-log-level {
        font-size: 9px;
        padding: 2px 6px;
        margin: 0 4px 4px 0;
        display: inline-block;
    }
    
    .zalo-log-message {
        display: block;
        word-wrap: break-word;
        overflow-wrap: break-word;
    }
    
    .zalo-log-footer {
        font-size: 9px;
        padding: 8px 0;
        word-wrap: break-word;
    }
    
    .zalo-log-empty {
        font-size: 13px;
        padding: 30px 10px;
    }
}
</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">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                        <polyline points="14,2 14,8 20,8" />
                    </svg>
                </span>
                <?= htmlspecialchars($messages['log_page_title_zalo'], ENT_QUOTES, 'UTF-8') ?>
            </h3>
            <div class="panel-controls">
                <a href="index.php?zalo" class="btn btn-secondary" style="text-decoration: none;">
                    <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="15 18 9 12 15 6" />
                            <line x1="9" y1="12" x2="21" y2="12" />
                        </svg>
                    </span>
                    <?= htmlspecialchars($messages['back_to_list'] ?? 'Quay lại', ENT_QUOTES, 'UTF-8') ?>
                </a>
            </div>
        </header>

        <!-- Statistics Cards -->
        <div id="zalo-stats-grid">
            <div class="zalo-stat-card zalo-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="zalo-stat-card zalo-stat-info">
                <div class="stat-label"><?= htmlspecialchars($messages['log_info'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['info'] ?></div>
            </div>
            
            <div class="zalo-stat-card zalo-stat-success">
                <div class="stat-label"><?= htmlspecialchars($messages['log_success'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['success'] ?></div>
            </div>
            
            <div class="zalo-stat-card zalo-stat-error">
                <div class="stat-label"><?= htmlspecialchars($messages['log_error'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="stat-value"><?= $stats['error'] ?></div>
            </div>
        </div>

        <?php if (!$fileExists): ?>
            <div class="zalo-log-empty">
                📝 <?= htmlspecialchars($messages['log_file_not_exists'], ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php else: ?>
            <!-- Controls -->
            <form class="zalo-log-controls" method="GET">
                <input type="hidden" name="zalo" 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'], 
                                'INFO' => $messages['log_info'], 
                                'SUCCESS' => $messages['log_success'], 
                                'ERROR' => $messages['log_error'], 
                                'DEBUG' => $messages['log_debug']
                            ];
                            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="INFO"><?= htmlspecialchars($messages['log_info'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="SUCCESS"><?= htmlspecialchars($messages['log_success'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="custom-select-option" role="option" data-value="ERROR"><?= htmlspecialchars($messages['log_error'], 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>
                        <input type="hidden" name="level" id="level-value" value="<?= htmlspecialchars($level, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                </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="zalo-log-container">
                <?php if (empty($filteredLogs)): ?>
                    <div class="zalo-log-empty"><?= htmlspecialchars($messages['log_no_logs_found'], ENT_QUOTES, 'UTF-8') ?></div>
                <?php else: ?>
                    <?php foreach ($filteredLogs as $log): ?>
                        <div class="zalo-log-line <?= $log['level'] ?>">
                            <span class="zalo-log-timestamp"><?= htmlspecialchars($log['timestamp']) ?></span>
                            <span class="zalo-log-level <?= $log['level'] ?>"><?php
                                $levelLabels = [
                                    'INFO' => $messages['log_info'],
                                    'SUCCESS' => $messages['log_success'], 
                                    'ERROR' => $messages['log_error'],
                                    'DEBUG' => $messages['log_debug']
                                ];
                                echo htmlspecialchars($levelLabels[$log['level']] ?? $log['level'], ENT_QUOTES, 'UTF-8');
                            ?></span>
                            <span class="zalo-log-message"><?= htmlspecialchars($log['message']) ?></span>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="zalo-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 Zalo Log Controls
(function() {
    const customSelects = document.querySelectorAll('.zalo-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');
                
                // 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('.zalo-log-controls .custom-select')) {
            customSelects.forEach(select => {
                select.classList.remove('open');
            });
        }
    });
})();
</script>