<?php
/**
 * KnowledgeHub Changelog.
 *
 * @package KnowledgeHub
 * @since   1.0.0
 */

defined('ABSPATH') || exit;

class KnowledgeHub_Changelog_Parser {

    public function get_items() {
        return $this->parse_changelog($this->read_changelog());
    }

    protected function read_changelog() {
        global $wp_filesystem;

        if (!$wp_filesystem || 'direct' !== $wp_filesystem->method) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem(request_filesystem_credentials('', 'direct'));
        }

        $knowledgehub_file = get_template_directory() . '/readme.txt';

        if (!$wp_filesystem || !$wp_filesystem->exists($knowledgehub_file)) {
            return new WP_Error('changelog_not_found', 'Changelog not found.');
        }

        return $wp_filesystem->get_contents($knowledgehub_file);
    }

    protected function parse_changelog($knowledgehub_content) {
        if (is_wp_error($knowledgehub_content)) return $knowledgehub_content;

        $knowledgehub_entries = preg_split('/(?==\s\d+\.\d+\.\d+)/', $knowledgehub_content, -1, PREG_SPLIT_NO_EMPTY);
        $knowledgehub_output  = [];

        foreach ($knowledgehub_entries as $entry) {

            if (!preg_match('/= (\d+(?:\.\d+)*) - (\d{4}-\d{2}-\d{2}) =/', $entry, $m)) continue;

            $version = $m[1];
            $date    = $m[2];
            $changes = [];

            if (preg_match_all('/^\* (.+)$/m', $entry, $lines)) {
                foreach ($lines[1] as $line) {

                    $parts = explode(' - ', $line, 2);
                    $tag   = count($parts) === 2 ? trim($parts[0]) : 'update';
                    $desc  = count($parts) === 2 ? trim($parts[1]) : trim($line);

                    $changes[$tag][] = rtrim($desc, '. ');
                }
            }

            if ($changes) {
                $knowledgehub_output[] = compact('version', 'date', 'changes');
            }
        }

        return $knowledgehub_output;
    }
}