<?php

namespace PortalPeople\shippingcosts\services;

use yii\helpers\Json;

/**
 * PriceCalculationService - Handles JSON price field operations.
 *
 * Responsible for parsing, processing, and encoding price data stored as JSON
 * in the database. Provides utilities for merging price arrays and safe JSON handling.
 */
class PriceCalculationService
{
    /**
     * Parse JSON price string into array of price objects.
     *
     * Decodes JSON price string and returns array of price objects.
     * Returns empty array if parsing fails or input is invalid.
     *
     * @param mixed $jsonPrices JSON string or existing array
     * @return array Array of price objects with qty and price properties
     */
    public static function parsePrices($jsonPrices)
    {
        if (!$jsonPrices) {
            return [];
        }

        // Already an array
        if (is_array($jsonPrices)) {
            return $jsonPrices;
        }

        // JSON string - decode it
        if (is_string($jsonPrices)) {
            $decoded = Json::decode($jsonPrices, true);
            return is_array($decoded) ? $decoded : [];
        }

        return [];
    }

    /**
     * Process and merge price arrays before database storage.
     *
     * Takes existing price array and merges with new empty price entries
     * up to the specified count. Returns JSON-encoded string ready for storage.
     *
     * @param mixed $prices Existing prices (array or JSON string)
     * @param int $count Total number of prices needed
     * @return string JSON-encoded price array
     */
    public static function processPrices($prices, $count)
    {
        $existingPrices = self::parsePrices($prices);
        $currentCount = count($existingPrices);

        // Add empty price entries to reach desired count
        while ($currentCount < $count) {
            $existingPrices[] = [];
            $currentCount++;
        }

        return Json::encode($existingPrices);
    }
}
