<?php

namespace App\Http\Resources;

use App\Http\Controllers\Helpers\HelperController;
use App\Models\Plant;
use Illuminate\Http\Resources\Json\JsonResource;

class ControllersResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone,
            'last_login' => $this->last_login ? HelperController::format_date($this->last_login) : "Never logged in",
            'plant' =>  $this->validate($this->plant_code),
            'plant_code' => $this->plant_code?? null,
            'created_at' => HelperController::pretty_date($this->created_at)
        ];
    }


    private function validate($string)
    {
        if (str_contains($string, '[')) {
            $codes = $this->string_manipulation($string);
            $plants = [];
            foreach ($codes as $key => $code) {
                $plant = Plant::where('plant_code', $code)->first();
                $plants[] = $plant->plant_name;
            }
            return $plants;
        } else {
            $plant = Plant::where('plant_code', $string)->first();
            return $plant->plant_name;
        }
    }
    private function string_manipulation($mystring)
    {
        //$mystring = '["1100","1200","1300"]';
        $remove[] = "'";
        $remove[] = '"';
        $remove[] = '[';
        $remove[] = ']';
        $test = substr($mystring, 1, -1);
        $test_a = "'" . $test . "'";
        $myarray = str_replace($remove, "", $mystring);
        $data = explode(",", $myarray);
        return $data;
    }
}
