<?php

use Carbon\Carbon;
use Illuminate\Config\Repository;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class FillFormFor{{ name }} extends Migration
{

    protected array $fields;

    public function __construct()
    {
        $this->fields = [
            {{ fields }}
        ];
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        $fields = $this->fields;
        DB::transaction(function () use ($fields){
          $fieldsIds = [];
          foreach($fields as $field) {
             $fieldExists = DB::table('fields')->where([
                  'key' => $field['key'],
             ])->first();
              if ($fieldExists === null) {
                DB::table('fields')->insert([
                    "label" => $field['label'],
                    "key" => $field['key'],
                    "type"=> $field['type'],
                    "placeholder" => $field['placeholder'],
                    "is_required" => $field['is_required'],
                    "has_options" => $field['has_options'],
                ]);

                $fieldsIds[] = DB::getPdo()->lastInsertId();

                if($field['is_required']){
                    $options = explode(',', $field['options']);
                    $options = array_map(function ($option){
                        return trim($option);
                    }, $options);
                    foreach($options as $option){
                        DB::table('field_options')->insert([
                            "field_id" => DB::getPdo()->lastInsertId(),
                            'type' => 'text',
                            'label' => $option,
                            'value' => $option,
                        ]);
                    }
                }
              }
              else {
                $fieldsIds[] = $fieldExists->id;
              }
          }


           $fromExists = DB::table('forms')->where([
                'key' => '{{ key }}',
           ])->first();
           if ($fromExists === null) {
               DB::table('forms')
                ->insert([
                    "title" => "{{ formTitle }}",
                    "key" => "{{ key }}",
                    "endpoint" => "{{ formEndpoint }}",
                    "method" => "{{ formMethod }}",
                    "description" => "{{ formDescription }}",
                    "type" => "{{ formType }}"
                ]);
           }

          $formId = DB::table('forms')->where([
             'key' => '{{ key }}',
          ])->first()->id;

          foreach($fieldsIds as $fieldKey=>$fieldItem){
              $checkExists = DB::table('form_has_fields')->where([
                    "form_id" => $formId,
                    "field_id" => $fieldItem,
              ])->first();
              if($checkExists === null){
                  DB::table('form_has_fields')->insert([
                      "form_id" => $formId,
                      "field_id" => $fieldItem,
                      "order" => $fieldKey,
                  ]);
              }
          }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        $fields = $this->fields;
        DB::transaction(function () use ($fields){
            foreach($fields as $field) {
                $filedID = DB::table('fields')->where([
                    'key' => $field['key'],
                ])->first()->id;

                DB::table('field_options')->where([
                    'field_id' => $filedID,
                ])->delete();

                DB::table('fields')->where([
                    'key' => $field['key'],
                ])->delete();
            }
            DB::table('forms')->where([
                'key' => '{{ key }}',
            ])->delete();
        });
    }
}
