<?php

namespace SEOAIC\preset_types;

class AddLink extends AbstractPresetType
{
    public $name = 'add_links';
    public $preselectDefault = false;

    public function getTitle() {
        return esc_html__('Add Links', 'seoaic');
    }

    public function drawHtml() {
        echo '<label for="posts_edit_add_link">' . esc_html($this->getTitle()) . '</label>
             <select name="posts_edit_add_link" id="posts_edit_add_link" class="seoaic-keyword-page-link seoaic-form-item form-select"></select>';
    }

    public function makePayload() {
        $__REQUEST = wp_unslash($_REQUEST);
        $arrayLinks = !empty($__REQUEST['posts_edit_add_link']) ? $__REQUEST['posts_edit_add_link'] : [];

        if (is_string($arrayLinks)) {
            $arrayLinks = json_decode($arrayLinks, true);
        }

        $links = [];

        foreach ($arrayLinks as $item) {
            if (strpos($item, $this->separator) !== false) {
                [$title, $url] = explode($this->separator, $item, 2);
                $links[] = [
                    'title' => sanitize_text_field($title),
                    'url'   => esc_url_raw($url),
                ];
            }
        }

        return [
            'links' => $links
        ];
    }
}
