<?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.
     *
     * @param string $basePath         Base path of the application
     * @param string $title            Main title
     * @param string $message          Main message
     * @param string $siteName         Site name
     * @param string $subtitle         Optional subtitle
     * @param string $contactInfo      Optional contact information
     * @param bool   $showLogo         Whether to show logo
     * @param bool   $adminHint        Whether to show admin login hint
     * @param string $returnInfo       Optional return/expected-back text
     * @param string $logoPath         Optional path to global logo for maintenance page
     * @param string $backgroundImage  Optional path to background image
     * @param string $customLogo       Optional path to custom logo (overrides global logo)
     */
    public static function enable(
        string $basePath,
        string $title,
        string $message,
        string $siteName,
        string $subtitle = '',
        string $contactInfo = '',
        bool $showLogo = true,
        bool $adminHint = false,
        string $returnInfo = '',
        string $logoPath = '',
        string $backgroundImage = '',
        string $customLogo = ''
    ): 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,
            'subtitle'         => $subtitle,
            'contact_info'     => $contactInfo,
            'show_logo'        => $showLogo,
            'admin_hint'       => $adminHint,
            'return_info'      => $returnInfo,
            'logo_path'        => $logoPath,
            'background_image' => $backgroundImage,
            'custom_logo'      => $customLogo,
            '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.
     * Includes defaults for new optional fields.
     */
    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;

        if (!is_array($data)) {
            return [];
        }

        // Ensure all fields have defaults
        return [
            'enabled'          => $data['enabled'] ?? false,
            'title'            => $data['title'] ?? '',
            'message'          => $data['message'] ?? '',
            'site_name'        => $data['site_name'] ?? '',
            'subtitle'         => $data['subtitle'] ?? '',
            'contact_info'     => $data['contact_info'] ?? '',
            'show_logo'        => $data['show_logo'] ?? true,
            'admin_hint'       => $data['admin_hint'] ?? false,
            'return_info'      => $data['return_info'] ?? '',
            'logo_path'        => $data['logo_path'] ?? '',
            'background_image' => $data['background_image'] ?? '',
            'custom_logo'      => $data['custom_logo'] ?? '',
            'activated_at'     => $data['activated_at'] ?? '',
        ];
    }

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

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