<?php
// /admin/cache.php
$page_title = "Maintenance & Cleanup";
require_once 'includes/header.php';

$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Clear Expired Ads ---
    if (isset($_POST['clear_expired_ads'])) {
        // This will permanently delete ads marked as 'expired'
        $stmt = $conn->prepare("DELETE FROM ads WHERE status = 'expired'");
        if ($stmt->execute()) {
            $deleted_count = $stmt->affected_rows;
            $message = "Successfully deleted $deleted_count expired ad(s).";
            $message_type = 'success';
        } else {
            $message = "Failed to delete expired ads.";
            $message_type = 'error';
        }
        $stmt->close();
    }

    // --- Delete Inactive Users ---
    if (isset($_POST['delete_inactive_users'])) {
        // Deletes users who haven't logged in for over a year and have 0 ads
        $one_year_ago = date('Y-m-d H:i:s', strtotime('-1 year'));
        $stmt = $conn->prepare("
            DELETE FROM users 
            WHERE (last_login IS NULL OR last_login < ?) 
            AND id NOT IN (SELECT DISTINCT user_id FROM ads)
            AND is_admin = 0
        ");
        $stmt->bind_param("s", $one_year_ago);
        if ($stmt->execute()) {
            $deleted_count = $stmt->affected_rows;
            $message = "Successfully deleted $deleted_count inactive user(s).";
            $message_type = 'success';
        } else {
            $message = "Failed to delete inactive users.";
            $message_type = 'error';
        }
        $stmt->close();
    }
    
    // --- Clear Application Cache ---
    if (isset($_POST['clear_app_cache'])) {
        $cache_dir = dirname(__DIR__) . '/cache'; // Assumes a 'cache' directory at the project root
        $files_deleted = 0;
        $files_failed = 0;

        if (is_dir($cache_dir)) {
            $files = glob($cache_dir . '/*'); // get all file names in the directory
            foreach($files as $file) {
                // Delete file if it's a file and not a .gitignore file
                if(is_file($file) && basename($file) !== '.gitignore') {
                    if(unlink($file)) {
                        $files_deleted++;
                    } else {
                        $files_failed++;
                    }
                }
            }

            if ($files_failed > 0) {
                 $message = "Cleared $files_deleted file(s), but failed to delete $files_failed file(s). Please check file permissions.";
                 $message_type = 'error';
            } else {
                 $message = "Successfully cleared $files_deleted file(s) from the application cache.";
                 $message_type = 'success';
            }
        } else {
            $message = "Cache directory could not be found. No files were deleted.";
            $message_type = 'error';
        }
    }
}
?>

<?php if ($message): ?>
    <div class="mb-6 p-4 rounded-md <?php echo $message_type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
        <?php echo escape($message); ?>
    </div>
<?php endif; ?>

<div class="bg-white p-8 rounded-lg shadow-md max-w-2xl mx-auto">
    <h1 class="text-2xl font-bold mb-2">Maintenance & Cleanup</h1>
    <p class="text-gray-600 mb-6">Perform various cleanup tasks to keep the database and filesystem optimized.</p>

    <div class="space-y-6">
        <div class="bg-gray-50 p-4 rounded-lg border flex items-center justify-between">
            <div>
                <h3 class="font-semibold">Clear Expired Ads</h3>
                <p class="text-sm text-gray-600">Permanently delete all ads that have the 'expired' status.</p>
            </div>
            <form action="/admin/cache.php" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete all expired ads? This cannot be undone.');">
                <button type="submit" name="clear_expired_ads" class="bg-red-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-red-700">Delete Now</button>
            </form>
        </div>

        <div class="bg-gray-50 p-4 rounded-lg border flex items-center justify-between">
            <div>
                <h3 class="font-semibold">Delete Inactive Users</h3>
                <p class="text-sm text-gray-600">Delete users with no ads who haven't logged in for over a year.</p>
            </div>
            <form action="/admin/cache.php" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete inactive users? This cannot be undone.');">
                <button type="submit" name="delete_inactive_users" class="bg-red-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-red-700">Delete Now</button>
            </form>
        </div>
        
        <div class="bg-gray-50 p-4 rounded-lg border flex items-center justify-between">
            <div>
                <h3 class="font-semibold">Clear Application Cache</h3>
                <p class="text-sm text-gray-600">Permanently delete temporary files from the system cache.</p>
            </div>
             <form action="/admin/cache.php" method="POST" onsubmit="return confirm('Are you sure you want to clear the application cache? This may temporarily slow down the site.');">
                <button type="submit" name="clear_app_cache" class="bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700">Clear Cache</button>
            </form>
        </div>
    </div>
</div>