Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/reports/dashboard/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/reports/dashboard/maintenance.php

<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// Check permission for maintenance access
if (!checkPermission('admin') && $_SESSION['user_level'] !== 'superuser') {
    header('Location: ' . $_SESSION['user_level'] . '.php?error=access_denied');
    exit();
}

$page_title = 'System Maintenance';
$page_description = 'Database cleanup and system optimization';

$success_message = '';
$error_message = '';

// Handle maintenance actions
if ($_POST) {
    if (isset($_POST['cleanup_notifications'])) {
        $days = (int)$_POST['notification_days'];
        $cleanup_query = "DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL :days DAY)";
        $cleanup_stmt = $db->prepare($cleanup_query);
        $cleanup_stmt->bindParam(':days', $days);
        
        if ($cleanup_stmt->execute()) {
            $deleted_count = $cleanup_stmt->rowCount();
            logAudit('MAINTENANCE', 'notifications', null, null, ['action' => 'cleanup', 'days' => $days, 'deleted' => $deleted_count]);
            $success_message = "Cleaned up $deleted_count old notifications.";
        } else {
            $error_message = 'Failed to cleanup notifications.';
        }
    } elseif (isset($_POST['cleanup_audit_logs'])) {
        $days = (int)$_POST['audit_days'];
        $cleanup_query = "DELETE FROM audit_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL :days DAY)";
        $cleanup_stmt = $db->prepare($cleanup_query);
        $cleanup_stmt->bindParam(':days', $days);
        
        if ($cleanup_stmt->execute()) {
            $deleted_count = $cleanup_stmt->rowCount();
            logAudit('MAINTENANCE', 'audit_logs', null, null, ['action' => 'cleanup', 'days' => $days, 'deleted' => $deleted_count]);
            $success_message = "Cleaned up $deleted_count old audit logs.";
        } else {
            $error_message = 'Failed to cleanup audit logs.';
        }
    } elseif (isset($_POST['optimize_database'])) {
        try {
            $tables = ['users', 'areas', 'districts', 'assemblies', 'notifications', 'audit_logs', 'settings', 'user_sessions'];
            foreach ($tables as $table) {
                $db->exec("OPTIMIZE TABLE $table");
            }
            logAudit('MAINTENANCE', 'database', null, null, ['action' => 'optimize']);
            $success_message = 'Database optimization completed successfully.';
        } catch (Exception $e) {
            $error_message = 'Database optimization failed: ' . $e->getMessage();
        }
    }
}

// Get system statistics
$stats_query = "SELECT 
    (SELECT COUNT(*) FROM notifications) as total_notifications,
    (SELECT COUNT(*) FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)) as old_notifications,
    (SELECT COUNT(*) FROM audit_logs) as total_audit_logs,
    (SELECT COUNT(*) FROM audit_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 365 DAY)) as old_audit_logs,
    (SELECT COUNT(*) FROM user_sessions WHERE last_activity < DATE_SUB(NOW(), INTERVAL 1 DAY)) as old_sessions";

$stats_stmt = $db->prepare($stats_query);
$stats_stmt->execute();
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

include '../includes/header.php';
?>

<?php if ($success_message): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-6 alert-auto-hide">
    <div class="flex items-center">
        <i class="fas fa-check-circle mr-2"></i>
        <span><?php echo htmlspecialchars($success_message); ?></span>
    </div>
</div>
<?php endif; ?>

<?php if ($error_message): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6 alert-auto-hide">
    <div class="flex items-center">
        <i class="fas fa-exclamation-circle mr-2"></i>
        <span><?php echo htmlspecialchars($error_message); ?></span>
    </div>
</div>
<?php endif; ?>

<!-- System Statistics -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
    <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-blue-500">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-bell text-3xl text-blue-500"></i>
            </div>
            <div class="ml-4">
                <p class="text-sm font-medium text-gray-600">Total Notifications</p>
                <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['total_notifications']); ?></p>
                <p class="text-xs text-gray-500"><?php echo number_format($stats['old_notifications']); ?> older than 30 days</p>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-green-500">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-history text-3xl text-green-500"></i>
            </div>
            <div class="ml-4">
                <p class="text-sm font-medium text-gray-600">Audit Logs</p>
                <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['total_audit_logs']); ?></p>
                <p class="text-xs text-gray-500"><?php echo number_format($stats['old_audit_logs']); ?> older than 1 year</p>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-yellow-500">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-clock text-3xl text-yellow-500"></i>
            </div>
            <div class="ml-4">
                <p class="text-sm font-medium text-gray-600">Old Sessions</p>
                <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['old_sessions']); ?></p>
                <p class="text-xs text-gray-500">Inactive for 24+ hours</p>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-sm p-6 border-l-4 border-purple-500">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-database text-3xl text-purple-500"></i>
            </div>
            <div class="ml-4">
                <p class="text-sm font-medium text-gray-600">Database Status</p>
                <p class="text-lg font-semibold text-green-600">Healthy</p>
                <p class="text-xs text-gray-500">Last optimized: Today</p>
            </div>
        </div>
    </div>
</div>

<!-- Maintenance Actions -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- Data Cleanup -->
    <div class="bg-white rounded-lg shadow-sm">
        <div class="p-6 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">Data Cleanup</h3>
            <p class="text-gray-600 text-sm">Remove old records to optimize database performance</p>
        </div>
        <div class="p-6 space-y-6">
            <!-- Notifications Cleanup -->
            <div class="bg-blue-50 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h4 class="font-medium text-gray-800">Cleanup Notifications</h4>
                        <p class="text-sm text-gray-600">Remove notifications older than specified days</p>
                    </div>
                    <i class="fas fa-bell text-blue-600 text-xl"></i>
                </div>
                <form method="POST" class="flex items-end space-x-3">
                    <div class="flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Days to keep</label>
                        <input type="number" 
                               name="notification_days" 
                               value="30" 
                               min="1" 
                               max="365"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    <button type="submit" 
                            name="cleanup_notifications"
                            onclick="return confirm('Are you sure you want to delete old notifications? This action cannot be undone.')"
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200">
                        <i class="fas fa-trash mr-1"></i>Cleanup
                    </button>
                </form>
            </div>

            <!-- Audit Logs Cleanup -->
            <div class="bg-green-50 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h4 class="font-medium text-gray-800">Cleanup Audit Logs</h4>
                        <p class="text-sm text-gray-600">Remove audit logs older than specified days</p>
                    </div>
                    <i class="fas fa-history text-green-600 text-xl"></i>
                </div>
                <form method="POST" class="flex items-end space-x-3">
                    <div class="flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Days to keep</label>
                        <input type="number" 
                               name="audit_days" 
                               value="365" 
                               min="30" 
                               max="1095"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    </div>
                    <button type="submit" 
                            name="cleanup_audit_logs"
                            onclick="return confirm('Are you sure you want to delete old audit logs? This action cannot be undone.')"
                            class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-200">
                        <i class="fas fa-trash mr-1"></i>Cleanup
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- System Optimization -->
    <div class="bg-white rounded-lg shadow-sm">
        <div class="p-6 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">System Optimization</h3>
            <p class="text-gray-600 text-sm">Optimize database performance and system resources</p>
        </div>
        <div class="p-6 space-y-6">
            <!-- Database Optimization -->
            <div class="bg-purple-50 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h4 class="font-medium text-gray-800">Optimize Database</h4>
                        <p class="text-sm text-gray-600">Optimize all database tables for better performance</p>
                    </div>
                    <i class="fas fa-database text-purple-600 text-xl"></i>
                </div>
                <form method="POST">
                    <button type="submit" 
                            name="optimize_database"
                            onclick="return confirm('This will optimize all database tables. Continue?')"
                            class="w-full px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition duration-200">
                        <i class="fas fa-cogs mr-2"></i>Optimize Database
                    </button>
                </form>
            </div>

            <!-- Session Cleanup -->
            <div class="bg-yellow-50 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h4 class="font-medium text-gray-800">Session Cleanup</h4>
                        <p class="text-sm text-gray-600">Remove expired user sessions</p>
                    </div>
                    <i class="fas fa-clock text-yellow-600 text-xl"></i>
                </div>
                <button onclick="cleanupSessions()" 
                        class="w-full px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition duration-200">
                    <i class="fas fa-broom mr-2"></i>Cleanup Sessions
                </button>
            </div>

            <!-- Cache Management -->
            <div class="bg-orange-50 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <h4 class="font-medium text-gray-800">Clear Cache</h4>
                        <p class="text-sm text-gray-600">Clear system cache and temporary files</p>
                    </div>
                    <i class="fas fa-memory text-orange-600 text-xl"></i>
                </div>
                <button onclick="clearCache()" 
                        class="w-full px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition duration-200">
                    <i class="fas fa-trash-alt mr-2"></i>Clear Cache
                </button>
            </div>
        </div>
    </div>
</div>

<!-- System Health Check -->
<div class="mt-8 bg-white rounded-lg shadow-sm">
    <div class="p-6 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800">System Health Check</h3>
        <p class="text-gray-600 text-sm">Monitor system components and performance</p>
    </div>
    <div class="p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div class="text-center">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-server text-2xl text-green-600"></i>
                </div>
                <h4 class="font-medium text-gray-800">Database Connection</h4>
                <p class="text-sm text-green-600 mt-1">
                    <i class="fas fa-check-circle mr-1"></i>Connected
                </p>
            </div>
            
            <div class="text-center">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-shield-alt text-2xl text-blue-600"></i>
                </div>
                <h4 class="font-medium text-gray-800">Security Status</h4>
                <p class="text-sm text-blue-600 mt-1">
                    <i class="fas fa-check-circle mr-1"></i>Secure
                </p>
            </div>
            
            <div class="text-center">
                <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-hdd text-2xl text-yellow-600"></i>
                </div>
                <h4 class="font-medium text-gray-800">Storage Space</h4>
                <p class="text-sm text-yellow-600 mt-1">
                    <i class="fas fa-exclamation-triangle mr-1"></i>Monitor
                </p>
            </div>
            
            <div class="text-center">
                <div class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-tachometer-alt text-2xl text-purple-600"></i>
                </div>
                <h4 class="font-medium text-gray-800">Performance</h4>
                <p class="text-sm text-purple-600 mt-1">
                    <i class="fas fa-check-circle mr-1"></i>Optimal
                </p>
            </div>
        </div>
    </div>
</div>

<script>
function cleanupSessions() {
    if (confirm('Remove all expired user sessions?')) {
        fetch('maintenance-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=cleanup_sessions'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('Sessions cleaned up successfully', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('Failed to cleanup sessions', 'error');
            }
        })
        .catch(error => {
            showToast('An error occurred', 'error');
        });
    }
}

function clearCache() {
    if (confirm('Clear all system cache?')) {
        fetch('maintenance-actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=clear_cache'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('Cache cleared successfully', 'success');
            } else {
                showToast('Failed to clear cache', 'error');
            }
        })
        .catch(error => {
            showToast('An error occurred', 'error');
        });
    }
}
</script>

<?php include '../includes/footer.php'; ?>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists