<?php
namespace PrimeLink\Modules\Imports\DataSources;

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

final class ExistingFileSource implements DataSourceInterface {

    public function handle( array $payload ) {
        $path = isset( $payload['path'] ) ? sanitize_text_field( $payload['path'] ) : '';
        if ( ! $path ) {
            return array( 'error' => 'File path is required.' );
        }

        $upload_dir = wp_upload_dir();
        $base_dir   = trailingslashit( $upload_dir['basedir'] );

        // Store original path for error messages
        $original_path = $path;

        // Convert relative path (e.g., /wp-content/uploads/primelink/file.csv) to absolute path
        if ( 0 === strpos( $path, '/wp-content/uploads/' ) ) {
            $path = str_replace( '/wp-content/uploads/', $base_dir, $path );
        } elseif ( 0 === strpos( $path, 'wp-content/uploads/' ) ) {
            $path = $base_dir . str_replace( 'wp-content/uploads/', '', $path );
        } elseif ( 0 === strpos( $path, 'uploads/' ) ) {
            $path = $base_dir . str_replace( 'uploads/', '', $path );
        } elseif ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $path ) && 0 !== strpos( $path, $base_dir ) ) {
            // If it's not already an absolute path, try to construct it
            $path = $base_dir . ltrim( $path, '/' );
        }

        // Normalize path separators
        $path = str_replace( array( '/', '\\' ), DIRECTORY_SEPARATOR, $path );
        
        // Try realpath first, but if it fails, use the normalized path
        $resolved_path = realpath( $path );
        if ( $resolved_path !== false ) {
            $path = $resolved_path;
        }

        if ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $path ) ) {
            return array( 'error' => 'File not found: ' . esc_html( $original_path ) );
        }

        // Normalize base_dir for comparison
        $base_dir_normalized = realpath( $base_dir );
        if ( $base_dir_normalized === false ) {
            $base_dir_normalized = rtrim( str_replace( array( '/', '\\' ), DIRECTORY_SEPARATOR, $base_dir ), DIRECTORY_SEPARATOR );
        } else {
            $base_dir_normalized = rtrim( $base_dir_normalized, DIRECTORY_SEPARATOR );
        }
        
        // Normalize the file path for comparison
        $path_normalized = rtrim( str_replace( array( '/', '\\' ), DIRECTORY_SEPARATOR, $path ), DIRECTORY_SEPARATOR );

        // Security: allow only files inside uploads directory
        // Use case-insensitive comparison on Windows
        $comparison_base = $base_dir_normalized;
        $comparison_path = $path_normalized;
        if ( DIRECTORY_SEPARATOR === '\\' ) {
            // Windows: case-insensitive comparison
            $comparison_base = strtolower( $comparison_base );
            $comparison_path = strtolower( $comparison_path );
        }

        if ( 0 !== strpos( $comparison_path, $comparison_base ) ) {
            return array( 'error' => 'Invalid file location. File must be inside uploads directory.' );
        }

        $rel_url = str_replace( $base_dir, trailingslashit( $upload_dir['baseurl'] ), $path );

        return array(
            'path'          => $path,
            'url'           => $rel_url,
            'type'          => strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ),
            'original_name' => basename( $path ),
        );
    }
}