<?php

namespace App\Services;

/**
 * ITSWEBER CMS – Maintenance Mode Service
 *
 * Manages the user-controlled maintenance flag (storage/.maintenance_mode).
 * Distinct from storage/.maintenance which is used exclusively by BackupService
 * during backup restore and CMS update operations (auto-managed).
 *
 * Both flags cause the frontend to be blocked; this service manages only the
 * user-activated flag and its configuration JSON payload.
 */
class MaintenanceService
{
    private const FLAG_FILE = '/storage/.maintenance_mode';

    // ─────────────────────────────────────────────────────────────────────────
    // Public API
    // ─────────────────────────────────────────────────────────────────────────

    /**
     * Activate maintenance mode and persist configuration.
     */
    public static function enable(
        string $basePath,
        string $title,
        string $message,
        string $siteName
    ): bool {
        $data = [
            'enabled'      => true,
            'title'        => $title ?: 'Website in Wartung',
            'message'      => $message ?: 'Diese Website wird aktuell gewartet. Bitte versuchen Sie es später erneut.',
            'site_name'    => $siteName,
            'activated_at' => date('c'),
        ];

        $result = file_put_contents(
            self::path($basePath),
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        );

        return $result !== false;
    }

    /**
     * Deactivate maintenance mode.
     */
    public static function disable(string $basePath): void
    {
        $file = self::path($basePath);
        if (is_file($file)) {
            @unlink($file);
        }
    }

    /**
     * Check whether user-controlled maintenance mode is active.
     */
    public static function isActive(string $basePath): bool
    {
        return is_file(self::path($basePath));
    }

    /**
     * Read the persisted maintenance configuration.
     * Returns an empty array when the flag is not set.
     */
    public static function getConfig(string $basePath): array
    {
        $file = self::path($basePath);
        if (!is_file($file)) {
            return [];
        }

        $raw  = @file_get_contents($file);
        $data = $raw !== false ? json_decode($raw, true) : null;

        return is_array($data) ? $data : [];
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Helpers
    // ─────────────────────────────────────────────────────────────────────────

    private static function path(string $basePath): string
    {
        return rtrim($basePath, '/') . self::FLAG_FILE;
    }
}
