<?php

namespace App\Http\Controllers\Assets\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\BulkUpload\BulkTechnicalSpecsService;
use App\Http\Requests\CsvFileUploadRequest;
use App\Http\Traits\FileSanitizationTrait;

class BulkTechnicalSpecsController extends Controller
{
    use FileSanitizationTrait;

    public function __construct(protected BulkTechnicalSpecsService $service) {}

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

    /**
     * Handle the upload of a CSV file for bulk technical specifications.
     *
     * This method processes the uploaded file, stores it in the designated directory,
     * and delegates further processing to the relevant service.
     *
     * @param \App\Http\Requests\CsvFileUploadRequest $request
     *        The validated request containing the uploaded CSV file.
     *
     * @return mixed
     *         The response from the 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());

        $fileName = 'bulk-technical-specs-' . date("m-d-y") . '-' . time() . '.' . $extension;

        $path = $file->storeAs('public/hardware_specs', $fileName);

        return $this->service->getViewData(storage_path('app/' . $path), $fileName);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $errors = [];
        $updatedCount = 0;

        if ($request->count == 0) {
            return redirect()->route('bulk-technical-specs.index')->with('error', 'Technical specs updated cannot be updated.');
        }

        $basePath = storage_path('app/public/hardware_specs');
        $filePath = $this->sanitizeFilePath($request->filePath, $basePath);
        $fileName = $this->sanitizeFileName($request->fileName);

        for ($i = 1; $i <= $request->count; $i++) {

            $updateResponse = $this->service->saveData($request->all(), $i);

            if ($updateResponse === false) {
                $errors[] = $request->input('new_technical_specs' . $i) ?? ''; // Add serial_no if available
                continue;
            }

            $updatedCount++;
        }

        $this->service->attachFiletoTicket($request->input('ticket_no1'), $filePath, $fileName);

        if (empty($errors)) {
            return redirect()->route('bulk-technical-specs.index')->with('message', 'Technical specs updated successfully.');
        }

        if ($request->count != count($errors)) {
            return redirect()->route('bulk-technical-specs.index')
                ->with([
                    'message' => "Total {$updatedCount} Technical specs updated successfully.",
                    'error' => 'Technical specs ' . implode(', ', $errors) . ' could not be updated.',
                ]);
        }

        return redirect()->route('bulk-technical-specs.index')->with('error', 'Technical specs cannot be updated.');
    }
}
