<?php

namespace App\Http\Controllers\Web;

use Inertia\Inertia;
use App\Models\Group;
use App\Models\Export;
use App\Models\Category;
use App\Imports\ExportsImport;
use MeiliSearch\Endpoints\Indexes;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Resources\ExportResource;

class ExportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (blank(request('group'))) {
            request()->merge([
                'group' => optional(Group::whereType('export')->where('is_default', true)->first())->id
            ]);
        }

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

        $exports = Export::query()
            ->where('group_id', request('group'))
            ->where('locale', app()->getLocale())
            ->when(request('title'), fn ($q) => $q->whereIn('id', $searchIds))
            ->when(request('category'), fn ($q) => $q->where('category_id', request('category')))
            ->when(request('unit'), fn ($q) => $q->where('unit', request('unit')))
            ->when(request('currency'), fn ($q) => $q->where('currency', request('currency')))
            ->when(request('payment'), fn ($q) => $q->where('payment', request('payment')))
            ->when(request('send'), fn ($q) => $q->where('send', request('send')))
            ->when(request('type'), fn ($q) => $q->where('type', request('type')));

        $ids = $exports->pluck('id');
        $categories = Category::query()
            ->when(filled($ids), function ($q) use ($ids) {
                $q->whereHas('exports', fn ($q) => $q->whereIn('id', $ids));
            })
            ->get();
        $groups = Group::whereType('export')->get();

        $filters = array_filter(request()->all([
            'title',
            'category',
            'group',
            'unit',
            'currency',
            'payment',
            'send',
            'type',
        ]));

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

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

        return Inertia::render('Exports', [
            'text' => settings('text')[app()->getLocale()],
            'filters' => $filters,
            'exports' => ExportResource::collection($exports->simplePaginate(50)),
            'categories' => fn () => $categories,
            'groups' => fn () => $groups,
            // 'countries' => fn () => Export::countries($ids),
            'units' => fn () => Export::units($ids),
            'payments' => fn () => Export::payments($ids),
            'sends' => fn () => Export::sends($ids),
            'currencies' => fn () => Export::currencies($ids),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function import()
    {
        request()->validate([
            'group' => ['exists:groups,id'],
            'file' => ['required', 'mimes:xlsx'],
        ]);

        if (!$group = Group::find(request('group'))) {
            $group = Group::create([
                'title' => 'New group',
                'type' => 'export',
                'is_default' => true
            ]);
        }

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

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

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

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

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

    public function status()
    {
        $id = session('import');

        return response([
            'started' => filled(cache("start_date_$id")),
            'finished' => filled(cache("end_date_$id")),
            'current_row' => (int) cache("current_row_$id"),
            'total_rows' => (int) cache("total_rows_$id"),
        ]);
    }
}
