<?php

namespace SEOAIC;

use SEOAIC\resources\PillarLink;
use SeoaicAjaxValidation;
use WP_Query;

class SeoaicPillarLinks
{
    private $seoaic;

    public function __construct($_seoaic)
    {
        $this->seoaic = $_seoaic;

        add_action('wp_ajax_seoaic_activate_pillar_links', [$this, 'activatePillarLinks']);
        add_action('wp_ajax_seoaic_pillar_links_tracked', [$this, 'trackedPillarLinks']);
    }

    public static function makePillarlLinksPermalinkAndTitleString(array $links): string
    {
        $links = array_map(function ($link) {
            if (is_a($link, 'WP_Post')) {
                return PillarLink::fromWP_Post($link);
            } else if (is_string($link)) {
                return PillarLink::fromString($link);
            }

            return $link;
        }, $links);
        $formattedPillarLinks = implode(
            ', ',
            array_map(function (PillarLink $item) {
                return $item->url . (!empty($item->title) ? " - " . $item->title : '');
            }, $links)
        ) . '.';

        return $formattedPillarLinks;
    }

    /**
     * Activate pillar links
     *
     * This function handles the AJAX request to activate or deactivate
     * pillar links based on the checked value sent via POST request.
     *
     * @return void
     */
    public function activatePillarLinks()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        if (empty($_POST['checked'])) {
            SEOAICAjaxResponse::error('Empty value')->wpSend();
        }

        $isChecked = sanitize_text_field(wp_unslash($_POST['checked']));

        if ($isChecked === 'true') {
            $SEOAIC_OPTIONS['seoaic_pillar_link_action'] = 'on';
        } else {
            $SEOAIC_OPTIONS['seoaic_pillar_link_action'] = '';
        }

        update_option('seoaic_options', $SEOAIC_OPTIONS);
        SEOAICAjaxResponse::success()->wpSend();
    }

    /**
     * Track pillar links
     *
     * This function handles the AJAX request to track or untrack pillar links
     * based on the POST request, updating the 'seoaic_tracked_pillar_link' meta field.
     *
     * @return void
     */
    public function trackedPillarLinks()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $post_id = !empty($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0;

        if (empty($post_id)) {
            SEOAICAjaxResponse::error('No valid ID set.')->wpSend();
        }

        $tracked = (!empty($_POST['tracked']) ? sanitize_text_field(wp_unslash($_POST['tracked'])) : false);

        update_post_meta($post_id, 'seoaic_tracked_pillar_link', $tracked);

        SEOAICAjaxResponse::success()->wpSend();
    }

    /**
     * Update old pillar links to new tracked ones
     *
     * This function goes through the old pillar links stored in the options
     * and updates the 'seoaic_tracked_pillar_link' meta field to true for each link.
     *
     * @return void
     */
    public function update_pillar_links() {
        global $SEOAIC_OPTIONS;

        $old_pillar_links = !empty($SEOAIC_OPTIONS['seoaic_pillar_links']) ? $SEOAIC_OPTIONS['seoaic_pillar_links'] : '';

        if (empty($old_pillar_links)) {
            return;
        }

        foreach ($old_pillar_links as $link) {
            $old_link = $link['url'];
            $post_id = url_to_postid($old_link);

            if ($post_id) {
                update_post_meta($post_id, 'seoaic_tracked_pillar_link', true);
            }
        }

        unset($SEOAIC_OPTIONS['seoaic_pillar_links']);
        update_option('SEOAIC_OPTIONS', $SEOAIC_OPTIONS);
    }

    /**
     * Get pillar links
     *
     * This function retrieves all posts marked as tracked pillar links.
     * It supports multilingual filtering if a language is specified.
     *
     * @param string $lang Optional language filter for multilingual sites.
     *
     * @return string A comma-separated list of tracked pillar link URLs with titles.
     */
    public function getPillarLinksString($lang = '')
    {
        $pillarLinks = $this->getPillarLinks($lang);

        if (!empty($pillarLinks)) {
            $formattedPillarLinks = self::makePillarlLinksPermalinkAndTitleString($pillarLinks);

            return $formattedPillarLinks;
        }

        return '';
    }

    /**
     * Get pillar links
     *
     * This function retrieves all posts marked as tracked pillar links.
     * It supports multilingual filtering if a language is specified.
     *
     * @param string $lang Optional language filter for multilingual sites.
     *
     * @return PillarLink[] Array of tracked pillar links - PillarLink object.
     */
    public function getPillarLinks($lang = '')
    {
        $pillar_links = [];

        $args = [
            'posts_per_page'    => -1,
            'post_type'         => seoaic_get_post_types(),
            'post_status'       => 'publish',
            'lang'              => '',
            'meta_query'        => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                [
                    'key'     => 'seoaic_tracked_pillar_link',
                    'value'   => 'true',
                    'compare' => '=',
                ],
            ],
        ];

        if (
            !empty($lang)
            && $this->seoaic->multilang->is_multilang()
        ) {
            $args['lang'] = $lang;
        }

        $query = new WP_Query($args);

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();

                $post = get_post(get_the_ID());
                $pillar_links[] = PillarLink::fromWP_Post($post);
            }

            wp_reset_postdata();
        }

        return $pillar_links;
    }

    /**
     * @param PillarLink[] $pillarLinks array of PillarLink objects
     */
    public function makePillarLinksOptionsString(array $pillarLinks)
    {
        $optionsString = '';

        foreach ($pillarLinks as $pillarLink) {
            $optionsString .= '<option value="' . esc_attr($pillarLink->id) . '" data-lang="' . (!empty($pillarLink->lang) ? esc_attr($pillarLink->lang) : '') . '" data-locale="' . (!empty($pillarLink->locale) ? esc_attr($pillarLink->locale) : '') . '">' . $pillarLink->title . '</option>';
        }

        return $optionsString;
    }

    public static function convertFromMetaDataToString(array $data)
    {
        if (
            empty($data)
            || !is_array($data)
        ) {
            return '';
        }

        $links = [];

        foreach ($data as $item) {
            if (is_numeric($item)) {
                $post = get_post($item);

                if ($post) {
                    $links[] = $post;
                }
            } else if (is_string($item)) { // external custom URL
                $links[] = $item;
            }
        }

        $formattedString = self::makePillarlLinksPermalinkAndTitleString($links);

        return $formattedString;
    }
}
