<?php
/**
 * Party Corp Changelog.
 *
 * @package Party Corp
 * @since   1.0.0
 */

defined('ABSPATH') || exit;

class Party_Corp_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'));
        }

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

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

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

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

        $party_corp_entries = preg_split('/(?==\s\d+\.\d+\.\d+)/', $party_corp_content, -1, PREG_SPLIT_NO_EMPTY);
        $party_corp_output  = [];

        foreach ($party_corp_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) {
                $party_corp_output[] = compact('version', 'date', 'changes');
            }
        }

        return $party_corp_output;
    }
}