<?php

namespace App\Services\Location;

use App\Http\Responses\ReportOutputData;
use App\Models\Accessory;

class LocationAccessoryData
{
    public function __construct(protected  ReportOutputData $reportOutputData)
    {
    }

    /** function fiters accessories of the selected location and returns paginated data
     * @return Accessories
     */
    public function locationAccessoriesFilter()
    {
        $accessories = Accessory::with(['location', 'makeAndModel.manufacturer', 'technicalSpec'])->where('location_id', request('form')['location']);

        $searchText   = isset(request('form')['filterAccessory']) ? request('form')['filterAccessory'] : '';

        if ($searchText) {
            $accessories = $accessories->whereHas('makeAndModel', function ($query) use ($searchText) {
                $query->where('name', 'like', '%' . $searchText . '%');
            });
        }

        $count = $accessories->count();
        $accessories = $this->reportOutputData->getOutputData($accessories);
        return compact('accessories', 'count');
    }

    /**
     * Gets the paginated data of accessories in the location
     * @param mixed $accessories
     * @param mixed $start
     * @param mixed $data
     *
     * @return [type]
     */
    public function getLocationAccessoriesData($accessories, $start, $data)
    {
        $parentIndex = $start;

        foreach ($accessories as $key => $accessory) {
            $parentId = $accessory->id;

            $parentIndex++;

            $nestedData = $this->getNestedLocationAccessoriesData($accessory, $parentIndex);

            $data[] = $nestedData;
        }

        return $data;
    }

    public function getNestedLocationAccessoriesData($accessory, $index)
    {
        $nestedData['id']           = $index;
        $nestedData['hardware']     = $accessory->makeAndModel->makeModelName ?? '';
        $nestedData['technical_spec']  = $accessory->technicalSpec->details ?? '';
        $nestedData['available_quantity']  = $accessory->available_quantity;
        $nestedData['weekly_demand']  = $accessory->weekly_demand;
        $nestedData['lead_time']  = $accessory->lead_time;
        $nestedData['order_quantity']  = $accessory->order_quantity;
        return $nestedData;
    }
}
