<?php

namespace App\View\Components;

use App\Models\Form;
use Illuminate\View\Component;

class ViserForm extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */

    public $identifier;
    public $identifierValue;
    public $form;
    public $data;
    public $formData;

    public function __construct($identifier, $identifierValue, $existingData = [])
    {
        $this->identifier = $identifier;
        $this->identifierValue = $identifierValue;
        $this->form = Form::where($this->identifier, $this->identifierValue)->first();
        $this->formData = @$this->form->form_data ?? [];
        $this->data = $existingData;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        if (!empty($this->data)) {
            $formDataArray = json_decode(json_encode($this->formData), true);
            $i = 0;

            foreach ($formDataArray as $key => $value) {
                $formDataArray[$key]['value'] = $this->data[$i]->value ?? '';
                $i++;
            }

            $this->formData = json_decode(json_encode($formDataArray));
        }
        return view('components.viser-form');
    }
}
