<?php

namespace App\Services\BulkUpload;

use Illuminate\Support\Facades\Auth;

class SpecialBulkStatusUpdate extends BulkStatusUpdate
{

    /**
     * Imports asset data from a given file path.
     *
     * @param string      $path     The path to the file containing asset data.
     * @param string|null $fileName The optional name of the file.
     *
     * @return array An array of error data encountered during import.
     */
    public function importAssetData(string $path, $fileName = null)
    {
        $count = 1;
        $data = $this->getItems($path);

        $items = $data['csvData'];
        $errorData = [];
        $ticketNo = '';

        if (!empty($items)) {
            foreach ($items as $item) {
                if (!count($item)) {
                    continue;
                }

                $csvData = $this->generateCSVData($item, $count++);
                $assetData = $csvData['assetData'];
                $validationError = $this->csvValidator($assetData, $count);

                if ($validationError) {
                    $errorData[] = $validationError->toArray();

                    continue;
                }

                if (!$this->updateStatusService->updateStatus($assetData, 'special_bulk_upload')) {
                    $errorData[] = 'Line no ' . ($count) . ' : The asset with serial # : ' . $assetData['serial_no'] . ' cannot be updated to ' . $this->getStatus($assetData['asset_status_id'])->name . '.';
                }

                $ticketNo = $ticketNo ? $ticketNo : $assetData['ticket_no'];
            }

            $this->attachFiletoTicket($ticketNo, $path, $fileName);
        }

        return $errorData;
    }

    /**
     * After bulk upload attach the uploaded file to the ticket as comment
     * @param mixed $ticketid
     * @param mixed $filePath
     * @param mixed $fileName
     *
     * @return [type]
     */
    public function attachFiletoTicket($ticketid, $filePath, $fileName)
    {
        if (!$ticketid || !$filePath || !$fileName) {
            return false;
        }

        $this->ticketManagementService->attachActionHistorytoTicket($ticketid, 'Bulk status update (special)', Auth::user()->id, $filePath, $fileName);

        return true;
    }
}
