<?php

namespace RistrettoApps\Spawnster\Services;

use RistrettoApps\Spawnster\Base\Constants;

class PublishPages
{
    public static function handle()
    {
        $pages = unserialize(get_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST));

        foreach ($pages as $key => $page) {
            $heading = get_option(Constants::SPAWNSTER_GENERATED_HEADING_KEY . $key);
            $content = implode("\n", unserialize(get_option(Constants::SPAWNSTER_GENERATED_CONTENT_KEY . $key)));
            wp_insert_post(array(
                'post_title'    => sanitize_text_field($page),
                'post_content'  => wp_kses_post($content),
                'post_type'     => 'page',
                'post_status'   => 'publish',
            ));
            // cleanup
            delete_option(Constants::SPAWNSTER_GENERATED_HEADING_KEY . $key);
            delete_option(Constants::SPAWNSTER_GENERATED_CONTENT_KEY . $key);
        }
        // more cleanup
        delete_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST);
        delete_option(Constants::SPAWNSTER_SETUP_YOUR_WEBSITE_KEY);
        delete_option(Constants::SPAWNSTER_SETUP_YOUR_PAGES_KEY);
        delete_option(Constants::SPAWNSTER_PAGE_DESCRIPTION_REQUEST);
        delete_option('spawnster-generated-progress');
    }
}