<?php

namespace SEOAIC\repositories;

use SEOAIC\repositories\interfaces\PostRepositoryInterface;
use SEOAIC\SEOAIC_SETTINGS;
use WP_Query;

class PostRepository implements PostRepositoryInterface
{
    /**
     * Get posts by their IDs
     * @param int[] array of IDs
     * @return array Array of WP_Post objects
     */
    public function getByIDs(array $ids = []): array
    {
        $args = [
            'numberposts'   => -1,
            'post_type'     => SEOAIC_SETTINGS::getSEOAICPostType(),
            'post_status'   => 'any',
            'include'       => $ids,
            'lang'          => '',
            'skip_hiding'   => true,
            'ignore_sticky_posts' => true,
        ];
        $posts = get_posts($args);

        return $posts;
    }

    /**
     * wp_insert_post
     * @param array $args
     */
    public function create(array $args): int
    {
        return wp_insert_post($args);
    }

    public function updateField(int $id, string $field, $value)
    {
        return wp_update_post([
            'ID'    => $id,
            $field  => $value,
        ], true);
    }

    /**
     * Returns an associative array of posts, keyed either by slug (default) or by ID.
     *
     * @param bool   $include_edit_link Whether to include the edit_link in the response.
     * @param string $key_by            Key type: 'slug' (default) or 'id'.
     *
     * @return array Associative array of posts.
     */
    public function get_associative_posts_array($include_edit_link = false, $key_by = 'slug')
    {
        $posts_array = [];

        $createdPostsQuery = new WP_Query([
            'posts_per_page' => -1,
            'post_type'      => seoaic_get_post_types(),
            'lang'           => '',
            'meta_query'     => [ // all posts, without hiding feature
                'relation' => 'OR',
                [
                    'key'     => 'seoaic_posted',
                    'compare' => 'EXISTS',
                ],
                [
                    'key'     => 'seoaic_posted',
                    'compare' => 'NOT EXISTS',
                ],
            ],
        ]);

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

                $id    = get_the_ID();
                $url   = get_the_permalink($id);
                $slug  = basename(parse_url($url, PHP_URL_PATH));

                $modified_date  = get_post_field('post_modified', $id);
                $published_date = get_post_field('post_date', $id);
                $edit_link      = get_edit_post_link($id);
                $title          = get_the_title($id);
                $post_type      = get_post_type($id);
                $url            = get_permalink($id);

                $array_key = ($key_by === 'id') ? (int) $id : $slug;

                $posts_array[$array_key] = [
                    'post_title'     => $title,
                    'post_modified'  => $modified_date,
                    'post_published' => $published_date,
                    'post_type'      => $post_type,
                    'post_url'       => $url,
                    'id'             => $id,
                ];

                if ($include_edit_link) {
                    $posts_array[$array_key]['edit_link'] = $edit_link;
                }
            }
            wp_reset_postdata();
        }

        return $posts_array;
    }


    public function check_page_type_with_regex_and_message($path)
    {
        $default_post_types = ['post', 'page', 'attachment', 'revision', 'nav_menu_item'];
        $custom_post_types = array_diff(get_post_types(['public' => true], 'names'), $default_post_types);

        if (preg_match('/^\/?([a-z]{2}(-[a-zA-Z]{2})?)?\/?$/', $path, $matches)) {
            $language = isset($matches[1]) ? $matches[1] : '';
            $title = esc_html__('Home', 'seoaic');
            if ($language) {
                $title .= ' ' . ucfirst($language);
            }
            return ['content' => $title];
        }

        if (preg_match('/^page\/(\d+)\/?$/', $path, $matches)) {
            return ['content' => esc_html__('Homepage ', 'seoaic') . $matches[1]];
        }

        if (preg_match('/author\/([^\/]+)\/page\/(\d+)/', $path, $matches)) {
            return ['content' => esc_html__('Author: ', 'seoaic') . ucfirst($matches[1]) . ', ' . esc_html__('page ', 'seoaic') . $matches[2]];
        } elseif (preg_match('/author\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Author: ', 'seoaic') . ucfirst($matches[1])];
        }

        if (preg_match('/([^\/]+)-category\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Category: ', 'seoaic') . ucfirst($matches[2])];
        }

        if (preg_match('/([^\/]+)-tag\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Tag: ', 'seoaic') . ucfirst($matches[2])];
        }

        if (preg_match('/product\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Product: ', 'seoaic') . ucfirst($matches[1])];
        } elseif (preg_match('/product-category\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Product category: ', 'seoaic') . ucfirst($matches[1])];
        } elseif (preg_match('/product-tag\/([^\/]+)/', $path, $matches)) {
            return ['content' => esc_html__('Product tag: ', 'seoaic') . ucfirst($matches[1])];
        }

        if (preg_match('/(\d{4})\/(\d{2})\/?$/', $path, $matches)) {
            return ['content' => esc_html__('Archive: ', 'seoaic') . $matches[2] . '/' . $matches[1]];
        } elseif (preg_match('/(\d{4})\/(\d{2})\/page\/(\d+)/', $path, $matches)) {
            return ['content' => esc_html__('Archive: ', 'seoaic') . $matches[2] . '/' . $matches[1] . ', ' . esc_html__('page ', 'seoaic') . $matches[3]];
        }

        if (preg_match('/([^\/]+)\/([^\/]+)/', $path, $matches)) {
            if (in_array($matches[1], $custom_post_types)) {
                return ['content' => esc_html__('Post type: ', 'seoaic') . ucfirst($matches[1]) . ' - ' . ucfirst($matches[2])];
            } else {
                return ['content' => esc_html__('Page: ', 'seoaic') . ucfirst($matches[1]) . ' - ' . ucfirst($matches[2])];
            }
        }

        return ['content' => esc_url($path)];
    }
}
