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

defined('ABSPATH') || exit;

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

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

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

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

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

        $bee_corp_entries = preg_split('/(?==\s\d+\.\d+\.\d+)/', $bee_corp_content, -1, PREG_SPLIT_NO_EMPTY);
        $bee_corp_output  = [];

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

        return $bee_corp_output;
    }
}