<?php

namespace App\Services\Security\Crowdstrike\Reports;

use App\Repositories\Security\Crowdstrike\CrowdstrikeReportRepository;
use Illuminate\Support\Str;

class SensorDetectionService extends AbstractCrowdstrikeService
{
    protected $repository;

    /**
     * Constructs a new instance of the class.
     *
     * @param CrowdstrikeReportRepository $repository The repository to use for retrieving Crowdstrike reports.
     */
    public function __construct(CrowdstrikeReportRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * Retrieves sensor detection data.
     *
     * @return array Returns an array containing the count of assets and the assets themselves.
     */
    public function data()
    {
        $assets = $this->repository->sensorDetectionData();
        $inputData = request()->form;
        $assets = $this->filterResults($assets, $inputData);
        $count = $assets->count();
        $assets = $this->getOutputData($assets, 'id', 'DESC');

        return compact('count', 'assets');
    }

    /**
     * Filters the main query based on the input data for sensor detection.
     *
     * @param mixed $assets The main query to be filtered.
     * @param array $inputData The input data used for filtering.
     * @return mixed The filtered main query.
     */
    public function filterResults($assets, $inputData)
    {
        $assetFields = ['asset_tag', 'serial_no', 'asset_status_id', 'make_and_model_id', 'technical_spec_id', 'user_id', 'location_id'];
        $assetUserFields = ['city'];
        $assetCustomQueryFields = ['crowdstrike_id'];

        foreach ($inputData as $filterKey => $filterValue) {

            if ($filterValue != '') {

                if (in_array($filterKey, $assetFields)) {
                    $assets = $this->repository->filterWithAssetFields($assets, $filterKey, $filterValue);
                }

                if (in_array($filterKey, $assetUserFields)) {
                    $assets  = $this->repository->filterWithAssetUserFields($assets, $filterKey, $filterValue);
                }

                if (in_array($filterKey, $assetCustomQueryFields)) {
                    $assets  = $this->repository->filterWithAssetCustomFields($assets, $filterKey, $filterValue);
                }
            }
        }

        return $assets;
    }

    /**
     * Format the record for export as csv
     * @param object single record object
     * 
     * @return array formatted
     */
    public function getExportNestedData($asset)
    {
        return [
            'Asset Tag #' => disableCSVInjection($asset->asset_tag ?? ''),
            'Serial #' => disableCSVInjection($asset->serial_no ?? ''),
            'Asset Status' => disableCSVInjection(optional($asset->assetStatus)->name ?? ''),
            'Hardware Standard' => disableCSVInjection(optional($asset->makeAndModel)->name ?? ''),
            'Tech Specs' => disableCSVInjection(optional($asset->technicalSpec)->details ?? ''),
            'User/Location' => disableCSVInjection($asset->user ? (optional($asset->user)->email) : ($asset->location ? (optional($asset->location)->room_name) : '')),
            'User Work Location' => disableCSVInjection(optional($asset->user)->city ?? ''),
            'Sensor Installed' => disableCSVInjection($asset->sensor_detected)
        ];
    }

    /**
     * Retrieves nested data for an asset.
     *
     * @param object $asset The asset object.
     * @param integer $index The index of the asset.
     * 
     * @return array The nested data for the asset.
     */
    public function getNestedData($asset, $index)
    {

        $nestedData = [];
        $commonData = $this->getExportNestedData($asset);
        $assetLink  = route('assets.show', $asset->id);
        $userLocationLink = $asset->user ? route('users.show', optional($asset->user)->id) : ($asset->location ? route('location.show', optional($asset->location)->id) : '#');

        $nestedData['id']   = $index;

        foreach ($commonData as $key => $value) {
            $nestedData[Str::slug($key, '_')] = $value;
        }
        $nestedData['asset_tag'] = "<a href=$assetLink>" . $nestedData['asset_tag'] . "</a>";
        $nestedData['serial'] = "<a href=$assetLink>" . $nestedData['serial'] . "</a>";
        $nestedData['userlocation'] = "<a href=$userLocationLink>" . $nestedData['userlocation'] . "</a>";

        return $nestedData;
    }

    /**
     * Export the data.
     *
     * @return mixed
     */
    public function exportData()
    {
        $assets = $this->repository->sensorDetectionData();
        $requestData = request()->all();
        $assets = $this->filterResults($assets, $requestData);
        $assets     = $assets->orderBy('id', 'DESC');

        return $assets;
    }
}
