<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Services\BulkUpload\SpecialBulkHoldService;
use App\Services\BulkUpload\BulkHoldService;
use App\Http\Controllers\Controller;
use App\Http\Requests\SpecialUpload;
use Illuminate\Http\Request;
use App\Http\Requests\CsvFileUploadRequest;
use App\Http\Traits\FileSanitizationTrait;
use Illuminate\Support\Facades\Storage;

class BulkHoldController extends Controller
{
    use FileSanitizationTrait;

    /**
     * Initialize the controller
     *
     * @param BulkHoldService $bulkStatusUpdate
     * @param SpecialBulkHoldService $specialBulkStatusUpdate
     */
    public function __construct(protected BulkHoldService $bulkStatusUpdate, protected SpecialBulkHoldService $specialBulkStatusUpdate) {}

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

        return view('settings.bulk-hold');
    }

    /**
     * Handle the upload of a CSV file for bulk hold asset updates.
     *
     * This method processes the uploaded file, stores it in a specific directory,
     * and delegates the file processing to the bulkStatusUpdate service.
     *
     * @param \App\Http\Requests\CsvFileUploadRequest $request
     *        The validated request containing the uploaded CSV file.
     *
     * @return mixed
     *         The response from the bulkStatusUpdate 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 = 'hold-asset-items-' . date("m-d-y") . '-' . time() . '.' . $extension;
        $path = $file->storeAs('public/asset_bulk_hold', $fileName);

        return $this->bulkStatusUpdate->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-hold.index'))->with('error', 'Assets cannot be updated.');
        }

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

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

            if (!$request->has('asset_id' . $i)) {
                continue; //row was deleted before submitting
            }

            $updateResponse = $this->bulkStatusUpdate->saveData($request->all(), $i);
            if ($updateResponse === false) {
                $errors[] = request('serial_no' . $i);
                continue;
            }

            $updatedCount++;
        }

        $this->bulkStatusUpdate->attachFiletoTicket(request('ticket_no1'), $filePath, $fileName);
        if (empty($errors)) {

            return redirect(route('bulk-hold.index'))->with('message', 'Assets updated successfully.');
        }

        if ($request->count != count($errors)) {
            return redirect(route('bulk-hold.index'))
                ->with([
                    'message' => "Total {$updatedCount} assets updated successfully.",
                    'error' => 'Assets ' . implode(', ', $errors) . ' cannot be updated.',
                ]);
        }

        return redirect(route('bulk-hold.index'))->with('error', 'Assets cannot be updated.');
    }

    /**
     * Handle the upload of a CSV file for bulk hold asset updates.
     *
     * This method processes the uploaded file, stores it in a specific directory,
     * and delegates the file processing to the specialBulkStatusUpdate service.
     *
     * @param \App\Http\Requests\SpecialUpload $request
     *        The validated request containing the uploaded CSV file.
     *
     * @return \Illuminate\Http\RedirectResponse
     *         The response from the specialBulkStatusUpdate service after processing the file.
     */
    public function specialUpload(SpecialUpload $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $file   = $request->file('bulk_upload_asset');

        $extension  = strtolower($file->getClientOriginalExtension());
        $fileName   = 'hold-asset-items-' . date("m-d-y") . '-' . time() . '.' . $extension;
        $path       = $file->storeAs('public/asset_bulk_hold', $fileName);
        $path       = storage_path('app/' . $path);

        $message = 'Bulk status change successful';
        $errors = $this->specialBulkStatusUpdate->importAssetData($path, $fileName);

        if (isset($errors['validationErrors']) && !empty($errors['validationErrors'])) {
            Storage::put('public/asset_bulk_hold/assign-error-' . date("m-d-y") . '-' . time() . '.txt', json_encode($errors['validationErrors']));

            return redirect(route('bulk-hold.index'))->with(['error' => implode(",\n", $errors['validationErrors'])]);
        }

        if ($errors && !isset($errors['validationErrors'])) {
            Storage::put('public/asset_bulk_hold/assign-error-' . date("m-d-y") . '-' . time() . '.txt', json_encode($errors));
            $message = 'Bulk Status completed with errors';

            return redirect(route('bulk-hold.index'))->with(['message' => $message, 'errors' => $errors]);
        }

        return redirect(route('bulk-hold.index'))->with(['message' => $message]);
    }
}
