<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Website\SiteUtmTag;  // Make sure to import the UTM Tag model
use App\Models\Website\SiteUtmModuleType;  // Make sure to import the UTM Tag model

class StoreUTMParameters
{ 
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // List of UTM parameters to capture
        $utmParameters = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
        $utmData = [];

        foreach ($utmParameters as $param) {
            if ($request->has($param)) {
                // Store UTM parameters in session
                $utmData[$param] = $request->get($param);
                $request->session()->put($param, $request->get($param));
            }
        }

        // Get the current route name
        $currentRouteName = $request->route()->getName();
        //dd($currentRouteName);
        // Retrieve the utm_module_type id based on the current route name
        $utmModuleType = SiteUtmModuleType::whereJsonContains('route_names', $currentRouteName)->first();

        //dd($utmModuleType);

        if ($utmModuleType) {
            $utmData['utm_module_type'] = $utmModuleType->id;
        } else {
            // Handle cases where the route name does not match any module type
            $utmData['utm_module_type'] = null; // Or some default value
        }
            
        $utmData['route_name'] = $currentRouteName;

        // Optionally, get the full URL
        $currentUrl = $request->fullUrl();
        $utmData['url'] = $currentUrl;

        if ($utmData['route_name'] == 'save.site.service.booking.mog') {
            //Get UTM data based on session
            $storedUTM = SiteUtmTag::where('session_id', session()->getId())->first();

            $utmData['utm_source'] = $storedUTM->utm_source ?? null;
            $utmData['utm_medium'] = $storedUTM->utm_medium ?? null;
            $utmData['utm_campaign'] = $storedUTM->utm_campaign ?? null;
            $utmData['utm_term'] = $storedUTM->utm_term ?? null;
            $utmData['utm_content'] = $storedUTM->utm_content ?? null;
        }

        if (!empty($utmData)) {
            $utmData['session_id'] = session()->getId();
            //dd($utmData);
            SiteUtmTag::create($utmData);
        }

        return $next($request);
    }
}
