<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Http\Controllers\Controller;
use App\Http\Requests\Eol\ConsolidatedCertificateRequest;
use App\Services\BulkUpload\BulkCertificatesUpload;

class BulkCertificatesUploadController extends Controller
{
    protected $updated;
    protected $notFound;
    protected $duplicate;
    protected $certificatePath;

    public function __construct(protected BulkCertificatesUpload $bulkCertificatesUpload)
    {
        $this->updated = 0;
        $this->notFound = '';
        $this->duplicate = '';
        $this->certificatePath = '';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        session(['asset_count' => 0]);

        return view('settings.bulk-certificates-upload');
    }

    /**
     * Handle the upload of consolidated certificate files and import asset data.
     *
     * This method processes the uploaded certificate files, stores them in the appropriate folder, 
     * imports asset data from the CSV, validates the data, and stores it if no errors are found.
     *
     * @param \App\Http\Requests\Eol\ConsolidatedCertificateRequest $request
     *        The validated request containing the uploaded files.
     *
     * @return \Illuminate\Http\JsonResponse
     *         A JSON response containing the result of the upload process, including errors if any.
     */
    public function upload(ConsolidatedCertificateRequest $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $view = [];
        // Get the uploaded file from the request
        $file = $request->file('file');
        $certificateFile = $request->file('certificate');

        if ($file && $certificateFile) {

            // Normalize file name to prevent directory traversal
            $sanitizedCertificateName = sanitizeFilename($certificateFile->getClientOriginalName());

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

            $folder             = $this->bulkCertificatesUpload->createFolder();
            $path               = $file->storeAs($folder, 'certificates-upload-items-' . date("m-d-y-H-i-s") . '.' . $extension);

            $certificatePath    = $certificateFile->storeAs($folder, $sanitizedCertificateName);
            $this->certificatePath = str_replace("public/", "", $certificatePath);

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

            return $this->bulkCertificatesUpload->getViewData($path, $certificatePath);
        }

        return response()->json($view);
    }

    /**
     * Create json string with certificate file name for saving to DB
     *
     * @param App\Models\Asset $asset
     * @param String $certificate    Certificate file name
     */
    public function jsonFormattedCertificate($asset, $certificate)
    {
        if ($asset->ewaste_certificate) {
            isJSON($asset->ewaste_certificate) ? $existCertificates =  json_decode($asset->ewaste_certificate, true) : $existCertificates[0] = $asset->ewaste_certificate;
            $index = is_countable($existCertificates) ? count($existCertificates) : 0;

            if (!in_array($certificate, $existCertificates))
                $existCertificates[$index + 1] = $certificate;
        } else {
            $existCertificates[0] = $certificate;
        }

        return json_encode($existCertificates);
    }
}
