<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Support\ActivityLogger;
use Illuminate\Contracts\Foundation\MaintenanceMode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Str;

class OperationsController extends Controller
{
    public function index()
    {
        $maintenanceActive = app()->isDownForMaintenance();
        $maintenanceSecret = null;
        if ($maintenanceActive) {
            try {
                $data = app(MaintenanceMode::class)->data();
                $maintenanceSecret = $data['secret'] ?? null;
            } catch (\Throwable) {
                $maintenanceSecret = null;
            }
        }

        $backupDir = storage_path('app/backups');
        $paths = glob($backupDir.DIRECTORY_SEPARATOR.'backup_*.zip') ?: [];
        rsort($paths, SORT_STRING);
        $backups = [];
        foreach (array_slice($paths, 0, 30) as $path) {
            $backups[] = [
                'name' => basename($path),
                'size' => @filesize($path) ?: 0,
                'mtime' => @filemtime($path) ?: 0,
            ];
        }

        return view('admin.operations.index', compact(
            'maintenanceActive',
            'maintenanceSecret',
            'backups'
        ));
    }

    public function runBackup(Request $request)
    {
        @set_time_limit(0);

        $exitCode = Artisan::call('backup:application');
        $output = trim(Artisan::output());

        if ($exitCode !== 0) {
            ActivityLogger::log('operations.backup.failed', Str::limit($output, 400));

            return back()
                ->with('error', __('Backup failed.') . ($output !== '' ? ' '.$output : ''));
        }

        ActivityLogger::log('operations.backup.created', __('Application backup created (admin).'));

        return back()
            ->with('success', __('Backup created successfully.'))
            ->with('backup_cli_output', $output !== '' ? $output : null);
    }

    public function maintenanceEnable(Request $request)
    {
        if (app()->isDownForMaintenance()) {
            return back()->with('info', __('The site is already in maintenance mode.'));
        }

        $options = [];

        if ($request->boolean('bypass_secret')) {
            $options['--with-secret'] = true;
        }

        // Kein --render: Wartungsseite kommt dynamisch aus errors.maintenance (Middleware),
        // damit z. B. Admin-Link immer aktuell ist und kein veraltetes HTML in storage/framework/down liegt.
        $exitCode = Artisan::call('down', $options);

        if ($exitCode !== 0) {
            $out = trim(Artisan::output());

            return back()->with('error', __('Could not enable maintenance mode.') . ($out !== '' ? ' '.$out : ''));
        }

        ActivityLogger::log('operations.maintenance.enabled', __('Maintenance mode enabled (admin).'));

        $bypassUrl = null;
        if ($request->boolean('bypass_secret') && app()->isDownForMaintenance()) {
            try {
                $secret = app(MaintenanceMode::class)->data()['secret'] ?? null;
                if (is_string($secret) && $secret !== '') {
                    $bypassUrl = url($secret);
                }
            } catch (\Throwable) {
                // ignore
            }
        }

        return back()
            ->with('success', __('Maintenance mode has been enabled.'))
            ->with('maintenance_bypass_url', $bypassUrl);
    }

    public function maintenanceDisable()
    {
        if (! app()->isDownForMaintenance()) {
            return back()->with('info', __('Maintenance mode is not active.'));
        }

        $exitCode = Artisan::call('up');

        if ($exitCode !== 0) {
            $out = trim(Artisan::output());

            return back()->with('error', __('Could not disable maintenance mode.') . ($out !== '' ? ' '.$out : ''));
        }

        ActivityLogger::log('operations.maintenance.disabled', __('Maintenance mode disabled (admin).'));

        return back()->with('success', __('Maintenance mode has been disabled. The site is live again.'));
    }
}
