<?php

namespace App\Services\BulkUpload;

use Facades\App\Services\AssetHistory as AssetHistoryService;
use App\Events\BulkUpdates;
use Illuminate\Support\Facades\Auth;
use App\Models\Location;
use App\Models\Asset;
use App\Rules\StorageLocation;
use App\Services\Integrations\Tickets\TicketManagementService;
use Illuminate\Support\Facades\Validator;

class SpecialBulkReturnService extends SpecialBulkAbstract
{
    protected $ticketManagementService;

    public function __construct(TicketManagementService $ticketManagementService)
    {
        $this->ticketManagementService = $ticketManagementService;
    }
    /**
     * Get Headers of CSV
     * @return array
     */
    public function getHeaderMap()
    {
        return Config('bulk-upload.returnData');
    }

    /**
     * Generate useful data from csv data
     * @param  array $item
     * @return mixed can be bool or array
     */
    public function generateCSVData(array $item)
    {
        if (empty($item)) {
            return false;
        }

        $assetData    = [];
        $errorData    = '';
        foreach ($this->getHeaderMap() as $dbField => $fileHeader) {
            $result = $this->getRelationalValues($item, $dbField, $fileHeader);
            if ($result == false) {
                if ($dbField == "location_id") {
                    $errorData .= 'Location ' . $item[$fileHeader] . ' do not exist.' . "\r\n";
                }
                if ($dbField == "user_id") {
                    $errorData .= 'User with email ' . trim($item[$fileHeader]) . ' do not exist.' . "\r\n";
                }
            }

            if ($result !== false) {
                $item[$fileHeader] = $result;
            }

            $assetData[$dbField] = !empty($item[$fileHeader]) ? $item[$fileHeader] : null;
            if ($dbField == "serial_no") {
                if (!empty($item[$fileHeader])) {
                    $asset = Asset::where('serial_no', trim($item[$fileHeader]))->first();
                    if ($asset) {
                        $assetData['id'] = $asset->id;
                    }

                    if (!$asset) {
                        $errorData .= 'Asset with serial # ' . $item[$fileHeader] . ' do not exist.' . "\r\n";
                    }
                }
            }
        }
        return compact('assetData', 'errorData');
    }

    public function saveAssetHistory(Asset $asset, array $assetData)
    {
        $comments = null;
        $description = __('history.Returned', [
            'assetname' => $asset->serial_no,
            'assetid' => $asset->id,
            'oldroomname' => optional($asset->location)->room_name,
            'newroomname' => optional(Location::findOrFail($assetData['location_id']))->room_name,
            'commenttext' => $comments,
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'asset_id' => $asset->id,
            'action' => 'returned',
            'old_location_id' => optional($asset->location)->id,
            'new_location_id' => $assetData['location_id'],
            'comments' => $comments,
            'old_value' => optional($asset->location)->room_name,
            'new_value' => optional(Location::findOrFail($assetData['location_id']))->room_name,
            'description' => $description,
            'ticket_no' => $assetData['ticket_no']
        ];

        $assetHistory = $this->getAdditionalHistoryData($assetHistory, $assetData, $asset);
        event(new BulkUpdates($assetHistory));
    }

    /**
     * Get Status Slug
     * @return string
     */
    public function getStatusSlug()
    {
        return "";
    }

    /**
     * Get Headers of CSV
     * @return array
     */
    public function getData(Asset $asset)
    {
        return "";
    }
    /**
     * Get Default Ticket #
     * @return String
     */
    public function getDefaultTicket()
    {
        return Config('tickets.bulk_return');
    }

    /**
     * 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 return (special)', Auth::user()->id, $filePath, $fileName);
        return true;
    }
}
