<?php

namespace PortalPeople\qvc\components;

class CsvParser
{
    public function parseCsvFile(string $filePath): array
    {
        $handle = fopen($filePath, 'rb');
        if ($handle === false) {
            return [
                'headers' => [],
                'rows' => [],
                'error' => 'Unable to read uploaded CSV file.',
            ];
        }

        $headers = fgetcsv($handle);
        if ($headers === false || count($headers) === 0) {
            fclose($handle);
            return [
                'headers' => [],
                'rows' => [],
                'error' => 'The CSV file is empty or missing a header row.',
            ];
        }

        $normalizedHeaders = [];
        foreach ($headers as $header) {
            $normalizedHeaders[] = trim((string) $header);
        }

        $rows = [];
        while (($row = fgetcsv($handle)) !== false) {
            if ($this->isCsvRowEmpty($row)) {
                continue;
            }

            $mapped = [];
            foreach ($normalizedHeaders as $index => $headerName) {
                $mapped[$headerName] = isset($row[$index]) ? trim((string) $row[$index]) : '';
            }

            $rows[] = $mapped;
        }

        fclose($handle);

        return [
            'headers' => $normalizedHeaders,
            'rows' => $rows,
            'error' => null,
        ];
    }

    private function isCsvRowEmpty(array $row): bool
    {
        foreach ($row as $value) {
            if (trim((string) $value) !== '') {
                return false;
            }
        }

        return true;
    }
}
