<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Exporter\Formats;

use BadamSoft\WooProductExporter\Helpers\DownloadHelper;
use BadamSoft\WooProductExporter\Helpers\Utils;

class CsvWriter extends AbstractStreamWriter {
    public function getKey(): string {
        return 'csv';
    }

    public function getLabel(): string {
        return __( 'CSV (Comma separated)', 'badamsoft-product-exporter-for-woocommerce' );
    }

    public function getFileExtension(): string {
        return 'csv';
    }

    public function getContentType(): string {
        return 'text/csv; charset=utf-8';
    }

    public function open( array $fields, array $field_definitions, array $settings = [] ): void {
        $this->fields            = $fields;
        $this->field_definitions = $field_definitions;

        $filename = ! empty( $settings['filename'] )
            ? (string) $settings['filename']
            : sprintf( 'wc-products-export-%s.%s', \wp_date( 'Y-m-d-H-i-s' ), $this->getFileExtension() );

        $content_type = $this->getContentType();

        $with_bom = isset( $settings['bom'] ) ? (bool) $settings['bom'] : true;

        $this->open_stream( $filename, $content_type, $settings, $with_bom );

        $headers = [];

        foreach ( $this->fields as $field_key ) {
            $headers[] = $this->field_definitions[ $field_key ]['label'] ?? $field_key;
        }

        fputcsv( $this->handle, $headers );
    }

    public function writeRow( array $row ): void {
        if ( ! is_resource( $this->handle ) ) {
            return;
        }

        $ordered = [];

        foreach ( $this->fields as $field_key ) {
            $value       = $row[ $field_key ] ?? '';
            $ordered[] = Utils::prepare_csv_value( $value );
        }

        fputcsv( $this->handle, $ordered );
    }

    public function close(): void {
        $this->close_output_stream();
    }
}
