<?php

namespace Digtective\Integrations;

use Digtective\Controllers\FormSubmissionController;

class GravityFormsIntegration
{
    private $fieldLabel = "Digger Id";
    private $fieldType = "hidden";
    private $formSubmissionController;

    public function __construct(){
        $this->formSubmissionController = new FormSubmissionController();
    }

    public function register(){
        add_action( 'gform_after_submission', [$this, 'getDiggerId'], 10, 2 );
    }

    public function getDiggerId( $entry, $form ) {
        try{
            $diggerFieldId = null;
            foreach($form['fields'] as $field){
                $label = $field['label'];
                if($label == $this->fieldLabel){
                    $diggerFieldId = $field['id'];
                }
            }

            if(!$diggerFieldId){
                $diggerFieldId = \GFFormsModel::get_next_field_id( $form['fields'] );

                $properties['id'] = $diggerFieldId;
                $properties['label'] = $this->fieldLabel;
                $properties['type'] = $this->fieldType;

                $field = \GF_Fields::create( $properties );
                $form['fields'][] = $field;
                \GFAPI::update_form( $form );
            }

            $response = $this->formSubmissionController->createFormSubmission([]);
            $diggerId = $response->data->formSubmissionId ?? "";
            \GFAPI::update_entry_field($entry['id'], $diggerFieldId, $diggerId);
        }catch(\Exception $e){
            error_log($e);
        }
    }

}


