<?php
/**
 * Import AJAX endpoints.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Core\Ajax;

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

final class ImportAjax {

    public static function register() {
        add_action( 'wp_ajax_mt_primelink_import_create_draft', array( __CLASS__, 'create_draft' ) );
        add_action( 'wp_ajax_mt_primelink_import_save_step', array( __CLASS__, 'save_step' ) );
        add_action( 'wp_ajax_mt_primelink_import_load_draft', array( __CLASS__, 'load_draft' ) );
        add_action( 'wp_ajax_mt_primelink_import_handle_source', array( __CLASS__, 'handle_source' ) );
        add_action( 'wp_ajax_mt_primelink_import_preview_file', array( __CLASS__, 'preview_file' ) );
        add_action( 'wp_ajax_mt_primelink_import_get_mapping_preview', array( __CLASS__, 'get_mapping_preview' ) );
        add_action( 'wp_ajax_mt_primelink_dropbox_list', array( __CLASS__, 'dropbox_list' ) );
        
        // Export templates via AJAX (simpler than REST)
        add_action( 'wp_ajax_mt_primelink_export_list_templates', array( __CLASS__, 'export_list_templates' ) );
    }

    private static function verify() {
        check_ajax_referer( 'mt_primelink_nonce', 'nonce' );

        // Use filterable capability for AJAX actions.
        // Default to manage_woocommerce if WooCommerce is active, otherwise manage_options.
        $default_capability = class_exists( 'WooCommerce' ) ? 'manage_woocommerce' : 'manage_options';
        $capability         = apply_filters( 'mt_primelink_capability', $default_capability );
        if ( ! current_user_can( $capability ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
        }
    }

    /**
     * Create empty draft import in options (temporary store).
     * Later we move to custom DB table.
     */
    public static function create_draft() {
        self::verify();

        $drafts = get_option( 'mt_primelink_import_drafts', array() );

        $id = time(); // simple unique id for now
        $drafts[ $id ] = array(
            'created_at' => current_time( 'mysql' ),
            'step_data'  => array(),
            'current_step' => 1,
        );

        update_option( 'mt_primelink_import_drafts', $drafts, false );

        wp_send_json_success( array( 'import_id' => $id ) );
    }

    /**
     * Save wizard step data.
     */
    public static function save_step() {
        self::verify();

        $import_id = isset( $_POST['import_id'] ) ? absint( $_POST['import_id'] ) : 0;
        $step      = isset( $_POST['step'] ) ? absint( $_POST['step'] ) : 1;
        $data      = isset( $_POST['data'] ) ? (array) $_POST['data'] : array();

        if ( ! $import_id ) {
            wp_send_json_error( array( 'message' => 'Missing import_id' ), 400 );
        }

        $drafts = get_option( 'mt_primelink_import_drafts', array() );
        if ( empty( $drafts[ $import_id ] ) ) {
            wp_send_json_error( array( 'message' => 'Draft not found' ), 404 );
        }

        $drafts[ $import_id ]['step_data'][ $step ] = $data;
        $drafts[ $import_id ]['current_step'] = $step;

        update_option( 'mt_primelink_import_drafts', $drafts, false );

        wp_send_json_success( array( 'saved' => true ) );
    }

    /**
     * Load wizard draft.
     */
    public static function load_draft() {
        self::verify();

        $import_id = isset( $_GET['import_id'] ) ? absint( $_GET['import_id'] ) : 0;
        $drafts    = get_option( 'mt_primelink_import_drafts', array() );

        if ( ! $import_id || empty( $drafts[ $import_id ] ) ) {
            wp_send_json_error( array( 'message' => 'Draft not found' ), 404 );
        }

        wp_send_json_success( $drafts[ $import_id ] );
    }

    public static function handle_source() {
        self::verify();

        $import_id = isset( $_POST['import_id'] ) ? absint( $_POST['import_id'] ) : 0;
        $source    = isset( $_POST['source'] ) ? sanitize_text_field( $_POST['source'] ) : '';

        if ( ! $import_id ) {
            wp_send_json_error( array( 'message' => 'Missing import_id' ), 400 );
        }

        $drafts = get_option( 'mt_primelink_import_drafts', array() );

        // If the draft is missing (for example, the option was cleaned but the URL
        // still contains an old import_id), recreate a minimal draft on-the-fly
        // instead of failing hard. This keeps older links usable and avoids
        // confusing "Draft not found" errors for the user.
        if ( empty( $drafts[ $import_id ] ) ) {
            $drafts[ $import_id ] = array(
                'created_at'   => current_time( 'mysql' ),
                'step_data'    => array(),
                'current_step' => 2,
            );
        }

        switch ( $source ) {
        case 'desktop':
            $handler = new \PrimeLink\Modules\Imports\DataSources\DesktopUploadSource();
            $res = $handler->handle( array() );
            break;

        case 'url':
            $handler = new \PrimeLink\Modules\Imports\DataSources\UrlSource();
            $res = $handler->handle( array( 'url' => mt_primelink_get( 'url', '', 'url' ) ) );
            break;

        case 'existing':
            $handler = new \PrimeLink\Modules\Imports\DataSources\ExistingFileSource();
            $res = $handler->handle( array( 'path' => mt_primelink_get( 'path', '', 'text' ) ) );
            break;

        case 'ftp':
            $settings = get_option( 'mt_primelink_settings', array() );
            $handler = new \PrimeLink\Modules\Imports\DataSources\FtpSource( $settings );
            $test_only = isset( $_POST['test_only'] ) && $_POST['test_only'] == 1;
            $res = $handler->handle( array(
                'protocol' => mt_primelink_get( 'protocol', '', 'text' ),
                'host'     => mt_primelink_get( 'host', '', 'text' ),
                'port'     => mt_primelink_get( 'port', 0, 'int' ),
                'user'     => mt_primelink_get( 'user', '', 'text' ),
                'pass'     => mt_primelink_get( 'pass', '', 'text' ),
                'root'     => mt_primelink_get( 'root', '', 'text' ),
                'path'     => mt_primelink_get( 'path', '', 'text' ),
                'passive'  => isset( $_POST['passive'] ) ? (bool) $_POST['passive'] : null,
                'test_only' => $test_only,
            ) );
            
            // For test_only mode, return success/error directly
            if ( $test_only ) {
                if ( isset( $res['error'] ) ) {
                    wp_send_json_error( array( 'message' => $res['error'] ), 400 );
                }
                if ( isset( $res['success'] ) && $res['success'] ) {
                    wp_send_json_success( array( 
                        'data' => array( 'message' => $res['message'] ?? 'Connection successful' )
                    ) );
                }
                // If neither success nor error, treat as error
                wp_send_json_error( array( 'message' => 'Unknown error during connection test' ), 400 );
            }
            
            if ( isset( $res['file_path'] ) && empty( $res['path'] ) ) {
                $res['path'] = $res['file_path'];
            }
            if ( isset( $res['file_type'] ) && empty( $res['type'] ) ) {
                $res['type'] = $res['file_type'];
            }
            break;

        case 'dropbox':
            $settings = get_option( 'mt_primelink_settings', array() );
            $handler = new \PrimeLink\Modules\Imports\DataSources\DropboxSource( $settings );
            $res = $handler->handle( array(
                'path' => mt_primelink_get( 'path', '', 'text' ),
            ) );
            if ( isset( $res['file_path'] ) && empty( $res['path'] ) ) {
                $res['path'] = $res['file_path'];
            }
            if ( isset( $res['file_type'] ) && empty( $res['type'] ) ) {
                $res['type'] = $res['file_type'];
            }
            break;

        case 'gdrive':
            $settings = get_option( 'mt_primelink_settings', array() );
            $handler = new \PrimeLink\Modules\Imports\DataSources\GoogleDriveSource( $settings );
            $res = $handler->handle( array(
                'file' => mt_primelink_get( 'path', '', 'text' ) ?: mt_primelink_get( 'file', '', 'text' ),
            ) );
            if ( isset( $res['file_path'] ) && empty( $res['path'] ) ) {
                $res['path'] = $res['file_path'];
            }
            if ( isset( $res['file_type'] ) && empty( $res['type'] ) ) {
                $res['type'] = $res['file_type'];
            }
            break;

        case 'onedrive':
            $settings = get_option( 'mt_primelink_settings', array() );
            $handler = new \PrimeLink\Modules\Imports\DataSources\OneDriveSource( $settings );
            $res = $handler->handle( array(
                'file' => mt_primelink_get( 'path', '', 'text' ) ?: mt_primelink_get( 'file', '', 'text' ),
            ) );
            if ( isset( $res['file_path'] ) && empty( $res['path'] ) ) {
                $res['path'] = $res['file_path'];
            }
            if ( isset( $res['file_type'] ) && empty( $res['type'] ) ) {
                $res['type'] = $res['file_type'];
            }
            break;

        default:
            $res = array( 'error' => 'Source not implemented yet.' );
    }

    if ( isset( $res['error'] ) ) {
        wp_send_json_error( array( 'message' => $res['error'] ), 400 );
    }

    // Save file info into step 2 data.
    $drafts[ $import_id ]['step_data'][2]['file'] = $res;
    update_option( 'mt_primelink_import_drafts', $drafts, false );

    wp_send_json_success( array( 'file' => $res ) );
}

public static function preview_file() {
    self::verify();

    $import_id = isset( $_GET['import_id'] ) ? absint( $_GET['import_id'] ) : 0;
    $xpath     = isset( $_GET['xpath'] ) ? wp_unslash( $_GET['xpath'] ) : '';

    $drafts = get_option( 'mt_primelink_import_drafts', array() );
    if ( empty( $drafts[ $import_id ]['step_data'][2]['file']['path'] ) ) {
        wp_send_json_error( array( 'message' => 'No file for preview.' ), 404 );
    }

    $file = $drafts[ $import_id ]['step_data'][2]['file'];
    $path = $file['path'];
    $type = $file['type'];

    $parser = \PrimeLink\Modules\Imports\Parsers\ParserFactory::make( $type );
    $preview = $parser->preview( $path, array(
        'xpath' => $xpath,
        'max_rows' => 10,
    ) );

    wp_send_json_success( array(
        'type' => $type,
        'preview' => $preview,
    ) );
}

public static function get_mapping_preview() {
    self::verify();

    $import_id = isset( $_GET['import_id'] ) ? absint( $_GET['import_id'] ) : 0;
    $index     = isset( $_GET['index'] ) ? absint( $_GET['index'] ) : 0;

    $drafts = get_option( 'mt_primelink_import_drafts', array() );
    if ( empty( $drafts[ $import_id ] ) ) {
        wp_send_json_error( array( 'message' => 'Draft not found' ), 404 );
    }

    if ( empty( $drafts[ $import_id ]['step_data'][2]['file'] ) ) {
        wp_send_json_error( array( 'message' => 'No file selected.' ), 400 );
    }

    $file = $drafts[ $import_id ]['step_data'][2]['file'];

    $xpath = '';
    if ( ! empty( $drafts[ $import_id ]['step_data'][4]['xpath'] ) ) {
        $xpath = $drafts[ $import_id ]['step_data'][4]['xpath'];
    }

    $preview = \PrimeLink\Modules\Imports\Service\ImportPreview::get_mapping_preview(
        $file,
        array(
            'index' => $index,
            'xpath' => $xpath,
        )
    );

    wp_send_json_success( $preview );
}

    /**
     * List Dropbox files/folders.
     */
    public static function dropbox_list() {
        self::verify();

        $settings = get_option( 'mt_primelink_settings', array() );
        $token    = $settings['dropbox_access_token'] ?? '';
        if ( ! $token ) {
            wp_send_json_error( array( 'message' => 'Dropbox token missing. Add it in Settings → Integrations.' ), 400 );
        }

        $path = isset( $_POST['path'] ) ? sanitize_text_field( $_POST['path'] ) : '';
        // If a file path is provided, use its directory.
        if ( $path && false === strpos( $path, '://' ) ) {
            $parts = explode( '/', trim( $path, '/' ) );
            if ( count( $parts ) > 1 ) {
                array_pop( $parts );
                $path = '/' . implode( '/', $parts );
            } else {
                $path = '';
            }
        }

        $body = wp_json_encode( array(
            'path'      => $path,
            'recursive' => false,
            'limit'     => 100,
        ) );

        $response = \PrimeLink\Helpers\HttpHelper::post( 'https://api.dropboxapi.com/2/files/list_folder', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $token,
                'Content-Type'  => 'application/json',
            ),
            'body'        => json_decode( $body, true ), // HttpHelper will handle JSON encoding
            'timeout'     => 30,
            'retry'       => 1,
            'retry_delay' => 1,
        ) );

        if ( ! $response['success'] ) {
            wp_send_json_error( array( 'message' => $response['error'] ?? __( 'Failed to list Dropbox folder.', 'primelink' ) ), 400 );
        }

        $code = $response['code'];
        $data = json_decode( $response['body'], true );

        if ( $code < 200 || $code > 299 ) {
            $msg = isset( $data['error_summary'] ) ? $data['error_summary'] : 'Dropbox listing failed.';
            wp_send_json_error( array( 'message' => $msg ), 400 );
        }

        $files = array();
        if ( ! empty( $data['entries'] ) && is_array( $data['entries'] ) ) {
            foreach ( $data['entries'] as $entry ) {
                if ( isset( $entry['.tag'] ) && 'file' === $entry['.tag'] ) {
                    $size = isset( $entry['size'] ) ? (int) $entry['size'] : 0;
                    $size_human = size_format( $size, 2 );
                    $files[] = array(
                        'name'       => $entry['name'] ?? '',
                        'path'       => $entry['path_lower'] ?? ( $entry['path_display'] ?? '' ),
                        'size'       => $size,
                        'size_human' => $size_human,
                    );
                }
            }
        }

        wp_send_json_success( array( 'files' => $files ) );
    }

    /**
     * List export templates filtered by type (AJAX version, simpler than REST).
     */
    public static function export_list_templates() {
        self::verify();

        // Get type from GET or POST (AJAX can send either)
        $type = isset( $_GET['type'] ) ? sanitize_text_field( $_GET['type'] ) : '';
        if ( empty( $type ) && isset( $_POST['type'] ) ) {
            $type = sanitize_text_field( $_POST['type'] );
        }
        
        $templates = get_option( 'mt_primelink_export_templates', array() );
        if ( ! is_array( $templates ) ) {
            $templates = array();
        }
        
        $all_names = array_keys( $templates );
        
        // Filter by type if provided - STRICT filtering: only show templates with the correct prefix
        if ( ! empty( $type ) ) {
            if ( $type === 'order' ) {
                // Show ONLY templates that start with "order:"
                $names = array_filter( $all_names, function( $name ) {
                    return strpos( $name, 'order:' ) === 0;
                } );
            } elseif ( $type === 'product' ) {
                // Show ONLY templates that start with "product:" OR have no prefix at all (backward compatibility)
                // BUT exclude any that have other prefixes
                $names = array_filter( $all_names, function( $name ) {
                    $has_order = strpos( $name, 'order:' ) === 0;
                    $has_customer = strpos( $name, 'customer:' ) === 0;
                    $has_coupon = strpos( $name, 'coupon:' ) === 0;
                    $has_product = strpos( $name, 'product:' ) === 0;
                    // Include ONLY if: has product prefix OR (no prefix at all)
                    $has_category = strpos( $name, 'category:' ) === 0;
                    $has_tag = strpos( $name, 'tag:' ) === 0;
                    return $has_product || ( ! $has_order && ! $has_customer && ! $has_coupon && ! $has_product && ! $has_category && ! $has_tag );
                } );
            } elseif ( $type === 'customer' ) {
                // Show ONLY templates that start with "customer:"
                $names = array_filter( $all_names, function( $name ) {
                    return strpos( $name, 'customer:' ) === 0;
                } );
            } elseif ( $type === 'coupon' ) {
                // Show ONLY templates that start with "coupon:"
                $names = array_filter( $all_names, function( $name ) {
                    return strpos( $name, 'coupon:' ) === 0;
                } );
            } elseif ( $type === 'category' || $type === 'categories' ) {
                // Show ONLY templates that start with "category:"
                $names = array_filter( $all_names, function( $name ) {
                    return strpos( $name, 'category:' ) === 0;
                } );
            } elseif ( $type === 'tag' || $type === 'tags' ) {
                // Show ONLY templates that start with "tag:"
                $names = array_filter( $all_names, function( $name ) {
                    return strpos( $name, 'tag:' ) === 0;
                } );
            } else {
                // Unknown type, return empty array (don't show all)
                $names = array();
            }
        } else {
            // If no type specified, return all (for backward compatibility)
            $names = $all_names;
        }
        
        $names = array_values( $names );
        sort( $names );

        wp_send_json_success( array( 'templates' => $names ) );
    }
}