<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Http\Controllers\Controller;
use App\Services\BulkUpload\BulkCreateLinkMobileService;
use App\Services\Integrations\Tickets\TicketManagementService;
use Illuminate\Http\Request;
use App\Http\Requests\CsvFileUploadRequest;
use App\Http\Traits\FileSanitizationTrait;

class BulkCreateLinkMobileController extends Controller
{
    use FileSanitizationTrait;

    /**
     * Initialize the controller with the BulkCreateLinkMobileService and TicketManagementService.
     *
     * @param BulkCreateLinkMobileService $bulkCreateLinkMobile The service for bulk creating link mobile assets.
     * @param TicketManagementService     $ticketManagementService The service for managing ITSM tickets.
     */
    public function __construct(protected BulkCreateLinkMobileService $bulkCreateLinkMobile, protected TicketManagementService $ticketManagementService) {}

    public function index()
    {
        session(['asset_count' => 0]);

        return view('settings.bulk-create-link-mobile');
    }

    /**
     * Handle the upload of a CSV file for creating asset links.
     *
     * This method processes the uploaded CSV file, stores it in the designated directory,
     * and delegates further processing to the bulkCreateLinkMobile service.
     *
     * @param \App\Http\Requests\CsvFileUploadRequest $request
     *        The validated request containing the uploaded CSV file.
     *
     * @return mixed
     *         The response from the bulkCreateLinkMobile 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 = 'create-link-asset-items-'  . date("m-d-y") . '-' . time() . '.' . $extension;

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

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

    /**
     * Create and link assets.
     *
     * @return view
     */
    public function store(Request $request)
    {
        $errors = [];
        $updatedCount = 0;
        $ticketNo = '';
        $filePath = '';
        $fileName = '';
        $basePath = storage_path('app/public/asset_bulk_create_link');

        if ($request->count == 0) {
            return redirect()->route('bulk-create-link.index')->with('error', 'Assets cannot be created and linked.');
        }

        for ($i = 1; $i <= $request->count; $i++) {
            if (!$request->has('asset_id' . $i)) {
                continue; // Row was deleted before submitting
            }

            $requestData = json_decode($request->input('asset_id' . $i), true);

            // Set ticket, filePath, and fileName from the first row
            $ticketNo = $ticketNo ?: ($requestData['ticket_no'] ?? null);
            $filePath = $filePath ?: $this->sanitizeFilePath($requestData['filePath'], $basePath);
            $fileName = $fileName ?: $this->sanitizeFileName($requestData['fileName']);

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

            if ($updateResponse === false) {
                $errors[] = $requestData['serial_no'] ?? ''; // Add serial_no if available
                continue;
            }

            $updatedCount++;
        }

        $this->bulkCreateLinkMobile->attachFiletoTicket($ticketNo, $filePath, $fileName);

        if (empty($errors)) {
            return redirect()->route('bulk-create-link.index')->with('message', 'Assets created and linked successfully.');
        }

        if ($request->count != count($errors)) {
            return redirect()->route('bulk-create-link.index')
                ->with([
                    'message' => "Total {$updatedCount} assets created and linked successfully.",
                    'error' => 'Assets ' . implode(', ', $errors) . ' could not be created and linked.',
                ]);
        }

        return redirect()->route('bulk-create-link.index')->with('error', 'Assets cannot be created and linked.');
    }
}
