<?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        = $request->input('maintenance_show_logo') ? true : false;
        $adminHint       = $request->input('maintenance_admin_hint') ? true : false;
        $backgroundImage = trim($request->input('maintenance_background_image', ''));
        $customLogo      = trim($request->input('maintenance_custom_logo', ''));
        $siteName        = Setting::get('site_name', 'Website');
        $logoPath        = Setting::get('logo_header', '');

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

        if ($ok) {
            set_flash('success', 'Wartungsmodus aktiviert – das Frontend ist jetzt für Besucher gesperrt.');
        } else {
            set_flash('error', __('messages.error.storage_not_writable'));
        }

        Response::redirect(admin_url('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_url('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'        => $request->input('show_logo') ? true : false,
            'admin_hint'       => $request->input('admin_hint') ? true : false,
            'logo_path'        => Setting::get('logo_header', ''),
            'background_image' => trim($request->input('background_image', '')),
            'custom_logo'      => trim($request->input('custom_logo', '')),
        ];

        // 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
            // Pass preview config so page.php uses it instead of reading from file
            $mainTitle   = $previewConfig['title'];
            $mainMessage = $previewConfig['message'];
            $mainSite    = $previewConfig['site_name'];
            $config      = $previewConfig;
            include $basePath . '/app/Maintenance/page.php';
        }
        exit;
    }
}
