<?php

namespace App\Services\Terminations\Retriever;

use App\Repositories\RetrieverRepository;
use App\Http\Responses\ReportOutputData;
use App\Repositories\CommonFilterRepository;

/**
 * RetrieverReportService - service class for Retriever Report
 */
class RetrieverReportService
{

    /**
     * Constructor for RetrieverReportService class.
     *
     * @param RetrieverRepository $repository The Retriever repository
     * @param CommonFilterRepository $commonFilterRepository The Common Filter repository
     * @param ReportOutputData $reportOutputData The Report Output Data
     */
    public function __construct(protected RetrieverRepository $repository, protected CommonFilterRepository $commonFilterRepository, protected ReportOutputData $reportOutputData)
    {
    }

    /**
     * filter function used in assets warrenty reports controller
     *
     * @return array
     */
    public function data($isDataTable = 0)
    {
        $inputData = $this->getInputData();
        $assets = $this->repository->getRetrieverReportData();
        $assets = $this->filter($assets, $inputData);
        if ($isDataTable === 1) {
            $count = $assets->count();
            $assets = $this->reportOutputData->getOutputData($assets);
            return compact('assets', 'count');
        }
        return $assets->orderBy('created_at', 'desc');
    }

    /**
     * Filer the results based on filters
     *
     * @param $assets DB Query
     * @param Array $inputData   Filter data
     *
     * @return Query
     */
    public function filter($assets, $inputData)
    {
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'user_name', $inputData['user_name']);
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'city', $inputData['city']);
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'shipment_status', $inputData['shipment_status']);
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'device_type', $inputData['device_type']);
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'outbound_tracking', $inputData['outbound_tracking']);
        $assets   = $this->commonFilterRepository->filterWithDirectFields($assets, 'return_tracking', $inputData['return_tracking']);

        $assets   = $this->repository->filterWithRequestCharger($assets, $inputData['request_charger']);

        $assets   = $this->commonFilterRepository->filterWithWhereHasRelationFields($assets, 'user', 'email', $inputData['work_email']);

        $assets   = $this->commonFilterRepository->filterWithDirectDateRange($assets, 'box_shipped_at', $inputData['box_shipped_at_from'], $inputData['box_shipped_at_to']);
        $assets   = $this->commonFilterRepository->filterWithDirectDateRange($assets, 'box_delivered_at', $inputData['box_delivered_at_from'], $inputData['box_delivered_at_to']);
        $assets   = $this->commonFilterRepository->filterWithDirectDateRange($assets, 'device_shipped_at', $inputData['device_shipped_at_from'], $inputData['device_shipped_at_to']);
        $assets   = $this->commonFilterRepository->filterWithDirectDateRange($assets, 'device_delivered_at', $inputData['device_delivered_at_from'], $inputData['device_delivered_at_to']);
        $assets   = $this->commonFilterRepository->filterWithDirectDateRange($assets, 'created_at', $inputData['created_at_from'], $inputData['created_at_to']);

        return $assets;
    }

    /**
     * Taking the input data
     * @return Array
     */
    public function getInputData()
    {
        $requestData = request()->form ?? request()->all();
        return [

            'user_name'                => $requestData['user_name'] ?? '',
            'work_email'               => $requestData['work_email'] ?? '',
            'city'                     => $requestData['city'] ?? '',
            'shipment_status'          => $requestData['shipment_status'] ?? '',
            'device_type'              => $requestData['device_type'] ?? '',
            'request_charger'          => $requestData['request_charger'] ?? '',
            'outbound_tracking'        => $requestData['outbound_tracking'] ?? '',
            'return_tracking'          => $requestData['return_tracking'] ?? '',
            'box_shipped_at_from'      => $requestData['box_shipped_at_from'] ?? '',
            'box_shipped_at_to'        => $requestData['box_shipped_at_to'] ?? '',
            'box_delivered_at_from'    => $requestData['box_delivered_at_from'] ?? '',
            'box_delivered_at_to'      => $requestData['box_delivered_at_to'] ?? '',
            'device_shipped_at_from'   => $requestData['device_shipped_at_from'] ?? '',
            'device_shipped_at_to'     => $requestData['device_shipped_at_to'] ?? '',
            'device_delivered_at_from' => $requestData['device_delivered_at_from'] ?? '',
            'device_delivered_at_to'   => $requestData['device_delivered_at_to'] ?? '',
            'created_at_from'          => $requestData['created_at_from'] ?? '',
            'created_at_to'            => $requestData['created_at_to'] ?? '',

        ];
    }

    /**
     * getAssetsData
     *
     * @param  mixed $assets
     * @param  mixed $start
     * @param  mixed $data
     * @return array
     */
    public function getReportData($assets, $start, $data, $isDataTable = 0)
    {
        $parentIndex = $start;
        $data = array();
        foreach ($assets as $assets) {
            $parentIndex++;
            $nestedData = $this->getNestedData($assets, $parentIndex, $isDataTable);
            $data[] = $nestedData;
        }
        return $data;
    }

    /**
     * getNestedData - get data for display in report table/Export
     *
     * @param  mixed $asset
     * @param  mixed $index
     * @return array
     */
    public function getNestedData($asset, $index = 0, $isDataTable = 0)
    {
        $nestedData = [];
        $nestedData['export']['User Name']             = $nestedData['report']['user_name']             = disableCSVInjection($asset->user_name);
        $nestedData['export']['Work Email']            = $nestedData['report']['work_email']            = disableCSVInjection(optional($asset->user)->email);
        $nestedData['export']['City']                  = $nestedData['report']['city']                  = disableCSVInjection($asset->city);
        $nestedData['export']['Shipment Status']       = $nestedData['report']['shipment_status']       = disableCSVInjection($asset->shipment_status);
        $nestedData['export']['Device Type']           = $nestedData['report']['device_type']           = disableCSVInjection(config('retriever.device_types.' . $asset->device_type, ''));
        $nestedData['export']['Request Charger']       = $nestedData['report']['request_charger']       = disableCSVInjection($asset->request_charger);
        $nestedData['export']['Outbound Tracking']     = $nestedData['report']['outbound_tracking']     = disableCSVInjection($asset->outbound_tracking);
        $nestedData['export']['Return Tracking']       = $nestedData['report']['return_tracking']       = disableCSVInjection($asset->return_tracking);
        $nestedData['export']['Box Shipped At']        = $nestedData['report']['box_shipped_at']        = disableCSVInjection($asset->box_shipped_at);
        $nestedData['export']['Box Delivered At']      = $nestedData['report']['box_delivered_at']      = disableCSVInjection($asset->box_delivered_at);
        $nestedData['export']['Device Shipped At']     = $nestedData['report']['device_shipped_at']     = disableCSVInjection($asset->device_shipped_at);
        $nestedData['export']['Device Delivered At']   = $nestedData['report']['device_delivered_at']   = disableCSVInjection($asset->device_delivered_at);
        $nestedData['export']['Created At']            = $nestedData['report']['created_at']            = disableCSVInjection($asset->created_at);

        if ($isDataTable === 1) {
            // Unset export indexes
            unset($nestedData['export']);
            $nestedData['report']['id']   = $index;
            $userLink = $asset->user_id ? route('users.show', $asset->user_id) : 'javascript:void(0);';
            $nestedData['report']['work_email']           = $asset->user ? "<a href=$userLink>" . optional($asset->user)->email . "</a>" : '';
            $nestedData['report']['view_asset_button']    = $this->getViewAssetsButton($asset->user_id);
            return $nestedData['report'];
        }
        unset($nestedData['report']);
        return $nestedData['export'];
    }

    /**
     * Get view user assets button
     *
     * @param int $userId
     *
     * @return string
     */
    public function getViewAssetsButton($userId)
    {
        if ($userId === null || $userId === 0) {
            return '';
        }
        return '<a href="" class="btn btn-primary btn-sm" data-action="' . url('terminations/retriever-user-assets/' . $userId) . '" data-toggle="modal" data-target="#viewAssetModal">View assets</a>';
    }

    /**
     * Return the filter auto fil data based on the user input
     *
     * @param String $search   Search text
     * @param String $type     Fild name
     */
    public function getFilterFields($search, $type)
    {
        $res = $this->repository->filterField($search, $type);

        return $res;
    }

    /**
     * Taking the user assets in Teqtivity
     *
     * @param int $userId
     *
     * @return Query
     */
    public function getUserTeqAssets($userId)
    {
        return  $this->repository->getUserTeqAssets($userId)->get();;
    }

    /**
     * returns the shipment status of an asset, with a link to view the deactivation reason if the status is "deactivated".
     *
     * @param asset
     *
     * @return the shipment status of the asset.
     */
    public function getShippingStatus($asset)
    {
        if ($asset->shipment_status != 'Deactivated') {
            return $asset->shipment_status;
        }
        return '<a href="" style="color:#0353a3" data-id="' . $asset->id . '" data-toggle="modal" data-target="#viewDeactivatedReasonModal">' . $asset->shipment_status . ' </a>';
    }

    /**
     * getdeactivated order reason from Retriver table
     *
     * @return object
     */
    public function getDeactivatedReason($retriverId)
    {
        return $retriverId ? $this->repository->getDeactivatedReason($retriverId) : '';
    }
}
