@props([
    'item' => null,
    'ajaxurl' => '',
])
@php
// utm_source, utm_medium, utm_campaign, etc.
// https://en.wikipedia.org/wiki/UTM_parameters
// utm_source	Identifies which site sent the traffic, and is a required parameter.
//              utm_source=google
// utm_medium	Identifies what type of link was used, such as email or pay-per-click advertising.
//           	utm_medium=ppc
// utm_campaign	Identifies a specific product promotion or strategic campaign.
//          	utm_campaign=spring_sale
// utm_term 	Identifies search terms.
//           	utm_term=running+shoes
// utm_content	Identifies what specifically was clicked to bring the user to the site,
//              such as a banner ad or a text link. It is often used for A/B testing and 
//              content-targeted ads.
//          	utm_content=logolink or utm_content=textlink

$debug = !empty(request()->bs4journey) ;
if( request()->bs4journey === 'forget' ) {
    // allowing to reset the journey record withoout amending code
    session()->forget('bs4_journey');
}

$journey = session('bs4_journey', []);

$from = request()->headers->get('referer');
$from_hostname = parse_url($from, PHP_URL_HOST);

$current = url()->current();
$current_hostname = parse_url($current, PHP_URL_HOST);

$now = date('Y-m-d H:i:s');

// we could do this -- but the session expires in 120 minutes anway
// if (array_key_exists('lastdate', $journey) && (strtotime($now) - strtotime($journey['lastdate'])) > 86400) {

$sessid = session()->getId();
if (!array_key_exists('session_id', $journey)) {
    $journey['session_id'] = $sessid;
}

$utms = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content' ];
foreach($utms as $utm) {
    $setone = false;
    if(!empty(request()->$utm)) {
        $journey[$utm] = request()->$utm;
        $setone = true;
    }
    if ($setone) {
        $journey['utm_date_time'] = $now;
    }
}

// make sure two array keys exist
if(!array_key_exists('history', $journey) ) {
    $journey['history'] = [];
}
if ( !array_key_exists('src_url', $journey) ) {
        $journey['src_url'] = [];
}

if ( (!empty($from) || empty($journey['src_url'])) && ( $from_hostname != $current_hostname )) {
    // $from is not the local host, so record that in the history
    // or src_url is empty so first page load

    $src = [ 'url' => $from ?? $current,
             'datetime' => $now,
             'hostname' => $from_hostname ?? $current_hostname,
    ];
    
    $src['utm_source'] = '';
    if(empty(request()->utm_source)) {
        if ( Str::contains($from_hostname, 'google') ) {
            $src['utm_source'] = 'Organic Search - Google';
        } else if ( Str::contains($from_hostname, 'twitter.com')  || ( $from_hostname == 'x.com' )) {
            $src['utm_source'] = 'Organic Search - Twitter';
        } else if ( !empty($from) && ($from_hostname != $current_hostname) ) {
            $src['utm_source'] = 'Other - ' . $from_hostname;
        }
    }
    // overrides utm_src if set in the params of the url
    foreach($utms as $utm) {
        $setone = false;
        if(!empty(request()->$utm)) {
            $src[$utm] = request()->$utm;
            $setone = true;
        }
    }
    if ( empty($src['utm_source']) ) {
        $src['utm_source'] = 'Direct';
    }

    $journey['src_url'][] = $src;
    if ( !empty($from) && ( $from_hostname != $current_hostname ) ) {
        // if from is not empty also record the from in the history
        $journey['history'][] = $src;
    }
}

$journey['history'][] = [ 'url' => $current,
                          'datetime' => $now
                        ];

$journey['lastdate'] = $now;

session(['bs4_journey' => $journey]);
@endphp
@if($debug)
<p><pre>DEBUG:REFERER:
{!! json_encode($journey, JSON_PRETTY_PRINT) !!}
</pre></p>
@endif
<script type="text/javascript">
const bs4_InitJourney = () => {
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", "bs4_journey");
    const jvalue = @json($journey);
    input.setAttribute("value", JSON.stringify(jvalue) );

    document.querySelectorAll('form').forEach((form) => {
        form.insertAdjacentElement('afterbegin', input.cloneNode(true));
    });
    @if(!empty($ajaxurl))
    // could add storing this to some backend every 
    // page load via ajax here
    // TO BE ADDED IN FUTURE

    @endif
};
document.addEventListener('DOMContentLoaded', bs4_InitJourney);
</script>