<?php

namespace App\Http\Middleware;

use App\Helpers\ClientHelper;
use App\Models\Statistic;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class StatisticsMiddleware
{
    use ClientHelper;

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            // record statistics
            if ($request->getMethod() == "GET") {
                $this->statistics();
            }

            // delete all rows older than 30 days
            Statistic::whereDate('created_at', '<=', now()->subDay(30))->delete();
        } catch (Exception $e) {
            //
        }

        return $next($request);
    }

    /**
     * record statistics
     */
    public function statistics()
    {
        // reject bots
        if ($this->isBot(request()->userAgent())) {
            return;
        }

        /** @var App\Models\User $user */
        $user = auth()->user();

        // skip admin panel and auth and system Routes
        if (
            str_starts_with(request()->getPathInfo(), '/login')
            || str_starts_with(request()->getPathInfo(), '/auth')
            || str_starts_with(request()->getPathInfo(), '/theme')
            || str_starts_with(request()->getPathInfo(), '/locale')
            || str_starts_with(request()->getPathInfo(), '/error')
            || str_starts_with(request()->getPathInfo(), '/search')
            || str_starts_with(request()->userAgent(), 'Symfony')
            || str_starts_with(request()->getPathInfo(), '/product/question/answer/')
            || str_starts_with(request()->getPathInfo(), '/compare/add/')
            || str_starts_with(request()->getPathInfo(), '/compare/delete/')
            || str_starts_with(request()->getPathInfo(), '/form/answer/')
            || str_starts_with(request()->getPathInfo(), '/newsletter/subscribe')
            || str_starts_with(request()->getPathInfo(), '/article/vote/')
            || str_starts_with(request()->getPathInfo(), '/article/comment/')

            || str_ends_with(request()->getPathInfo(), '/add-to-cart')
            || str_ends_with(request()->getPathInfo(), '/favorites')
            || str_ends_with(request()->getPathInfo(), '/notification')
            || str_ends_with(request()->getPathInfo(), '/comment/add')
        ) {
            return;
        }

        // data
        $platform = str_starts_with(request()->getPathInfo(), '/blog') ? 'blog' : 'shop';
        $service = null;
        if (request()->getPathInfo() == '/') {
            $service = 'index';
        } else if (request()->getPathInfo() == '/blog') {
            $service = 'blog_index';
        } else if (str_starts_with(request()->getPathInfo(), '/product/')) {
            $service = 'product';
        } else if (str_starts_with(request()->getPathInfo(), '/products')) {
            $service = 'products';
        } else if (str_starts_with(request()->getPathInfo(), '/blog/article/')) {
            $service = 'article';
        } else if (str_starts_with(request()->getPathInfo(), '/blog/articles')) {
            $service = 'articles';
        } else if (str_starts_with(request()->getPathInfo(), '/page')) {
            $service = 'page';
        } else if (str_starts_with(request()->getPathInfo(), '/form')) {
            $service = 'form';
        } else if (str_starts_with(request()->getPathInfo(), '/brand')) {
            $service = 'brand';
        } else if (str_starts_with(request()->getPathInfo(), '/store')) {
            $service = 'store';
        } else if (str_starts_with(request()->getPathInfo(), '/compare')) {
            $service = 'compare';
        } else if (str_starts_with(request()->getPathInfo(), '/cart')) {
            $service = 'cart';
        } else if (str_starts_with(request()->getPathInfo(), '/user')) {
            $service = 'user';
        } else if (str_starts_with(request()->getPathInfo(), '/seller')) {
            $service = 'seller';
        } else if (str_starts_with(request()->getPathInfo(), '/admin')) {
            $service = 'admin';
        }

        // record
        Statistic::create([
            'user_id' => $user != null ? $user->id : null,
            'platform' => $platform,
            'service' => $service,
            'ip' => $this->getUserIp(),
            'url' => request()->getPathInfo(),
            'agent' => request()->userAgent(),
            'os' => $this->getDeviceMeta(request())['platform'],
            'browser' => $this->getDeviceMeta(request())['browser'],
        ]);
    }
}
