<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\CsvFileUploadRequest;
use App\Services\User\UserBulkUpload;

class UserUploadController extends Controller
{
    public function __construct(protected UserBulkUpload $userBulkUpload) {}

    /**
     * Handle the upload of a CSV file for bulk user creation or update.
     *
     * This method processes the uploaded file, stores it in a specific directory,
     * and delegates the file processing to the userBulkUpload service.
     *
     * @param \App\Http\Requests\CsvFileUploadRequest $request
     *        The validated request containing the uploaded CSV file.
     *
     * @return mixed
     *         The response from the userBulkUpload service after processing the file.
     */
    public function upload(CsvFileUploadRequest $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        // Get the uploaded file from the request
        $file = $request->file('file');

        // Get the file extension in lowercase
        $extension = strtolower($file->getClientOriginalExtension());

        $path = 'users-' . date("m-d-y") . '-' . time() . '.' . $extension;
        $path = $file->storeAs('public/user_bulk_upload', $path);

        $path = storage_path('app/' . $path);

        $csvData = $this->userBulkUpload->importAssetData($path);

        if (!empty($csvData['error'])) {
            $errors = $csvData['error'];
            $view = [];
            $view['errors'] = view('assets.partials.upload-csv-errors', compact('errors'))->render();
            return response()->json($view);
        }

        $count = count($csvData);

        $errors = $this->userBulkUpload->validateFields($csvData);
        $errorsView = view('users.partials.upload-errors', compact('errors'))->render();
        if (!empty(array_filter($errors))) {
            $csvData = [];
        }
        $dataView = view('users.partials.upload-users', compact('csvData'))->render();
        return response()->json([
            'count' => $count,
            'errors' => $errorsView,
            'data' => $dataView
        ]);
    }
}
