<?php

use App\Http\Middleware\ActivationCheckMiddleware;
use App\Http\Middleware\AdminMiddleware;
use App\Http\Middleware\AdminRentalModuleCheckMiddleware;
// Core Laravel web middleware
use App\Http\Middleware\APIGuestMiddleware;
use App\Http\Middleware\Authenticate;
use App\Http\Middleware\CurrentModule;
use App\Http\Middleware\DmTokenIsValid;
use App\Http\Middleware\EncryptCookies;
use App\Http\Middleware\InstallationMiddleware;
use App\Http\Middleware\Localization;
// Custom middleware
use App\Http\Middleware\LocalizationMiddleware;
use App\Http\Middleware\ModuleCheckMiddleware;
use App\Http\Middleware\ModulePermissionMiddleware;
use App\Http\Middleware\ProviderRentalModuleCheckMiddleware;
use App\Http\Middleware\ReactValid;
use App\Http\Middleware\RedirectIfAuthenticated;
use App\Http\Middleware\Subscription;
use App\Http\Middleware\ShowroomSessionMiddleware;
use App\Http\Middleware\TrustProxies;
use App\Http\Middleware\VendorMiddleware;
use App\Http\Middleware\VendorTokenIsValid;
use App\Services\Customer\CustomerQualityService;
use App\Http\Middleware\VerifyCsrfToken;
use App\CentralLogics\Helpers;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
use Illuminate\Auth\Middleware\RequirePassword;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\SetCacheHeaders;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Routing\Middleware\ValidateSignature;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;

return Application::configure(basePath: dirname(__DIR__))

    ->withRouting(
        // commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )

    ->withSchedule(function (Schedule $schedule) {
        if (! filter_var(env('EXTERNAL_SCHEDULER_ENABLED', false), FILTER_VALIDATE_BOOL)) {
            return;
        }

        $courierIntegration = Helpers::get_business_settings('courier_integration') ?? [];

        if (data_get($courierIntegration, 'enabled') && data_get($courierIntegration, 'auto_sync_enabled')) {
            $schedule->command('courier:sync-statuses --limit=50')
                ->everyThirtyMinutes()
                ->withoutOverlapping()
                ->runInBackground();
        }

        $schedule->command('courier:retry-out-for-delivery-sms --limit=50')
            ->everyTenMinutes()
            ->withoutOverlapping();

        if (data_get(app(CustomerQualityService::class)->settings(), 'auto_sync_enabled', false)) {
            $schedule->command('customer-quality:auto-sync')
                ->hourly()
                ->withoutOverlapping()
                ->runInBackground();
        }

        if (config('services.meta_marketing.insights_sync_enabled')) {
            $days = max(1, min(180, (int) config('services.meta_marketing.insights_sync_days', 14)));
            $time = (string) config('services.meta_marketing.insights_sync_time', '02:15');

            $schedule->command("meta-ads:sync-insights --days={$days}")
                ->dailyAt($time)
                ->withoutOverlapping()
                ->runInBackground();
        }
    })

    ->withMiddleware(function (Middleware $middleware) {

        $middleware->use([
            TrustProxies::class,
            \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
            \App\Http\Middleware\TrimStrings::class,
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            \Illuminate\Http\Middleware\HandleCors::class,
        ]);

        $middleware->group('web', [
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            StartSession::class,
            ShareErrorsFromSession::class,
            VerifyCsrfToken::class,
            SubstituteBindings::class,
            Localization::class,
        ]);

        $middleware->group('api', [
            SubstituteBindings::class,
        ]);

        $middleware->alias([
            'auth' => Authenticate::class,
            'guest' => RedirectIfAuthenticated::class,

            'admin' => AdminMiddleware::class,
            'vendor' => VendorMiddleware::class,
            'vendor.api' => VendorTokenIsValid::class,
            'dm.api' => DmTokenIsValid::class,
            'module' => ModulePermissionMiddleware::class,
            'installation-check' => InstallationMiddleware::class,
            'actch' => ActivationCheckMiddleware::class,
            'localization' => LocalizationMiddleware::class,
            'subscription' => Subscription::class,
            'showroom.session' => ShowroomSessionMiddleware::class,
            'react' => ReactValid::class,
            'apiGuestCheck' => APIGuestMiddleware::class,
            'auth.basic' => AuthenticateWithBasicAuth::class,
            'cache.headers' => SetCacheHeaders::class,
            'can' => Authorize::class,
            'password.confirm' => RequirePassword::class,
            'signed' => ValidateSignature::class,
            'throttle' => ThrottleRequests::class,
            'verified' => EnsureEmailIsVerified::class,
            'module-check' => ModuleCheckMiddleware::class,
            'current-module' => CurrentModule::class,
            'admin-rental-module' => AdminRentalModuleCheckMiddleware::class,
            'provider-rental-module' => ProviderRentalModuleCheckMiddleware::class,
        ]);
    })

    ->withExceptions(function (Exceptions $exceptions) {
        //
    })

    ->create();

// $requestUri = $_SERVER['REQUEST_URI'] ?? '';
// if (!str_starts_with($requestUri, '/image-proxy')) {
//     header('Access-Control-Allow-Origin: *');
// }
// header('Access-Control-Allow-Methods: *');
// header('Access-Control-Allow-Headers: *');
