<?php
namespace Domain\Integrations;

class IntegrationsRepository
{
    private $db;

    private const SETTINGS_TABLES = [
        'apilo'  => 'pp_shop_apilo_settings',
        'shoppro' => 'pp_shop_shoppro_settings',
    ];

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

    // ── Settings ────────────────────────────────────────────────

    private function settingsTable( string $provider ): string
    {
        if ( !isset( self::SETTINGS_TABLES[$provider] ) )
            throw new \InvalidArgumentException( "Unknown provider: $provider" );

        return self::SETTINGS_TABLES[$provider];
    }

    public function getSettings( string $provider ): array
    {
        $table = $this->settingsTable( $provider );
        $rows = $this->db->select( $table, [ 'name', 'value' ] );
        $settings = [];
        foreach ( $rows ?: [] as $row )
            $settings[$row['name']] = $row['value'];

        return $settings;
    }

    public function getSetting( string $provider, string $name ): ?string
    {
        $table = $this->settingsTable( $provider );
        $value = $this->db->get( $table, 'value', [ 'name' => $name ] );
        return $value !== false ? $value : null;
    }

    public function saveSetting( string $provider, string $name, $value ): bool
    {
        $table = $this->settingsTable( $provider );
        if ( $this->db->count( $table, [ 'name' => $name ] ) ) {
            $this->db->update( $table, [ 'value' => $value ], [ 'name' => $name ] );
        } else {
            $this->db->insert( $table, [ 'name' => $name, 'value' => $value ] );
        }
        \Shared\Helpers\Helpers::delete_dir('../temp/');
        return true;
    }

    // ── Logs ────────────────────────────────────────────────────

    /**
     * Pobiera logi z tabeli pp_log z paginacją, sortowaniem i filtrowaniem.
     *
     * @return array{items:array, total:int}
     */
    public function getLogs( array $filters, string $sortColumn, string $sortDir, int $page, int $perPage ): array
    {
        $where = [];

        if ( !empty( $filters['log_action'] ) ) {
            $where['action[~]'] = '%' . $filters['log_action'] . '%';
        }

        if ( !empty( $filters['message'] ) ) {
            $where['message[~]'] = '%' . $filters['message'] . '%';
        }

        if ( !empty( $filters['order_id'] ) ) {
            $where['order_id'] = (int) $filters['order_id'];
        }

        $total = $this->db->count( 'pp_log', $where );

        $where['ORDER'] = [ $sortColumn => $sortDir ];
        $where['LIMIT'] = [ ( $page - 1 ) * $perPage, $perPage ];

        $items = $this->db->select( 'pp_log', '*', $where );
        if ( !is_array( $items ) ) {
            $items = [];
        }

        return [
            'items' => $items,
            'total' => (int) $total,
        ];
    }

    /**
     * Usuwa wpis logu po ID.
     */
    public function deleteLog( int $id ): bool
    {
        $this->db->delete( 'pp_log', [ 'id' => $id ] );
        return true;
    }

    /**
     * Czyści wszystkie logi z tabeli pp_log.
     */
    public function clearLogs(): bool
    {
        $this->db->delete( 'pp_log', [] );
        return true;
    }

    // ── Product linking (Apilo) ─────────────────────────────────

    public function linkProduct( int $productId, $externalId, $externalName ): bool
    {
        return (bool) $this->db->update( 'pp_shop_products', [
            'apilo_product_id'   => $externalId,
            'apilo_product_name' => \Shared\Helpers\Helpers::remove_special_chars( $externalName ),
        ], [ 'id' => $productId ] );
    }

    public function unlinkProduct( int $productId ): bool
    {
        return (bool) $this->db->update( 'pp_shop_products', [
            'apilo_product_id'   => null,
            'apilo_product_name' => null,
        ], [ 'id' => $productId ] );
    }

    // ── Product data ─────────────────────────────────────────────

    public function getProductSku( int $productId ): ?string
    {
        $sku = $this->db->get( 'pp_shop_products', 'sku', [ 'id' => $productId ] );
        return $sku ?: null;
    }

    // ── ShopPRO import ──────────────────────────────────────────

    public function shopproImportProduct( int $productId ): array
    {
        $settings = $this->getSettings( 'shoppro' );
        $missingSetting = $this->missingShopproSetting( $settings, [ 'domain', 'db_name', 'db_host', 'db_user' ] );
        if ( $missingSetting !== null ) {
            return [ 'success' => false, 'message' => 'Brakuje konfiguracji shopPRO: ' . $missingSetting . '.' ];
        }

        $mdb2 = $this->shopproDb( $settings );

        $product = $mdb2->get( 'pp_shop_products', '*', [ 'id' => $productId ] );
        if ( !$product )
            return [ 'success' => false, 'message' => 'Podczas importowania produktu wystąpił błąd.' ];

        $this->db->insert( 'pp_shop_products', [
            'price_netto'                => $product['price_netto'],
            'price_brutto'               => $product['price_brutto'],
            'vat'                        => $product['vat'],
            'stock_0_buy'                => $product['stock_0_buy'],
            'quantity'                   => $product['quantity'],
            'wp'                         => $product['wp'],
            'sku'                        => $product['sku'],
            'ean'                        => $product['ean'],
            'custom_label_0'             => $product['custom_label_0'],
            'custom_label_1'             => $product['custom_label_1'],
            'custom_label_2'             => $product['custom_label_2'],
            'custom_label_3'             => $product['custom_label_3'],
            'custom_label_4'             => $product['custom_label_4'],
            'additional_message'         => $product['additional_message'],
            'additional_message_text'    => $product['additional_message_text'],
            'additional_message_required'=> $product['additional_message_required'],
            'weight'                     => $product['weight'],
            'producer_id'                => $product['producer_id'] ?? null,
        ] );

        $newProductId = $this->db->id();
        if ( !$newProductId )
            return [ 'success' => false, 'message' => 'Podczas importowania produktu wystąpił błąd.' ];

        // Import translations
        $languages = $mdb2->select( 'pp_shop_products_langs', '*', [ 'product_id' => $productId ] );
        if ( is_array( $languages ) ) {
            foreach ( $languages as $lang ) {
                $this->db->insert( 'pp_shop_products_langs', [
                    'product_id'               => $newProductId,
                    'lang_id'                  => $lang['lang_id'],
                    'name'                     => $lang['name'],
                    'short_description'        => $lang['short_description'],
                    'description'              => $lang['description'],
                    'tab_name_1'               => $lang['tab_name_1'],
                    'tab_description_1'        => $lang['tab_description_1'],
                    'tab_name_2'               => $lang['tab_name_2'],
                    'tab_description_2'        => $lang['tab_description_2'],
                    'meta_title'               => $lang['meta_title'],
                    'meta_description'         => $lang['meta_description'],
                    'meta_keywords'            => $lang['meta_keywords'],
                    'seo_link'                 => $lang['seo_link'],
                    'copy_from'                => $lang['copy_from'],
                    'warehouse_message_zero'   => $lang['warehouse_message_zero'],
                    'warehouse_message_nonzero'=> $lang['warehouse_message_nonzero'],
                    'canonical'                => $lang['canonical'],
                    'xml_name'                 => $lang['xml_name'],
                    'security_information'     => $lang['security_information'] ?? null,
                ] );
            }
        }

        // Import custom fields
        $customFields = $mdb2->select( 'pp_shop_products_custom_fields', '*', [ 'id_product' => $productId ] );
        if ( is_array( $customFields ) ) {
            foreach ( $customFields as $field ) {
                $this->db->insert( 'pp_shop_products_custom_fields', [
                    'id_product'   => $newProductId,
                    'name'         => (string)($field['name'] ?? ''),
                    'type'         => (string)($field['type'] ?? 'text'),
                    'is_required'  => !empty( $field['is_required'] ) ? 1 : 0,
                ] );
            }
        }

        // Import images
        $images = $mdb2->select( 'pp_shop_products_images', '*', [ 'product_id' => $productId ] );
        $importLog = [];
        $domainRaw = preg_replace( '#^https?://#', '', (string)($settings['domain'] ?? '') );
        if ( is_array( $images ) ) {
            foreach ( $images as $image ) {
                $srcPath   = (string)($image['src'] ?? '');
                $imageUrl  = 'https://' . rtrim( $domainRaw, '/' ) . '/' . ltrim( $srcPath, '/' );
                $imageName = basename( $srcPath );

                if ( $imageName === '' ) {
                    $importLog[] = '[SKIP] Pusta nazwa pliku dla src: ' . $srcPath;
                    continue;
                }

                $ch = curl_init( $imageUrl );
                curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
                curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
                curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
                curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
                curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
                curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
                $imageData  = curl_exec( $ch );
                $httpCode   = (int)curl_getinfo( $ch, CURLINFO_HTTP_CODE );
                $curlErrno  = curl_errno( $ch );
                $curlError  = curl_error( $ch );
                curl_close( $ch );

                if ( $curlErrno !== 0 || $imageData === false ) {
                    $importLog[] = '[ERROR] cURL: ' . $imageUrl . ' — błąd ' . $curlErrno . ': ' . $curlError;
                    continue;
                }

                if ( $httpCode !== 200 ) {
                    $importLog[] = '[ERROR] HTTP ' . $httpCode . ': ' . $imageUrl;
                    continue;
                }

                $imageDir  = dirname( __DIR__, 3 ) . '/upload/product_images/product_' . $newProductId;
                $imagePath = $imageDir . '/' . $imageName;

                if ( !file_exists( $imageDir ) && !mkdir( $imageDir, 0777, true ) && !file_exists( $imageDir ) ) {
                    $importLog[] = '[ERROR] Nie można utworzyć katalogu: ' . $imageDir;
                    continue;
                }

                $written = file_put_contents( $imagePath, $imageData );
                if ( $written === false ) {
                    $importLog[] = '[ERROR] Zapis pliku nieudany: ' . $imagePath;
                    continue;
                }

                $this->db->insert( 'pp_shop_products_images', [
                    'product_id' => $newProductId,
                    'src'        => '/upload/product_images/product_' . $newProductId . '/' . $imageName,
                    'alt'        => $image['alt'] ?? '',
                    'o'          => $image['o'],
                ] );
                $importLog[] = '[OK] ' . $imageUrl . ' → ' . $imagePath . ' (' . $written . ' B)';
            }
        }

        // Zapisz log importu zdjęć (ścieżka absolutna — niezależna od cwd)
        $logDir  = dirname( __DIR__, 3 ) . '/logs';
        $logFile = $logDir . '/shoppro-import-debug.log';
        $mkdirOk = file_exists( $logDir ) || mkdir( $logDir, 0755, true ) || file_exists( $logDir );
        $logEntry = '[' . date( 'Y-m-d H:i:s' ) . '] Import produktu #' . $productId . ' → #' . $newProductId . "\n"
            . '  Domain: ' . $domainRaw . "\n"
            . '  Obrazy źródłowe: ' . count( $images ?: [] ) . "\n";
        foreach ( $importLog as $line ) {
            $logEntry .= '  ' . $line . "\n";
        }
        // Zawsze loguj do error_log (niezależnie od uprawnień do pliku)
        error_log( '[shopPRO shoppro-import] ' . str_replace( "\n", ' | ', $logEntry ) );

        if ( $mkdirOk && file_put_contents( $logFile, $logEntry, FILE_APPEND ) === false ) {
            error_log( '[shopPRO shoppro-import] WARN: nie można zapisać logu do: ' . $logFile );
        } elseif ( !$mkdirOk ) {
            error_log( '[shopPRO shoppro-import] WARN: nie można utworzyć katalogu: ' . $logDir );
        }

        // Zbuduj czytelny komunikat z wynikiem importu zdjęć
        $imgCount = count( $images ?: [] );
        if ( $imgCount === 0 ) {
            $imgSummary = 'Zdjęcia: brak w bazie źródłowej.';
        } else {
            $ok    = 0;
            $errors = [];
            foreach ( $importLog as $line ) {
                if ( strncmp( $line, '[OK]', 4 ) === 0 ) {
                    $ok++;
                } else {
                    $errors[] = $line;
                }
            }
            $imgSummary = 'Zdjęcia: ' . $ok . '/' . $imgCount . ' zaimportowanych.';
            if ( !empty( $errors ) ) {
                $imgSummary .= ' Błędy: ' . implode( '; ', $errors );
            }
        }

        return [ 'success' => true, 'message' => 'Produkt został zaimportowany. ' . $imgSummary ];
    }

    private function missingShopproSetting( array $settings, array $requiredKeys ): ?string
    {
        foreach ( $requiredKeys as $requiredKey ) {
            if ( trim( (string)($settings[$requiredKey] ?? '') ) === '' ) {
                return $requiredKey;
            }
        }

        return null;
    }

    private function shopproDb( array $settings ): \medoo
    {
        return new \medoo( [
            'database_type' => 'mysql',
            'database_name' => $settings['db_name'],
            'server'        => $settings['db_host'],
            'username'      => $settings['db_user'],
            'password'      => $settings['db_password'] ?? '',
            'charset'       => 'utf8'
        ] );
    }

}
