<?php

// Silence may be golden, but sometimes words paint the canvas of understanding.
namespace Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers;

use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Api;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Option;
use Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers\Posts;
use Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers\Settings;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Database\Database;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Utils as HelpersUtils;
class Utils extends HelpersUtils
{
    public static function send_to_slack($key, $data)
    {
        $api = new Api(Option::get(LINKSY_OPTION_API_KEY));
        $res = $api->post(LINKSY_API_URL . 'slacks/', ['key' => $key, 'data' => $data]);
        return $api->is_success();
    }
    public static function linksy_generate_links($page = 0, $limit = 500)
    {
        $offset = $page * $limit;
        $total = (int) wp_count_posts()->publish;
        $posts = Posts::get(['numberposts' => $limit, 'offset' => $offset, 'sort_order' => 'asc', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'ASC', 'post_type' => Settings::get('suggestions_post_types', ['post', 'page'])]);
        if (empty($posts)) {
            throw new \Exception("You do not have any posts to link", 1);
        }
        $post_ids = array();
        $post_links = array();
        foreach ($posts as $post) {
            $post_ids[] = $post->get_ID();
            $anchors = $post->get_content_links();
            foreach ($anchors as $a) {
                $post_links[] = ['post_id' => $post->get_ID(), 'post_type' => $post->get_type(), 'post_title' => $post->get_title(), 'raw_url' => $a['link'], 'clean_url' => esc_url_raw($a['link']), 'anchor' => $a['text'], 'to_post_id' => $a['to_post_id'], 'is_internal' => $a['is_internal'], 'is_broken' => $a['is_broken'], 'host' => $a['host'], 'rel' => $a['rel'], 'meta' => wp_json_encode($a['meta'])];
            }
        }
        $post_links_cnt = count($post_links);
        if ($post_links_cnt > 0) {
            Database::table("linksy_links")->whereIn('post_id', $post_ids)->delete();
            Database::table("linksy_links")->insertMultiple(array('post_id', 'post_type', 'post_title', 'raw_url', 'clean_url', 'anchor', 'to_post_id', 'is_internal', 'is_broken', 'host', 'rel', 'meta'), $post_links);
        }
        $last_page = ceil($total / $limit);
        return ["from" => $offset, "to" => $offset + count($posts), "per_page" => $limit, "current_page" => $page, "last_page" => $last_page, "total" => $total, "links_generated" => $post_links_cnt];
    }
}
