<?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'     => __('admin.nav.maintenance'),
            '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', ''));
        $subtitle    = trim($request->input('maintenance_subtitle', ''));
        $contactInfo = trim($request->input('maintenance_contact_info', ''));
        $returnInfo  = trim($request->input('maintenance_return_info', ''));
        $showLogo    = (bool) $request->input('maintenance_show_logo');
        $adminHint   = (bool) $request->input('maintenance_admin_hint', true);
        $siteName    = Setting::get('site_name', 'Website');
        $logoPath    = Setting::get('logo_header', '');

        $ok = MaintenanceService::enable(
            $basePath,
            $title,
            $message,
            $siteName,
            $subtitle,
            $contactInfo,
            $showLogo,
            $adminHint,
            $returnInfo,
            $logoPath
        );

        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');
    }

    /**
     * GET /admin/maintenance/preview – render maintenance page preview.
     *
     * Renders the maintenance page with provided query parameters
     * without actually enabling maintenance mode.
     */
    public function preview(Request $request, array $params = []): void
    {
        $basePath = $this->app->basePath();

        $mainTitle   = trim($request->input('title', 'Website in Wartung'));
        $mainMessage = trim($request->input('message', 'Wir arbeiten gerade an der Website.'));
        $siteName    = Setting::get('site_name', 'Website');

        // Build preview config
        $previewConfig = [
            'title'        => $mainTitle,
            'message'      => $mainMessage,
            'site_name'    => $siteName,
            'subtitle'     => trim($request->input('subtitle', '')),
            'contact_info' => trim($request->input('contact_info', '')),
            'return_info'  => trim($request->input('return_info', '')),
            'show_logo'    => (bool) $request->input('show_logo'),
            'admin_hint'   => (bool) $request->input('admin_hint'),
            'logo_path'    => Setting::get('logo_header', ''),
        ];

        // Determine active theme for theme-aware rendering
        $activeTheme = Setting::get('active_theme', 'default');
        $themeMaintenancePage = $basePath . '/themes/' . $activeTheme . '/templates/maintenance.php';

        header('Content-Type: text/html; charset=UTF-8');

        if (is_file($themeMaintenancePage)) {
            // Theme provides its own maintenance page
            $config = $previewConfig;
            include $themeMaintenancePage;
        } else {
            // Fall back to core maintenance page
            $mainTitle   = $previewConfig['title'];
            $mainMessage = $previewConfig['message'];
            $mainSite    = $previewConfig['site_name'];
            include $basePath . '/app/Maintenance/page.php';
        }
        exit;
    }
}
