<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Setting;

class CheckMaintenance
{
    public function handle(Request $request, Closure $next)
    {
        // ✅ 1. Admin tidak terpengaruh maintenance apapun
        if (Auth::check() && Auth::user()->is_admin) {
            return $next($request);
        }

        // ✅ 2. Kecualikan halaman publik (landing, login, register)
       if (
    $request->is('/') || 
    $request->is('login') ||
    $request->is('register') ||
    $request->is('about') ||
    $request->is('syarat') ||
    $request->is('informasi') ||
    $request->is('callback/*') ||
    $request->is('api/webhook/smscode')
) {
    return $next($request);
}

        // ✅ 3. Maintenance Global
        // Semua halaman user (selain "/") terkena maintenance global
        // ✅ 3. Maintenance Global
if (
    Setting::isMaintenance('global') &&
    $request->is([
        'dashboard',
        'deposit',
        'deposit/*',
        'orderv2',
        'orderv2/*',
        'riwayat',
        'riwayat/*',
        'daftar-harga-v2',
        'daftar-harga-v2/*',
        'referral',
        'referral/*',
        'syarat',
        'syarat/*',
        'informasi',
        'informasi/*',
        'profile',
        'profile/*',
        'dokumentasi-api/v2',
        'dokumentasi-api/v2/*',
    ])
) {
    return response()->view('maintenance.all');
}

        // ✅ 4. Maintenance khusus deposit
        if ($request->is('deposit*') && Setting::isMaintenance('deposit')) {
            return response()->view('maintenance.deposit');
        }

        // ✅ 5. Maintenance khusus order (order & orderv2)
        if (
         $request->is(['order', 'order/*']) 
          && Setting::isMaintenance('order')
        ) {
        return response()->view('maintenance.order');
        }

        // ✅ 6. Jika tidak ada maintenance aktif
        return $next($request);
    }
}
