<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Setting;
use App\Services\MaintenanceService;

/**
 * ITSWEBER CMS – Admin Maintenance Controller
 *
 * Allows admins to enable / disable the user-controlled maintenance mode
 * (storage/.maintenance_mode). The backup/restore flag (storage/.maintenance)
 * is managed exclusively by BackupService and is not touched here.
 */
class MaintenanceController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $basePath = $this->app->basePath();

        $isActive       = MaintenanceService::isActive($basePath);
        $config         = MaintenanceService::getConfig($basePath);
        $backupFlagSet  = is_file($basePath . '/storage/.maintenance');

        $this->renderAdmin('maintenance/index', [
            'pageTitle'     => 'Wartungsmodus',
            'isActive'      => $isActive,
            'config'        => $config,
            'backupFlagSet' => $backupFlagSet,
            'auth'          => $this->auth(),
            'csrf'          => $this->csrf(),
        ]);
    }

    /**
     * POST /admin/maintenance/enable
     */
    public function enable(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $basePath = $this->app->basePath();

        $title    = trim($request->input('maintenance_title', ''));
        $message  = trim($request->input('maintenance_message', ''));
        $siteName = Setting::get('site_name', 'Website');

        $ok = MaintenanceService::enable($basePath, $title, $message, $siteName);

        if ($ok) {
            set_flash('success', 'Wartungsmodus aktiviert – das Frontend ist jetzt für Besucher gesperrt.');
        } else {
            set_flash('error', 'Fehler beim Aktivieren: storage/ ist nicht beschreibbar.');
        }

        Response::redirect('/admin/maintenance');
    }

    /**
     * POST /admin/maintenance/disable
     */
    public function disable(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $basePath = $this->app->basePath();

        MaintenanceService::disable($basePath);

        set_flash('success', 'Wartungsmodus deaktiviert – die Website ist wieder öffentlich erreichbar.');
        Response::redirect('/admin/maintenance');
    }
}
