<?php
// File: admin.php
session_start();

// CREDENTIALS RAHASIA
$SECRET_EMAIL = "admin@filemanager.store";
$SECRET_PASSWORD = "adminfileku";

// Cek login via session
$loggedin = false;
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    $loggedin = true;
}

// Cek login via cookie (remember me)
if (!$loggedin && isset($_COOKIE['filemanager_auth'])) {
    $expected_hash = hash('sha256', $SECRET_EMAIL . $SECRET_PASSWORD . 'SALT_RAHASIA');
    if ($_COOKIE['filemanager_auth'] === $expected_hash) {
        $_SESSION['loggedin'] = true;
        $_SESSION['email'] = $SECRET_EMAIL;
        $loggedin = true;
    }
}

// Jika belum login, redirect ke login page
if (!$loggedin) {
    header('Location: login.php');
    exit;
}

// Cek session timeout (24 jam)
$max_inactive_time = 24 * 60 * 60; // 24 jam
if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time'] > $max_inactive_time)) {
    session_destroy();
    header('Location: login.php?timeout=1');
    exit;
}

// Update session time
$_SESSION['login_time'] = time();

// Logout handler
if (isset($_GET['logout'])) {
    session_destroy();
    setcookie('filemanager_auth', '', time() - 3600, '/');
    header('Location: login.php');
    exit;
}

// Get gallery stats
$uploads_dir = 'uploads/';
$total_files = 0;
$total_size = 0;
$recent_files = [];

if (is_dir($uploads_dir)) {
    $files = scandir($uploads_dir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..') {
            $filepath = $uploads_dir . $file;
            if (is_file($filepath)) {
                $total_files++;
                $total_size += filesize($filepath);
                
                // Get recent files (last 10)
                $filetime = filemtime($filepath);
                $recent_files[] = [
                    'name' => $file,
                    'size' => filesize($filepath),
                    'time' => $filetime,
                    'date' => date('Y-m-d H:i:s', $filetime)
                ];
            }
        }
    }
    
    // Sort by recent
    usort($recent_files, function($a, $b) {
        return $b['time'] - $a['time'];
    });
    
    $recent_files = array_slice($recent_files, 0, 10);
}

// Format size
function formatSize($bytes) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 2) . ' ' . $units[$i];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Panel - FileManager</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', sans-serif; }
        body { 
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            color: #f8fafc;
            min-height: 100vh;
        }
        .admin-header {
            background: rgba(15, 23, 42, 0.95);
            border-bottom: 1px solid #334155;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
            backdrop-filter: blur(10px);
        }
        .admin-nav {
            display: flex;
            align-items: center;
            gap: 2rem;
        }
        .admin-nav a {
            color: #cbd5e1;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            transition: 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .admin-nav a:hover {
            background: rgba(59, 130, 246, 0.1);
            color: #60a5fa;
        }
        .logout-btn {
            background: rgba(239, 68, 68, 0.1);
            color: #fca5a5;
            border: 1px solid #ef4444;
        }
        .logout-btn:hover {
            background: rgba(239, 68, 68, 0.2);
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #60a5fa;
        }
        .user-info i {
            font-size: 1.2rem;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }
        .stat-card {
            background: rgba(30, 41, 59, 0.8);
            border: 1px solid #334155;
            border-radius: 12px;
            padding: 1.5rem;
            transition: 0.3s;
        }
        .stat-card:hover {
            border-color: #60a5fa;
            transform: translateY(-3px);
        }
        .stat-icon {
            font-size: 2rem;
            color: #60a5fa;
            margin-bottom: 1rem;
        }
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #f8fafc;
            margin-bottom: 0.5rem;
        }
        .stat-label {
            color: #94a3b8;
            font-size: 0.9rem;
        }
        .section-title {
            font-size: 1.5rem;
            margin-bottom: 1.5rem;
            color: #f8fafc;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .file-list {
            background: rgba(30, 41, 59, 0.8);
            border: 1px solid #334155;
            border-radius: 12px;
            overflow: hidden;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #334155;
            transition: 0.3s;
        }
        .file-item:last-child {
            border-bottom: none;
        }
        .file-item:hover {
            background: rgba(59, 130, 246, 0.05);
        }
        .file-name {
            flex: 1;
            color: #f8fafc;
            font-family: monospace;
            word-break: break-all;
        }
        .file-size {
            color: #94a3b8;
            margin: 0 1rem;
            white-space: nowrap;
        }
        .file-date {
            color: #64748b;
            font-size: 0.9rem;
            white-space: nowrap;
        }
        .file-actions {
            display: flex;
            gap: 0.5rem;
            margin-left: 1rem;
        }
        .file-action-btn {
            background: none;
            border: 1px solid #475569;
            color: #cbd5e1;
            padding: 0.4rem 0.8rem;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: 0.3s;
        }
        .file-action-btn:hover {
            border-color: #60a5fa;
            color: #60a5fa;
        }
        .danger-btn {
            border-color: #ef4444;
            color: #fca5a5;
        }
        .danger-btn:hover {
            background: rgba(239, 68, 68, 0.1);
        }
        .quick-actions {
            display: flex;
            gap: 1rem;
            margin: 2rem 0;
            flex-wrap: wrap;
        }
        .action-btn {
            padding: 0.8rem 1.5rem;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: 0.3s;
            text-decoration: none;
        }
        .action-btn:hover {
            background: #2563eb;
            transform: translateY(-2px);
        }
        .session-info {
            background: rgba(30, 41, 59, 0.8);
            border: 1px solid #334155;
            border-radius: 12px;
            padding: 1rem;
            margin-top: 2rem;
            color: #94a3b8;
            font-size: 0.9rem;
        }
        .login-time {
            color: #60a5fa;
            font-weight: 600;
        }
        @media (max-width: 768px) {
            .admin-header {
                flex-direction: column;
                gap: 1rem;
                padding: 1rem;
            }
            .admin-nav {
                flex-wrap: wrap;
                justify-content: center;
            }
            .container {
                padding: 1rem;
            }
            .file-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            .file-actions {
                margin-left: 0;
                width: 100%;
                justify-content: flex-end;
            }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <!-- HEADER -->
    <header class="admin-header">
        <div class="admin-nav">
            <a href="admin.php">
                <i class="fas fa-home"></i> Dashboard
            </a>
            <a href="index.html" target="_blank">
                <i class="fas fa-external-link-alt"></i> Website
            </a>
            <a href="upload-file.html" target="_blank">
                <i class="fas fa-upload"></i> Unggah Gambar
            </a>
        </div>
        
        <div class="user-info">
            <i class="fas fa-user-shield"></i>
            <span>Admin: <?php echo htmlspecialchars($_SESSION['email']); ?></span>
            <a href="?logout=1" class="logout-btn" onclick="return confirm('Yakin ingin logout?')">
                <i class="fas fa-sign-out-alt"></i> Keluar
            </a>
        </div>
    </header>

    <!-- MAIN CONTENT -->
    <main class="container">
        <!-- STATS -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-images"></i>
                </div>
                <div class="stat-value"><?php echo $total_files; ?></div>
                <div class="stat-label">Total Gambar</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-hdd"></i>
                </div>
                <div class="stat-value"><?php echo formatSize($total_size); ?></div>
                <div class="stat-label">Total Penyimpanan</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-server"></i>
                </div>
                <div class="stat-value">10 GB</div>
                <div class="stat-label">Kapasitas Tersedia</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-shield-alt"></i>
                </div>
                <div class="stat-value">1</div>
                <div class="stat-label">Admin Aktif</div>
            </div>
        </div>

        <!-- QUICK ACTIONS -->
        <div class="quick-actions">
            <a href="upload-file.html" target="_blank" class="action-btn">
                <i class="fas fa-upload"></i> Unggah Gambar
            </a>
            <button class="action-btn" onclick="clearOldFiles()">
                <i class="fas fa-trash"></i> Hapus File Lama
            </button>
            <button class="action-btn" onclick="downloadBackup()">
                <i class="fas fa-download"></i> Backup Database
            </button>
        </div>

        <!-- RECENT FILES -->
        <h2 class="section-title">
            <i class="fas fa-clock"></i> File Terbaru
        </h2>
        
        <div class="file-list">
            <?php if (empty($recent_files)): ?>
                <div class="file-item" style="justify-content: center; color: #94a3b8;">
                    <i class="fas fa-folder-open" style="margin-right: 10px;"></i>
                    Belum ada file yang diupload
                </div>
            <?php else: ?>
                <?php foreach ($recent_files as $file): ?>
                    <div class="file-item">
                        <div class="file-name">
                            <i class="fas fa-file-image" style="color: #60a5fa; margin-right: 8px;"></i>
                            <?php echo htmlspecialchars($file['name']); ?>
                        </div>
                        <div class="file-size"><?php echo formatSize($file['size']); ?></div>
                        <div class="file-date"><?php echo $file['date']; ?></div>
                        <div class="file-actions">
                            <a href="uploads/<?php echo urlencode($file['name']); ?>" 
                               target="_blank" class="file-action-btn" title="Lihat">
                                <i class="fas fa-eye"></i>
                            </a>
                            <button class="file-action-btn" 
                                    onclick="copyLink('uploads/<?php echo $file['name']; ?>')"
                                    title="Salin Link">
                                <i class="fas fa-copy"></i>
                            </button>
                            <button class="file-action-btn danger-btn" 
                                    onclick="deleteFile('<?php echo $file['name']; ?>')"
                                    title="Hapus">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- SESSION INFO -->
        <div class="session-info">
            <i class="fas fa-info-circle"></i> 
            Login: <span class="login-time"><?php echo date('d M Y H:i:s', $_SESSION['login_time']); ?></span>
            • Sesi berakhir dalam: <span id="sessionTimer">24:00:00</span>
            • IP: <?php echo $_SERVER['REMOTE_ADDR']; ?>
        </div>
    </main>

    <script>
    // Session timer
    let sessionTime = 24 * 60 * 60; // 24 jam dalam detik
    const timerElement = document.getElementById('sessionTimer');
    
    function updateTimer() {
        if (sessionTime <= 0) {
            timerElement.textContent = "00:00:00";
            alert('Sesi telah berakhir!');
            window.location.href = '?logout=1';
            return;
        }
        
        const hours = Math.floor(sessionTime / 3600);
        const minutes = Math.floor((sessionTime % 3600) / 60);
        const seconds = sessionTime % 60;
        
        timerElement.textContent = 
            `${hours.toString().padStart(2, '0')}:` +
            `${minutes.toString().padStart(2, '0')}:` +
            `${seconds.toString().padStart(2, '0')}`;
        
        sessionTime--;
        setTimeout(updateTimer, 1000);
    }
    
    // Start timer
    updateTimer();
    
    // Utility functions
    function copyLink(path) {
        const fullUrl = window.location.origin + '/' + path;
        navigator.clipboard.writeText(fullUrl)
            .then(() => alert('Link disalin: ' + fullUrl))
            .catch(err => console.error('Copy failed:', err));
    }
    
    function deleteFile(filename) {
        if (!confirm(`Yakin ingin menghapus "${filename}"?`)) return;
        
        fetch('admin-actions.php?action=delete&file=' + encodeURIComponent(filename))
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('File berhasil dihapus');
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Gagal menghapus file');
            });
    }
    
    function clearOldFiles() {
        if (!confirm('Hapus file yang lebih lama dari 30 hari?')) return;
        alert('Fitur dalam pengembangan...');
    }
    
    function downloadBackup() {
        alert('Fitur backup dalam pengembangan...');
    }
    
    // Auto-logout warning (5 menit sebelum timeout)
    setTimeout(() => {
        const warning = confirm('Sesi akan segera berakhir. Lanjutkan sesi?');
        if (warning) {
            // Refresh session
            fetch('admin-actions.php?action=refresh')
                .then(() => location.reload());
        }
    }, (24 * 60 * 60 - 5 * 60) * 1000); // 5 menit sebelum timeout
    </script>
</body>
</html>