<?php
/**
 * Admin Logs Viewer
 * Video Portal Management System
 */

require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

requireAdmin();

$settings = getAllSettings();
$siteName = $settings['site_name'] ?? 'Video Portal';
$rtl = $settings['rtl_direction'] ?? '0';

// Get log files
$logDir = __DIR__ . '/../logs';
$logFiles = [];
if (file_exists($logDir)) {
    $files = glob($logDir . '/upload_*.log');
    rsort($files); // newest first
    foreach ($files as $file) {
        $logFiles[] = [
            'name' => basename($file),
            'date' => str_replace(['upload_', '.log'], '', basename($file)),
            'size' => filesize($file),
            'path' => $file
        ];
    }
}

// Get selected log file content
$selectedLog = $_GET['file'] ?? '';
$logContent = '';
$logEntries = [];

if ($selectedLog && preg_match('/^upload_\d{4}-\d{2}-\d{2}\.log$/', $selectedLog)) {
    $logPath = $logDir . '/' . $selectedLog;
    if (file_exists($logPath)) {
        $logContent = file_get_contents($logPath);
        // Parse log entries
        $lines = explode("\n", trim($logContent));
        $lines = array_reverse($lines); // newest first
        foreach ($lines as $line) {
            if (empty($line)) continue;
            
            $entry = ['raw' => $line, 'type' => 'INFO'];
            
            if (preg_match('/^\[(.*?)\] \[(.*?)\] (.*)$/', $line, $matches)) {
                $entry['timestamp'] = $matches[1];
                $entry['type'] = $matches[2];
                $entry['message'] = $matches[3];
            } else {
                $entry['message'] = $line;
            }
            
            $logEntries[] = $entry;
        }
    }
}

// Clear log action
if (isset($_POST['clear_log']) && $selectedLog) {
    $logPath = $logDir . '/' . $selectedLog;
    if (file_exists($logPath)) {
        file_put_contents($logPath, '');
        header('Location: logs.php?file=' . $selectedLog . '&cleared=1');
        exit;
    }
}

// Delete log action
if (isset($_POST['delete_log']) && $selectedLog) {
    $logPath = $logDir . '/' . $selectedLog;
    if (file_exists($logPath)) {
        unlink($logPath);
        header('Location: logs.php?deleted=1');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="<?= $rtl == '1' ? 'he' : 'en' ?>" dir="<?= $rtl == '1' ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Logs - <?= htmlspecialchars($siteName) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        :root {
            --primary-color: <?= $settings['primary_color'] ?? '#3498db' ?>;
            --secondary-color: <?= $settings['secondary_color'] ?? '#2c3e50' ?>;
            --sidebar-color: <?= $settings['sidebar_color'] ?? '#1e272e' ?>;
        }
        
        .log-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            align-items: center;
        }
        
        .log-selector select {
            padding: 10px 15px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            min-width: 200px;
        }
        
        .log-container {
            background: #1e1e1e;
            border-radius: 8px;
            padding: 20px;
            max-height: 600px;
            overflow-y: auto;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
        }
        
        .log-entry {
            padding: 8px 12px;
            margin-bottom: 5px;
            border-radius: 4px;
            display: flex;
            gap: 10px;
            align-items: flex-start;
        }
        
        .log-entry.ERROR {
            background: rgba(231, 76, 60, 0.2);
            border-left: 3px solid #e74c3c;
            color: #e74c3c;
        }
        
        .log-entry.SUCCESS {
            background: rgba(46, 204, 113, 0.2);
            border-left: 3px solid #2ecc71;
            color: #2ecc71;
        }
        
        .log-entry.INFO {
            background: rgba(52, 152, 219, 0.2);
            border-left: 3px solid #3498db;
            color: #3498db;
        }
        
        .log-entry.WARNING {
            background: rgba(241, 196, 15, 0.2);
            border-left: 3px solid #f1c40f;
            color: #f1c40f;
        }
        
        .log-timestamp {
            color: #888;
            white-space: nowrap;
            font-size: 12px;
        }
        
        .log-type {
            font-weight: bold;
            min-width: 70px;
        }
        
        .log-message {
            flex: 1;
            word-break: break-word;
        }
        
        .log-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .log-stat {
            background: white;
            padding: 15px 25px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .log-stat .number {
            font-size: 24px;
            font-weight: bold;
        }
        
        .log-stat .label {
            color: #666;
            font-size: 13px;
        }
        
        .log-stat.errors .number { color: #e74c3c; }
        .log-stat.success .number { color: #2ecc71; }
        .log-stat.info .number { color: #3498db; }
        
        .empty-log {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .empty-log i {
            font-size: 50px;
            margin-bottom: 15px;
            color: #ddd;
        }
        
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .btn-warning {
            background: #f39c12;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d68910;
        }
        
        .refresh-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
        }
        
        @media (max-width: 768px) {
            .log-entry {
                flex-direction: column;
                gap: 5px;
            }
            .log-timestamp {
                font-size: 11px;
            }
        }
    </style>
</head>
<body class="<?= $rtl == '1' ? 'rtl' : '' ?>">
    <div class="portal-wrapper">
        <aside class="sidebar">
            <div class="sidebar-header">
                <i class="fas fa-play-circle" style="font-size: 40px;"></i>
                <h2>Admin Panel</h2>
            </div>
            
            <ul class="sidebar-menu">
                <li><a href="dashboard.php"><i class="fas fa-tachometer-alt"></i><span>Dashboard</span></a></li>
                <li><a href="videos.php"><i class="fas fa-video"></i><span>Videos</span></a></li>
                <li><a href="categories.php"><i class="fas fa-folder"></i><span>Categories</span></a></li>
                <li><a href="users.php"><i class="fas fa-users"></i><span>Users</span></a></li>
                <li><a href="settings.php"><i class="fas fa-cog"></i><span>Settings</span></a></li>
                <li><a href="logs.php" class="active"><i class="fas fa-file-alt"></i><span>Upload Logs</span></a></li>
                <div class="menu-divider"></div>
                <li><a href="../index.php"><i class="fas fa-home"></i><span>Back to Portal</span></a></li>
                <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i><span>Logout</span></a></li>
            </ul>
        </aside>
        
        <main class="main-content">
            <div class="top-bar">
                <h1><i class="fas fa-file-alt"></i> Upload Logs</h1>
                <button class="refresh-btn" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
            
            <?php if (isset($_GET['cleared'])): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> Log file cleared successfully
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['deleted'])): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> Log file deleted successfully
                </div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body">
                    <?php if (empty($logFiles)): ?>
                        <div class="empty-log">
                            <i class="fas fa-file-alt"></i>
                            <h3>No Log Files</h3>
                            <p>Upload logs will appear here when you upload videos.</p>
                        </div>
                    <?php else: ?>
                        <div class="log-selector">
                            <form method="GET" style="display: flex; gap: 10px; align-items: center;">
                                <select name="file" onchange="this.form.submit()">
                                    <option value="">-- Select Log File --</option>
                                    <?php foreach ($logFiles as $log): ?>
                                        <option value="<?= htmlspecialchars($log['name']) ?>" 
                                                <?= $selectedLog === $log['name'] ? 'selected' : '' ?>>
                                            <?= $log['date'] ?> (<?= round($log['size']/1024, 1) ?> KB)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </form>
                            
                            <?php if ($selectedLog): ?>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Clear this log file?')">
                                    <button type="submit" name="clear_log" class="btn btn-warning btn-sm">
                                        <i class="fas fa-eraser"></i> Clear
                                    </button>
                                </form>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this log file permanently?')">
                                    <button type="submit" name="delete_log" class="btn btn-danger btn-sm">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($selectedLog && !empty($logEntries)): ?>
                            <?php
                            $errorCount = count(array_filter($logEntries, fn($e) => ($e['type'] ?? '') === 'ERROR'));
                            $successCount = count(array_filter($logEntries, fn($e) => ($e['type'] ?? '') === 'SUCCESS'));
                            $infoCount = count(array_filter($logEntries, fn($e) => ($e['type'] ?? '') === 'INFO'));
                            ?>
                            <div class="log-stats">
                                <div class="log-stat errors">
                                    <div class="number"><?= $errorCount ?></div>
                                    <div class="label">Errors</div>
                                </div>
                                <div class="log-stat success">
                                    <div class="number"><?= $successCount ?></div>
                                    <div class="label">Successful</div>
                                </div>
                                <div class="log-stat info">
                                    <div class="number"><?= $infoCount ?></div>
                                    <div class="label">Info</div>
                                </div>
                            </div>
                            
                            <div class="log-container">
                                <?php foreach ($logEntries as $entry): ?>
                                    <div class="log-entry <?= htmlspecialchars($entry['type'] ?? 'INFO') ?>">
                                        <?php if (isset($entry['timestamp'])): ?>
                                            <span class="log-timestamp"><?= htmlspecialchars($entry['timestamp']) ?></span>
                                        <?php endif; ?>
                                        <span class="log-type">[<?= htmlspecialchars($entry['type'] ?? 'INFO') ?>]</span>
                                        <span class="log-message"><?= htmlspecialchars($entry['message'] ?? $entry['raw']) ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php elseif ($selectedLog): ?>
                            <div class="empty-log">
                                <i class="fas fa-check-circle" style="color: #2ecc71;"></i>
                                <h3>Log File Empty</h3>
                                <p>No entries in this log file.</p>
                            </div>
                        <?php else: ?>
                            <div class="empty-log">
                                <i class="fas fa-hand-pointer"></i>
                                <h3>Select a Log File</h3>
                                <p>Choose a log file from the dropdown to view its contents.</p>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- PHP Info Section -->
            <div class="card" style="margin-top: 20px;">
                <div class="card-header">
                    <h2><i class="fas fa-info-circle"></i> PHP Upload Settings</h2>
                </div>
                <div class="card-body">
                    <table class="table">
                        <tr>
                            <td><strong>upload_max_filesize</strong></td>
                            <td><?= ini_get('upload_max_filesize') ?></td>
                            <td><small>Maximum size of uploaded file</small></td>
                        </tr>
                        <tr>
                            <td><strong>post_max_size</strong></td>
                            <td><?= ini_get('post_max_size') ?></td>
                            <td><small>Maximum size of POST data</small></td>
                        </tr>
                        <tr>
                            <td><strong>max_execution_time</strong></td>
                            <td><?= ini_get('max_execution_time') ?> seconds</td>
                            <td><small>Maximum script execution time</small></td>
                        </tr>
                        <tr>
                            <td><strong>max_input_time</strong></td>
                            <td><?= ini_get('max_input_time') ?> seconds</td>
                            <td><small>Maximum time for parsing input</small></td>
                        </tr>
                        <tr>
                            <td><strong>upload_tmp_dir</strong></td>
                            <td><?= ini_get('upload_tmp_dir') ?: sys_get_temp_dir() ?></td>
                            <td><small>Temporary upload directory</small></td>
                        </tr>
                        <tr>
                            <td><strong>file_uploads</strong></td>
                            <td><?= ini_get('file_uploads') ? '<span style="color:green">Enabled</span>' : '<span style="color:red">Disabled</span>' ?></td>
                            <td><small>File uploads enabled</small></td>
                        </tr>
                        <tr>
                            <td><strong>Videos Directory</strong></td>
                            <td><?= realpath(__DIR__ . '/../assets/uploads/videos') ?: __DIR__ . '/../assets/uploads/videos' ?></td>
                            <td>
                                <?php 
                                $videoDir = __DIR__ . '/../assets/uploads/videos';
                                if (file_exists($videoDir) && is_writable($videoDir)): ?>
                                    <span style="color:green"><i class="fas fa-check"></i> Writable</span>
                                <?php elseif (file_exists($videoDir)): ?>
                                    <span style="color:red"><i class="fas fa-times"></i> Not Writable</span>
                                <?php else: ?>
                                    <span style="color:orange"><i class="fas fa-exclamation"></i> Does not exist</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </main>
    </div>
    
    <button class="mobile-toggle">
        <i class="fas fa-bars"></i>
    </button>
    
    <script src="../assets/js/script.js"></script>
</body>
</html>
