<?php

namespace App\Http\Resources\MobileCarrier;

use Illuminate\Http\Resources\Json\JsonResource;

class MobileCarrierResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        $selectedColumns  = $this->getSelectedColumns($request);
        $mappings = $this->getFieldMappings();

        return $this->getMappedFields($mappings, $selectedColumns);
    }

    /**
     * Get the mapped fields.
     *
     * @param array $mapping
     * @param array $selectedColumns
     *
     * @return array
     */
    private function getMappedFields($mapping, $selectedColumns)
    {
        return collect($mapping)
            ->filter(function ($value, $key) use ($selectedColumns) {
                return in_array($key, $selectedColumns);
            })
            ->map(function ($value, $key) {
                return $this->transformField($key, $this->{$value});
            })
            ->toArray();
    }

    /**
     * Transform field values based on field name
     *
     * @param string $key Field name
     * @param mixed $value Field value
     *
     * @return mixed Transformed value
     */
    private function transformField($key, $value)
    {
        $dateFields = config('api-return-fields.date_fields');

        if (in_array($key, $dateFields)) {
            return parse_date_from_db_datetime($value);
        }

        if ($key == "country") {
            return $value->name;
        }

        return $value;
    }

    /**
     * Get the selected columns from the request.
     *
     * @param \Illuminate\Http\Request $request
     * 
     * @return array
     */
    protected function getSelectedColumns($request)
    {
        return $request->has('selected_columns')
            ? explode(',', $request->selected_columns)
            : array_keys($this->getFieldMappings());
    }

    /**
     * Get the field mappings.
     *
     * @return array
     */
    protected function getFieldMappings()
    {
        return config('api-return-fields.mobile_carrier');
    }
}
