<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Http\Request;

class MaintenanceController extends Controller
{
    private $secret;
    private $bypass;

    public function __construct()
    {
        $this->secret = env('MAINTENANCE_SECRET');
        $this->bypass = env('MAINTENANCE_SECRET_URL');
    }

    // ✅ Enable maintenance mode
    public function enable($secret)
    {
        if ($secret !== $this->secret) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 401);
        }

        // Enable maintenance with secret bypass URL
        Artisan::call('down', ['--secret' => $this->bypass]);

        return response()->json([
            'status' => 'success',
            'message' => 'Maintenance mode enabled successfully.',
            'bypass_url' => url($this->bypass . '/maintenance/disable/' . $this->secret),
        ]);
    }

    // ✅ Disable maintenance mode (always works)
    public function disable($secret)
    {
        if ($secret !== $this->secret) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 401);
        }

        // Run up command
        Artisan::call('up');

        // Fallback: manually delete down file
        $downFile = storage_path('framework/down');
        if (file_exists($downFile)) {
            @unlink($downFile);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Maintenance mode disabled successfully.',
        ]);
    }
}
