<?php

namespace Clevercherry\Backslash4\Traits;

use Illuminate\Support\Str;

trait journeyTracker
{
    // -- JourneyTracker -- for <x-backslash4::bs-header.journey-tracker /> ---

    /**
     * Gets the Journey Tracker array $journey for the header component
     * <x-backslash4::bs-header.journey-tracker />
     * fetching the array from a session variable and saving the updated
     * version back to the session
     * 
     * The function is here in the User model so that it could be overidden
     * per application
     * 
     * The Javascript in the component then injects the $journey array into 
     * any forms on the page so that any form submission can record the 
     * journey data
     * 
     * return array    
     */
    public static function getUpdatedJourney() : array
    {
        if( request()->bs4journey === 'forget' ) {
            // allowing to reset the journey record without 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', 'doubleclick']) ) {
                    if ( Str::contains($from_hostname, ['ad', 'syndication']) ) {
                        $src['utm_source'] = 'Google Ads';
                    } else {
                        $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]);
        
        return $journey;
    }
}