<?php

namespace Digtective\Controllers;

use Digtective\Base\Route;
use Ramsey\Uuid\Uuid;
use WP_REST_Request;

class SessionController{
    private const CONNECTION_ROUTE = "session";

    public function setSession(WP_REST_Request $request){
        if(session_status() == PHP_SESSION_NONE){
            session_start();
        }

        if(!isset($_SESSION['originalReferrer']) && $request['referrer']){
            $_SESSION['originalReferrer'] = sanitize_url($request['referrer']);
            $_SESSION['referrer'] = sanitize_url($request['referrer']);
        }

        if(!isset($_SESSION['sessionId'])){
            $_SESSION['sessionId'] = Uuid::uuid4()->toString();
        }

        if(!isset($_SESSION['adCode']) && $request['dig']){
            $_SESSION['adCode'] = sanitize_text_field($request['dig']);
        }

        if(!isset($_SESSION['keyword']) && $request['kwd']){
            $_SESSION['keyword'] = sanitize_text_field($request['kwd']);
        }

        if(!isset($_SESSION['gclid']) && $request['gclid']){
            $_SESSION['gclid'] = sanitize_text_field($request['gclid']);
        }

        if(!isset($_SESSION['gbraid']) && $request['gbraid']){
            $_SESSION['gbraid'] = sanitize_text_field($request['gbraid']);
        }

        if(!isset($_SESSION['wbraid']) && $request['wbraid']){
            $_SESSION['wbraid'] = sanitize_text_field($request['wbraid']);
        }

        if(!isset($_SESSION['fbclid']) && $request['fbclid']){
            $_SESSION['fbclid'] = sanitize_text_field($request['fbclid']);
        }

        $_SESSION['path'] = $request['path'];
        $_SESSION['referrer'] = sanitize_url($request['referrer']) ?? null;

        $_SESSION['browser'] = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : "";

        wp_send_json([
            'sessionId'        => sanitize_text_field($_SESSION['sessionId'] ?? ""),
            'dig'              => sanitize_text_field($_SESSION['adCode'] ?? ""),
            'gclid'            => sanitize_text_field($_SESSION['gclid'] ?? ""),
            'gbraid'            => sanitize_text_field($_SESSION['gbraid'] ?? ""),
            'wbraid'            => sanitize_text_field($_SESSION['wbraid'] ?? ""),
            'fbclid'            => sanitize_text_field($_SESSION['fbclid'] ?? ""),
            'referrer'         => sanitize_text_field($_SESSION['referrer'] ?? ""),
            'keyword'         => sanitize_text_field($_SESSION['kwd'] ?? ""),
            'originalReferrer' => sanitize_text_field($_SESSION['originalReferrer'] ?? ""),
        ]);
    }

    public function register(){
        add_action("rest_api_init", function(){
            register_rest_route(
                Route::BASE_PATH, self::CONNECTION_ROUTE, [
                    "methods"  => "POST",
                    "callback" => [$this, "setSession"],
                ]
            );
        });
    }
}
