<?php
namespace PrimeLink\Modules\Downloads;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class DownloadImportService {
    /**
     * Find an existing download by product ID and file name/ID
     * 
     * @param array $download_data Download data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return array Array with product_id and download key, or empty array if not found
     */
    public static function find_existing_download( $download_data, $match_by, $batch_lookups = null ) {
        $match_by = (string) $match_by;
        
        // Product ID is required
        if ( empty( $download_data['product_id'] ) ) {
            return array();
        }
        
        $product_id = absint( $download_data['product_id'] );
        $product = wc_get_product( $product_id );
        
        if ( ! $product || ! $product->is_downloadable() ) {
            return array();
        }
        
        $existing_downloads = $product->get_downloads();
        
        if ( empty( $existing_downloads ) ) {
            return array();
        }
        
        // Match by file name
        if ( $match_by === 'file_name' && ! empty( $download_data['file_name'] ) ) {
            $file_name = sanitize_text_field( $download_data['file_name'] );
            foreach ( $existing_downloads as $key => $download ) {
                if ( $download->get_name() === $file_name ) {
                    return array(
                        'product_id' => $product_id,
                        'download_key' => $key,
                    );
                }
            }
        }
        
        // Match by file URL
        if ( $match_by === 'file_url' && ! empty( $download_data['file_url'] ) ) {
            $file_url = esc_url_raw( $download_data['file_url'] );
            foreach ( $existing_downloads as $key => $download ) {
                if ( $download->get_file() === $file_url ) {
                    return array(
                        'product_id' => $product_id,
                        'download_key' => $key,
                    );
                }
            }
        }
        
        // Match by download ID (if provided)
        if ( $match_by === 'download_id' && ! empty( $download_data['download_id'] ) ) {
            $download_id = sanitize_text_field( $download_data['download_id'] );
            if ( isset( $existing_downloads[ $download_id ] ) ) {
                return array(
                    'product_id' => $product_id,
                    'download_key' => $download_id,
                );
            }
        }
        
        return array();
    }

    /**
     * Add or update a downloadable file for a product
     */
    public static function add_or_update_download( $download_data, $import_id = 0 ) {
        // Product ID is required
        if ( empty( $download_data['product_id'] ) ) {
            return false;
        }
        
        $product_id = absint( $download_data['product_id'] );
        $product = wc_get_product( $product_id );
        
        if ( ! $product ) {
            \PrimeLink\Helpers\LoggerHelper::error(
                'Download Import Error: Product not found',
                array( 'product_id' => $product_id )
            );
            return false;
        }
        
        // File URL is required
        if ( empty( $download_data['file_url'] ) ) {
            \PrimeLink\Helpers\LoggerHelper::error(
                'Download Import Error: File URL is required',
                array( 'product_id' => $product_id )
            );
            return false;
        }
        
        // Get existing downloads
        $downloads = $product->get_downloads();
        
        // Generate download key (use provided download_id or generate new)
        $download_key = ! empty( $download_data['download_id'] ) 
            ? sanitize_key( $download_data['download_id'] ) 
            : md5( $download_data['file_url'] . time() );
        
        // Ensure unique key
        $original_key = $download_key;
        $counter = 1;
        while ( isset( $downloads[ $download_key ] ) ) {
            $download_key = $original_key . '_' . $counter;
            $counter++;
        }
        
        // Create download object
        $download = new \WC_Product_Download();
        $download->set_name( ! empty( $download_data['file_name'] ) ? sanitize_text_field( $download_data['file_name'] ) : basename( $download_data['file_url'] ) );
        $download->set_file( esc_url_raw( $download_data['file_url'] ) );
        
        // Add download to product
        $downloads[ $download_key ] = $download;
        $product->set_downloads( $downloads );
        
        // Set download limit
        if ( isset( $download_data['download_limit'] ) ) {
            $limit = absint( $download_data['download_limit'] );
            if ( $limit > 0 ) {
                update_post_meta( $product_id, '_download_limit', $limit );
            } else {
                delete_post_meta( $product_id, '_download_limit' );
            }
        }
        
        // Set download expiry
        if ( isset( $download_data['download_expiry'] ) ) {
            $expiry = absint( $download_data['download_expiry'] );
            if ( $expiry > 0 ) {
                update_post_meta( $product_id, '_download_expiry', $expiry );
            } else {
                delete_post_meta( $product_id, '_download_expiry' );
            }
        }
        
        // Ensure product is marked as downloadable
        $product->set_downloadable( 'yes' );
        
        // Save product
        $product->save();
        
        // Store import tracking
        if ( $import_id > 0 ) {
            update_post_meta( $product_id, '_mt_primelink_download_import_id', absint( $import_id ) );
        }
        
        return true;
    }

    /**
     * Update an existing downloadable file
     */
    public static function update_download( $product_id, $download_key, $download_data, $update_fields = array() ) {
        $product = wc_get_product( $product_id );
        if ( ! $product ) {
            return false;
        }
        
        $downloads = $product->get_downloads();
        
        if ( ! isset( $downloads[ $download_key ] ) ) {
            return false;
        }
        
        $update_all = empty( $update_fields ) || in_array( 'all', $update_fields, true );
        $download = $downloads[ $download_key ];
        
        // Update file name
        if ( ( $update_all || in_array( 'name', $update_fields, true ) ) && isset( $download_data['file_name'] ) ) {
            $download->set_name( sanitize_text_field( $download_data['file_name'] ) );
        }
        
        // Update file URL
        if ( ( $update_all || in_array( 'url', $update_fields, true ) ) && isset( $download_data['file_url'] ) ) {
            $download->set_file( esc_url_raw( $download_data['file_url'] ) );
        }
        
        $downloads[ $download_key ] = $download;
        $product->set_downloads( $downloads );
        
        // Update download limit
        if ( ( $update_all || in_array( 'limit', $update_fields, true ) ) && isset( $download_data['download_limit'] ) ) {
            $limit = absint( $download_data['download_limit'] );
            if ( $limit > 0 ) {
                update_post_meta( $product_id, '_download_limit', $limit );
            } else {
                delete_post_meta( $product_id, '_download_limit' );
            }
        }
        
        // Update download expiry
        if ( ( $update_all || in_array( 'expiry', $update_fields, true ) ) && isset( $download_data['download_expiry'] ) ) {
            $expiry = absint( $download_data['download_expiry'] );
            if ( $expiry > 0 ) {
                update_post_meta( $product_id, '_download_expiry', $expiry );
            } else {
                delete_post_meta( $product_id, '_download_expiry' );
            }
        }
        
        $product->save();
        
        return true;
    }

    /**
     * Remove a downloadable file from a product
     */
    public static function remove_download( $product_id, $download_key ) {
        $product = wc_get_product( $product_id );
        if ( ! $product ) {
            return false;
        }
        
        $downloads = $product->get_downloads();
        
        if ( isset( $downloads[ $download_key ] ) ) {
            unset( $downloads[ $download_key ] );
            $product->set_downloads( $downloads );
            
            // If no downloads left, mark product as non-downloadable
            if ( empty( $downloads ) ) {
                $product->set_downloadable( 'no' );
            }
            
            $product->save();
            return true;
        }
        
        return false;
    }

    /**
     * Prepare batch lookups for downloads
     */
    public static function prepare_batch_lookups( $rows, $headers, $mapping, $match_by ) {
        $lookups = array(
            'downloads_by_product_file_name' => array(),
            'downloads_by_product_file_url' => array(),
        );
        
        if ( empty( $rows ) || empty( $mapping ) ) {
            return $lookups;
        }
        
        // Extract product IDs and file names/URLs from the batch
        $product_file_pairs = array();
        
        foreach ( $rows as $row ) {
            $item = array();
            foreach ( $headers as $idx => $header ) {
                $item[ $header ] = $row[ $idx ] ?? '';
            }
            
            // Try to get product_id and file_name/file_url from mapped data
            $product_id = null;
            $file_name = null;
            $file_url = null;
            
            foreach ( $mapping as $column_config ) {
                if ( is_string( $column_config ) ) {
                    $column_config = array( 'source' => $column_config );
                }
                $source = $column_config['source'] ?? '';
                
                if ( $source === 'product_id' && ! empty( $item[ $source ] ) ) {
                    $product_id = absint( $item[ $source ] );
                }
                if ( $source === 'file_name' && ! empty( $item[ $source ] ) ) {
                    $file_name = sanitize_text_field( $item[ $source ] );
                }
                if ( $source === 'file_url' && ! empty( $item[ $source ] ) ) {
                    $file_url = esc_url_raw( $item[ $source ] );
                }
            }
            
            if ( $product_id ) {
                if ( $file_name && $match_by === 'file_name' ) {
                    if ( ! isset( $lookups['downloads_by_product_file_name'][ $product_id ] ) ) {
                        $lookups['downloads_by_product_file_name'][ $product_id ] = array();
                    }
                    $lookups['downloads_by_product_file_name'][ $product_id ][] = $file_name;
                }
                if ( $file_url && $match_by === 'file_url' ) {
                    if ( ! isset( $lookups['downloads_by_product_file_url'][ $product_id ] ) ) {
                        $lookups['downloads_by_product_file_url'][ $product_id ] = array();
                    }
                    $lookups['downloads_by_product_file_url'][ $product_id ][] = $file_url;
                }
            }
        }
        
        // Batch lookup downloads
        foreach ( $lookups['downloads_by_product_file_name'] as $product_id => $file_names ) {
            $product = wc_get_product( $product_id );
            if ( $product && $product->is_downloadable() ) {
                $downloads = $product->get_downloads();
                foreach ( $downloads as $key => $download ) {
                    $name = $download->get_name();
                    if ( in_array( $name, $file_names, true ) ) {
                        if ( ! isset( $lookups['downloads_by_product_file_name'][ $product_id ][ $name ] ) ) {
                            $lookups['downloads_by_product_file_name'][ $product_id ][ $name ] = array();
                        }
                        $lookups['downloads_by_product_file_name'][ $product_id ][ $name ] = $key;
                    }
                }
            }
        }
        
        foreach ( $lookups['downloads_by_product_file_url'] as $product_id => $file_urls ) {
            $product = wc_get_product( $product_id );
            if ( $product && $product->is_downloadable() ) {
                $downloads = $product->get_downloads();
                foreach ( $downloads as $key => $download ) {
                    $url = $download->get_file();
                    if ( in_array( $url, $file_urls, true ) ) {
                        if ( ! isset( $lookups['downloads_by_product_file_url'][ $product_id ][ $url ] ) ) {
                            $lookups['downloads_by_product_file_url'][ $product_id ][ $url ] = array();
                        }
                        $lookups['downloads_by_product_file_url'][ $product_id ][ $url ] = $key;
                    }
                }
            }
        }
        
        return $lookups;
    }
}

