<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';

// Handle cache actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clear_cache'])) {
        // In a real application, this would clear various caches
        // For demonstration, we'll just simulate the action
        $success = "Cache cleared successfully! (This is a simulation - implement actual cache clearing in production)";
        
        // Log the activity
        $pdo->prepare("INSERT INTO activities (
            user_id, activity_type, description, created_at
        ) VALUES (?, ?, ?, NOW())")->execute([
            $_SESSION['user_id'],
            "cache_cleared",
            "Admin {$admin['first_name']} {$admin['last_name']} cleared the application cache"
        ]);
    }
    
    if (isset($_POST['clear_session_cache'])) {
        // Clear session cache
        $success = "Session cache cleared successfully! (This is a simulation)";
        
        // Log the activity
        $pdo->prepare("INSERT INTO activities (
            user_id, activity_type, description, created_at
        ) VALUES (?, ?, ?, NOW())")->execute([
            $_SESSION['user_id'],
            "session_cache_cleared",
            "Admin {$admin['first_name']} {$admin['last_name']} cleared the session cache"
        ]);
    }
}

// Get cache statistics (simulated)
$cache_stats = [
    'page_cache_size' => '15.2 MB',
    'session_cache_size' => '2.8 MB',
    'database_cache_size' => '8.4 MB',
    'total_cache_size' => '26.4 MB',
    'cache_efficiency' => '92%'
];

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Cache Management - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .cache-item {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .cache-size {
            font-size: 1.5em;
            font-weight: 600;
            color: #3fb7fe;
        }
        .cache-efficiency {
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: 600;
            display: inline-block;
        }
        .efficiency-high {
            background: #d4edda;
            color: #155724;
        }
        .efficiency-medium {
            background: #fff3cd;
            color: #856404;
        }
        .efficiency-low {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <?php include 'admin-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="section-title position-relative mb-4">
            <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">System Management</h6>
            <h1 class="display-5">Cache Management</h1>
        </div>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <!-- Cache Statistics -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="stat-card">
                    <div class="card-body">
                        <h6>Page Cache</h6>
                        <div class="cache-size"><?= htmlspecialchars($cache_stats['page_cache_size']) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stat-card" style="border-left-color: #28a745;">
                    <div class="card-body">
                        <h6>Session Cache</h6>
                        <div class="cache-size"><?= htmlspecialchars($cache_stats['session_cache_size']) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stat-card" style="border-left-color: #ffc107;">
                    <div class="card-body">
                        <h6>Database Cache</h6>
                        <div class="cache-size"><?= htmlspecialchars($cache_stats['database_cache_size']) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stat-card" style="border-left-color: #17a2b8;">
                    <div class="card-body">
                        <h6>Total Cache</h6>
                        <div class="cache-size"><?= htmlspecialchars($cache_stats['total_cache_size']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Cache Efficiency -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="cache-item">
                    <h5>Cache Efficiency</h5>
                    <p>The cache efficiency indicates how effectively the cache is reducing database queries and page load times.</p>
                    <div class="cache-efficiency efficiency-high">
                        <?= htmlspecialchars($cache_stats['cache_efficiency']) ?> Efficient
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="cache-item">
                    <h5>Last Cache Update</h5>
                    <p>Cache was last updated: <?= date('F j, Y, g:i a') ?></p>
                    <p>Next automatic update: <?= date('F j, Y, g:i a', strtotime('+1 hour')) ?></p>
                </div>
            </div>
        </div>
        
        <!-- Cache Management Actions -->
        <div class="row">
            <div class="col-md-6">
                <div class="cache-item">
                    <h5><i class="fas fa-memory mr-2"></i> Page Cache</h5>
                    <p>Stores rendered pages to serve them faster on subsequent requests.</p>
                    <form method="POST">
                        <button type="submit" name="clear_cache" class="btn btn-danger">
                            <i class="fas fa-trash-alt mr-2"></i> Clear Page Cache
                        </button>
                    </form>
                </div>
            </div>
            <div class="col-md-6">
                <div class="cache-item">
                    <h5><i class="fas fa-user-clock mr-2"></i> Session Cache</h5>
                    <p>Stores user session data for faster access during their visit.</p>
                    <form method="POST">
                        <button type="submit" name="clear_session_cache" class="btn btn-warning">
                            <i class="fas fa-trash-alt mr-2"></i> Clear Session Cache
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Cache Information -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="cache-item">
                    <h5><i class="fas fa-info-circle mr-2"></i> Cache Information</h5>
                    <p>Cache management helps improve website performance by storing frequently accessed data in memory.</p>
                    <ul>
                        <li><strong>Page Cache:</strong> Stores complete HTML pages for faster loading.</li>
                        <li><strong>Session Cache:</strong> Stores user session data for quick retrieval.</li>
                        <li><strong>Database Cache:</strong> Stores query results to reduce database load.</li>
                    </ul>
                    <p><strong>Note:</strong> Clearing cache will temporarily slow down page loads until the cache is rebuilt.</p>
                </div>
            </div>
        </div>
    </div>

    <?php include 'footer.php'; ?>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
</body>
</html>