<?php

/**
 * @package     PublishPress\Checklists
 * @author      PublishPress <help@publishpress.com>
 * @copyright   copyright (C) 2024 PublishPress. All rights reserved.
 * @license     GPLv2 or later
 * @since       1.0.0
 */

namespace PublishPress\ChecklistsPro\ImageCaptionCount\Requirement;

use PublishPress\Checklists\Core\Requirement\Base_counter;

defined('ABSPATH') or die('No direct script access allowed.');

class ImageCaptionCount extends Base_counter
{
    /**
     * The name of the requirement, in a slug format
     *
     * @var string
     */
    public $name = 'image_caption_count';

    /**
     * The name of the group, used for the tabs
     * 
     * @var string
     */
    public $group = 'images';

    /**
     * @var int
     */
    public $position = 136;

    /**
     * Initialize the language strings for the instance
     *
     * @return void
     */
    public function init_language()
    {
        $this->lang['label']                = __('Number of characters in image captions', 'publishpress-checklists-pro');
        $this->lang['label_settings']       = __('Number of characters in image captions', 'publishpress-checklists-pro');
        $this->lang['label_min_singular']   = __('Minimum of %d character in image captions', 'publishpress-checklists-pro');
        $this->lang['label_min_plural']     = __('Minimum of %d characters in image captions', 'publishpress-checklists-pro');
        $this->lang['label_max_singular']   = __('Maximum of %d character in image captions', 'publishpress-checklists-pro');
        $this->lang['label_max_plural']     = __('Maximum of %d characters in image captions', 'publishpress-checklists-pro');
        $this->lang['label_exact_singular'] = __('%d character in image captions', 'publishpress-checklists-pro');
        $this->lang['label_exact_plural']   = __('%d characters in image captions', 'publishpress-checklists-pro');
        $this->lang['label_between']        = __('Between %d and %d characters in image captions', 'publishpress-checklists-pro');
    }

    /**
     * Returns the current status of the requirement.
     *
     * @param stdClass $post
     * @param mixed $option_value
     *
     * @return mixed
     */
    public function get_current_status($post, $option_value)
    {
        $post_content = isset($post->post_content) ? $post->post_content : '';
        $caption_lengths = $this->get_image_caption_lengths($post_content);

        foreach ($caption_lengths as $length) {
            if ($length < $option_value[0] || ($option_value[1] > 0 && $length > $option_value[1])) {
                return false;
            }
        }

        return true;
    }

    /**
     * Get the lengths of captions for all images in the content
     *
     * @param string $content
     *
     * @return array
     */
    private function get_image_caption_lengths($content)
    {
        $lengths = [];

        if (!is_string($content) || $content === '') {
            return $lengths;
        }

        $captions = [];

        if (preg_match_all('/<figcaption[^>]*>(.*?)<\/figcaption>/is', $content, $matches)) {
            foreach ($matches[1] as $caption) {
                $captions[] = $caption;
            }
        }

        if (preg_match_all('/\[caption[^\]]*\](.*?)\[\/caption\]/is', $content, $matches)) {
            foreach ($matches[1] as $caption) {
                $captions[] = preg_replace('/<img[^>]*>/i', '', $caption);
            }
        }

        if (preg_match_all('/<p[^>]*class=(["\'])(?:[^"\']*\s)?wp-caption-text(?:\s[^"\']*)?\1[^>]*>(.*?)<\/p>/is', $content, $matches)) {
            foreach ($matches[2] as $caption) {
                $captions[] = $caption;
            }
        }

        if (preg_match_all('/<dd[^>]*class=(["\'])(?:[^"\']*\s)?wp-caption-dd(?:\s[^"\']*)?\1[^>]*>(.*?)<\/dd>/is', $content, $matches)) {
            foreach ($matches[2] as $caption) {
                $captions[] = $caption;
            }
        }

        foreach ($captions as $caption) {
            $lengths[] = strlen(trim(wp_strip_all_tags($caption)));
        }

        $image_count = 0;
        if (preg_match_all('/<img\s[^>]*>/i', $content, $image_matches)) {
            $image_count = count($image_matches[0]);
        }

        if ($image_count > count($lengths)) {
            $lengths = array_merge($lengths, array_fill(0, $image_count - count($lengths), 0));
        }

        if ($image_count > 0 && count($lengths) > $image_count) {
            $lengths = array_slice($lengths, 0, $image_count);
        }

        return $lengths;
    }
}
