<?php

namespace App\Http\Controllers;

use App\Exports\EmployeeTemplateExport;
use App\Imports\EmployeeBulkImport;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Throwable;

class EmployeeImportController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('employees/import', ['result' => null]);
    }

    public function template(): BinaryFileResponse
    {
        return Excel::download(new EmployeeTemplateExport, 'employee-import-template.xlsx');
    }

    public function store(Request $request): Response|RedirectResponse
    {
        $request->validate([
            'file' => ['required', 'file', 'mimes:xlsx,xls,csv,txt', 'max:10240'],
        ]);

        $import = new EmployeeBulkImport;

        try {
            Excel::import($import, $request->file('file'));
        } catch (Throwable $e) {
            return back()->with('error', 'Could not read the file: '.$e->getMessage());
        }

        return Inertia::render('employees/import', [
            'result' => [
                'created' => $import->created,
                'updated' => $import->updated,
                'skipped' => $import->skipped,
                'errors' => array_slice($import->errors, 0, 200),
                'error_count' => count($import->errors),
            ],
        ]);
    }
}
