<?php
defined( 'ABSPATH' ) || exit;

class NASEO_CSV_Importer {

    /**
     * Імпортує CSV файл у чергу — доступно у Free
     */
    public function import( string $file_path ): array {
        if ( ! file_exists( $file_path ) ) {
            return [ 'success' => false, 'message' => __( 'Файл не знайдено.', 'nemynai-seo-autopilot' ) ];
        }

        $content = file_get_contents( $file_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents

        // Видаляємо BOM
        $content = preg_replace( '/^\xEF\xBB\xBF/', '', $content );

        // Конвертуємо Windows-1251 → UTF-8 якщо треба
        if ( ! mb_check_encoding( $content, 'UTF-8' ) ) {
            $content = mb_convert_encoding( $content, 'UTF-8', 'Windows-1251' );
        }

        // Визначаємо роздільник
        $delimiter = $this->detect_delimiter( $content );

        $lines   = explode( "\n", str_replace( "\r\n", "\n", $content ) );
        $headers = str_getcsv( array_shift( $lines ), $delimiter );
        $headers = array_map( 'trim', $headers );

        $required = [ 'title', 'keyword' ];
        foreach ( $required as $col ) {
            if ( ! in_array( $col, $headers, true ) ) {
                return [ 'success' => false, 'message' => "Відсутня колонка: {$col}" ];
            }
        }

        global $wpdb;
        $table    = $wpdb->prefix . 'naseo_queue';
        $imported = 0;
        $skipped  = 0;

        foreach ( $lines as $line ) {
            $line = trim( $line );
            if ( empty( $line ) ) continue;

            $row = array_combine( $headers, str_getcsv( $line, $delimiter ) );
            if ( ! $row ) { $skipped++; continue; }

            $title = sanitize_text_field( trim( $row['title'] ?? '' ) );
            if ( empty( $title ) ) { $skipped++; continue; }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->insert( $table, [
                'title'          => $title,
                'keyword'        => sanitize_text_field( trim( $row['keyword'] ?? $title ) ),
                'lsi_keywords'   => sanitize_textarea_field( trim( $row['lsi_keywords'] ?? '' ) ),
                'category'       => sanitize_text_field( trim( $row['category'] ?? '' ) ),
                'scheduled_date' => $this->parse_date( $row['date'] ?? '' ),
                'schedule'       => sanitize_text_field( trim( $row['schedule'] ?? 'daily' ) ),
                'status'         => 'pending',
            ] );

            $imported++;
        }

        return [
            'success'  => true,
            'message'  => sprintf( /* translators: 1: number of imported rows, 2: number of skipped rows */
                __( 'Імпортовано: %1$d рядків. Пропущено: %2$d.', 'nemynai-seo-autopilot' ), $imported, $skipped ),
            'imported' => $imported,
        ];
    }

    private function detect_delimiter( string $content ): string {
        $first_line = strtok( $content, "\n" );
        $semicolons = substr_count( $first_line, ';' );
        $commas     = substr_count( $first_line, ',' );
        return $semicolons > $commas ? ';' : ',';
    }

    private function parse_date( string $date ): ?string {
        if ( empty( $date ) ) return null;
        $ts = strtotime( $date );
        return $ts ? gmdate( 'Y-m-d', $ts ) : null;
    }
}
