<?php

namespace App\Http\Controllers\Web;

use Inertia\Inertia;
use App\Models\Group;
use App\Models\Import;
use App\Imports\ImportsImport;
use MeiliSearch\Endpoints\Indexes;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Resources\ImportResource;
use App\Models\BirzhaUser;

class ImportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        try {
            $birzha_user = null;
            
            // For Admin's session
            if (!\Auth::check()) {

                $userId = preg_split("/[\s\[\]\",]+/", \Cookie::get('user_auth'))[1];
                // $userId = 64;

                $birzha_user = BirzhaUser::find($userId);
            }
        } catch (\Throwable $th) {
            \Log::info($th);
            return Inertia::location(env('PARENT_APP'));
        }

        if (blank(request('group'))) {
            request()->merge([
                'group' => optional(Group::whereType('import')->where('is_default', true)->first())->id
            ]);
        }

        $searchIds = filled(request('title'))
            ? Import::search(request('title'), function (Indexes $meilisearch, $query, $options) {
                $options['filters'] = 'group=' . request('group');
                $options['limit'] = 500;
                return $meilisearch->search($query, $options);
            })->keys()
            : [];

        $filters = array_filter(request()->all([
            'title',
            'country',
            'currency',
            'unit',
            'group',
        ]));

        if (array_key_exists('group', $filters)) {
            $filters['group'] = intval($filters['group']);
        }

        $groups = Group::whereType('import')->get();

        $imports = Import::query()
            ->where('group_id', request('group'))
            ->where('locale', app()->getLocale())
            ->when(request('title'), fn ($q) => $q->whereIn('id', $searchIds))
            ->when(request('country'), fn ($q) => $q->where('country', request('country')))
            ->when(request('unit'), fn ($q) => $q->where('unit', request('unit')))
            ->when(request('currency'), fn ($q) => $q->where('currency', request('currency')))
            ->when(request('registered_at'), fn ($q) => $q->whereDate('registered_at', request('registered_at')));

        $ids = $imports->pluck('id');

        return Inertia::render('Imports', [
            'imports' => ImportResource::collection($imports->simplePaginate(50)),
            'filters' => $filters,
            'groups' => $groups,
            'countries' => fn () => Import::countries($ids),
            'units' => fn () => Import::units($ids),
            'currencies' => fn () => Import::currencies($ids),
            'birzha_user' => fn () => $birzha_user
        ]);
    }

    /**
     * Import
     */
    public function import()
    {
        request()->validate([
            'file' => ['required', 'mimes:xlsx'],
        ]);

        if (!$group = Group::whereType('import')->where('is_default', true)->first()) {
            $group = Group::create([
                'title' => 'New group',
                'type' => 'import',
                'is_default' => true
            ]);
        }

        $group->imports()->whereLocale(app()->getLocale())->delete();

        try {
            $id = now()->unix();
            session(['import' => $id]);

            $file = request()->file('file')->storeAs('uploads', $filename = $group->filename);
            $group->update(['file' => [app()->getLocale() => $filename]]);

            Excel::queueImport(new ImportsImport($id, $group, app()->getLocale()), $file);
        } catch (\Throwable $th) {
            info('error here');
            info($th->getMessage());
        }

        return redirect()->route('imports');
    }
}
