<?php


namespace App\Http\Controllers\Dropdown;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\Controller;
use App\Models\Export;

class DropdownExportController extends Controller
{
    public function export(Request $request)
    {
        $params = $request->all();
        if ($request->has('defaultFilter')) {
            $params = array_merge($params, $request->input('defaultFilter'));
        }

        $data = User::all()->map(function ($user) {
            return implode(',', [$user->id, $user->name]) . "\n";
        })->implode('');

        $filename = 'export_' . now()->format('mmddyyyy') . '.csv';
        Storage::put("exports/{$filename}", $data);

        Export::create(['filename' => $filename, 'exported_at' => now()]);

        return Response::download(storage_path("app/exports/{$filename}"))->deleteFileAfterSend(true);
    }
}