<?php

namespace Storeplugin\PDFInvoice\Framework\Forms;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractMeta;
use Storeplugin\PDFInvoice\Framework\Contracts\MetaInterface;

/**
 * Post-type meta box implementation.
 *
 * Uses get_post_meta / update_post_meta and hooks into save_post.
 *
 * @package Storeplugin\PDFInvoice\Framework\Forms
 * @since 1.0.0
 */
class Meta extends AbstractMeta
{
    /**
     * Create a new metabox instance.
     *
     * @param string       $id          Unique metabox ID
     * @param string       $title       Display title
     * @param string       $optionGroup Prefix for form field names (required)
     * @param string|array $postTypes   Post types to show the metabox on
     * @param string       $context     Where the box should show up ('normal', 'side', 'advanced')
     * @param string       $priority    Priority within the context
     *
     * @return MetaInterface
     */
    public static function create($id, $title, string $optionGroup, $postTypes = ['post'], $context = 'normal', $priority = 'default'): MetaInterface
    {
        return new self($id, $title, $optionGroup, (array) $postTypes, $context, $priority);
    }

    /**
     * @inheritDoc
     */
    protected function getMetaValues($object): array
    {
        $values = [];
        foreach ($this->getAllFields() as $field) {
            $id = \sanitize_key((string) ($field['id'] ?? ''));
            if ($id === '') { continue; }
            if (\metadata_exists('post', $object->ID, $id)) {
                $values[$id] = \get_post_meta($object->ID, $id, true);
            }
        }
        return $values;
    }

}
