<?php

function sparrow_read_csv_preview(string $file_path, int $row_limit = 10): array
{
    if (!is_file($file_path)) {
        throw new RuntimeException('CSV file was not found.');
    }

    $handle = fopen($file_path, 'r');

    if (!$handle) {
        throw new RuntimeException('Could not open the CSV file.');
    }

    $headers = fgetcsv($handle);

    if (!$headers) {
        fclose($handle);
        throw new RuntimeException('The CSV file appears to be empty or invalid.');
    }

    $headers = array_map('trim', $headers);

    $rows = [];
    $count = 0;

    while (($data = fgetcsv($handle)) !== false && $count < $row_limit) {
        $rows[] = $data;
        $count++;
    }

    fclose($handle);

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

function sparrow_count_csv_rows(string $file_path): int
{
    if (!is_file($file_path)) {
        throw new RuntimeException('CSV file was not found.');
    }

    $handle = fopen($file_path, 'r');

    if (!$handle) {
        throw new RuntimeException('Could not open the CSV file.');
    }

    // Skip header row.
    fgetcsv($handle);

    $count = 0;

    while (fgetcsv($handle) !== false) {
        $count++;
    }

    fclose($handle);

    return $count;
}

function sparrow_read_forminator_grouped_preview(string $file_path, int $entry_limit = 5): array
{
    if (!is_file($file_path)) {
        throw new RuntimeException('CSV file was not found.');
    }

    $handle = fopen($file_path, 'r');

    if (!$handle) {
        throw new RuntimeException('Could not open the CSV file.');
    }

    $headers = fgetcsv($handle);

    if (!$headers) {
        fclose($handle);
        throw new RuntimeException('The CSV file appears to be empty or invalid.');
    }

    $headers = array_map('trim', $headers);

    $entry_id_index = array_search('entry_id', $headers);
    $meta_key_index = array_search('meta_key', $headers);
    $meta_value_index = array_search('meta_value', $headers);
    $date_created_index = array_search('date_created', $headers);

    if ($entry_id_index === false || $meta_key_index === false || $meta_value_index === false) {
        fclose($handle);
        throw new RuntimeException('This does not look like a Forminator meta CSV. Missing entry_id, meta_key, or meta_value.');
    }

    $orders = [];

    while (($row = fgetcsv($handle)) !== false) {
        $entry_id = $row[$entry_id_index] ?? '';

        if ($entry_id === '') {
            continue;
        }

        if (!isset($orders[$entry_id])) {
            if (count($orders) >= $entry_limit) {
                continue;
            }

            $orders[$entry_id] = [
                'entry_id' => $entry_id,
                'date_created' => $date_created_index !== false ? ($row[$date_created_index] ?? '') : '',
                'fields' => [],
            ];
        }

        if (!isset($orders[$entry_id])) {
            continue;
        }

        $meta_key = $row[$meta_key_index] ?? '';
        $meta_value = $row[$meta_value_index] ?? '';

        $orders[$entry_id]['fields'][$meta_key] = $meta_value;
    }

    fclose($handle);

    return array_values($orders);
}