<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\PickupOrder\Grid;

use PrestaShop\PrestaShop\Core\Grid\Data\Factory\GridDataFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Data\GridData;
use PrestaShop\PrestaShop\Core\Grid\Data\GridDataInterface;
use PrestaShop\PrestaShop\Core\Grid\Record\RecordCollection;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class PickupOrderGridDataFactory implements GridDataFactoryInterface
{
    /**
     * @var GridDataFactoryInterface
     */
    private $dataFactory;

    public function __construct(GridDataFactoryInterface $dataFactory)
    {
        $this->dataFactory = $dataFactory;
    }

    public function getData(SearchCriteriaInterface $searchCriteria): GridDataInterface
    {
        $data = $this->dataFactory->getData($searchCriteria);

        $records = array_map([$this, 'modifyRecord'], $data->getRecords()->all());

        return new GridData(
            new RecordCollection($records),
            $data->getRecordsTotal(),
            $data->getQuery()
        );
    }

    private function modifyRecord(array $record): array
    {
        $record['shipment_numbers'] = explode(',', $record['shipment_numbers']);
        $record['pickup_time'] = $this->formatPickupTime($record);

        return $record;
    }

    private function formatPickupTime(array $record): string
    {
        $start = new \DateTime($record['pickup_time_start']);
        $end = new \DateTime($record['pickup_time_end']);

        return sprintf('%s - %s', $start->format('Y-m-d H:i'), $end->format('H:i'));
    }
}
