<?php

namespace App\Exports;

use App\Models\User;
use App\Lib\UserNetwork;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class NetworkExport implements FromCollection, WithHeadings, WithMapping
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        // return User::all();
        $user = auth()->user();

        $cacheKey = 'user:' . $user->id . ':network';

        if ($user->is_network_updated || !Cache::has($cacheKey)) {
            $networkData = app(UserNetwork::class)->getUsersLevelWise($user);
            Cache::put($cacheKey, $networkData, 120);
        } else {
            $networkData = Cache::get($cacheKey);
        }

        $networkData = $networkData->filter(function ($item) {
            $matchesSearch = true;
            $matchesDistance = true;

            // Search filter
            if (request()->search) {
                $searchTerm = request()->search;
                $matchesSearch = stripos($item->firstname, $searchTerm) !== false || stripos($item->lastname, $searchTerm) !== false || stripos($item->email, $searchTerm) !== false || stripos($item->username, $searchTerm) !== false || stripos($item->mobile, $searchTerm) !== false;
            }

            // Distance filter
            if (request()->distance) {
                $matchesDistance = $item->distance == request()->distance;
            }

            return $matchesSearch && $matchesDistance;
        });

        return $networkData;
    }

    public function map($user): array
    {
        return [
            $user->system_id,
            $user->username,
            $user->email,
            $user->mobile,
            $user->position,
            $user->rank,
            $user->network_size,
            $user->active_network_size,
            $user->network_activated_at ? $user->network_activated_at->format('d-M-Y') : 'N/A' ,
            $user->distance,
        ];
    }

    public function headings(): array
    {
        return [
            'User Id',
            'User Name',
            'Email',
            'Mobile',
            'Position',
            'Rank',
            'Size Of network',
            'Active Network Size',
            'Network Activated',
            'Level',
        ];
    }
}
