<?php

namespace Meliconnect\Meliconnect\Modules\Exporter\Controllers;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Interfaces\ControllerInterface;
use Meliconnect\Meliconnect\Core\Models\Process;
use Meliconnect\Meliconnect\Core\Models\ProcessItems;
use Meliconnect\Meliconnect\Core\Models\UserConnection;
use Meliconnect\Meliconnect\Modules\Exporter\Models\ProductToExport;
use Meliconnect\Meliconnect\Modules\Exporter\Services\ExportProductsTable;

class ExportController implements ControllerInterface {

	public function __construct() {
	}

	public function getData() {
		$data             = array();
		$process          = Process::getCurrentProcessData( 'custom-export' );
		$process_finished = Process::getCurrentProcessData( 'custom-export', 'finished' );

		$data = array(
            'sellers_exceeding_limit'       => UserConnection::getSellersExceedingLimit(),
			'export_process_finished'       => $process_finished,
			'export_process_data'           => $process,
			'execution_time'                => Process::calculateExecutionTime( $process ),
			'products_to_export_count'      => ProductToExport::count_products_to_export(),
			'woo_total_active_products'     => Helper::get_woo_active_products_count(),
			'woo_total_vinculated_products' => count( Helper::getProductsWithMeta( 'meliconnect_meli_listing_id' ) ),
		);

		return $data;
	}

    public static function handleSaveDefaultSeller() {
        check_ajax_referer('meliconnect_nonce', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error();
        }

        $seller_id = sanitize_text_field($_POST['seller_id'] ?? '');

        update_option('meliconnect_default_seller_id', $seller_id);

        wp_send_json_success();
    }



	/* START HANDLE AJAX METHODS */
    /* public static function handleFillExportProductsTable() {
        
        check_ajax_referer('fill_products_nonce', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('No permissions');
        }

        // Reset flag
        update_option('meliconnect_products_filled','0');


        wp_send_json_success();
    } */

    public static function handleFillProductsStep() {

        check_ajax_referer('fill_products_nonce','nonce');

        if(!current_user_can('manage_woocommerce')){
            wp_send_json_error('No permissions');
        }

        $offset = intval($_POST['offset'] ?? 0);
        $limit  = 500;

        if ($offset === 0) {
            ProductToExport::truncate_table();
        }

        // Total de productos (una vez)
        $total = Helper::get_woo_active_products_count();

        if(!$total){
            wp_send_json_success([
                'finished' => true,
                'progress' => 100
            ]);
        }

        // Traer batch
        $products = Helper::get_woo_active_products($limit, $offset);
        

        if(empty($products)){

            update_option('meliconnect_products_filled','1');

            wp_send_json_success([
                'finished' => true,
                'progress' => 100
            ]);
        }

        // Procesar
        ProductToExport::fill_products_table($products);

        // Calcular progreso
        $processed = min($offset + $limit, $total);

        $progress = round(($processed / $total) * 100);

        wp_send_json_success([
            'finished'    => false,
            'next_offset' => $offset + $limit,
            'progress'    => $progress,
            'processed'   => $processed,
            'total'       => $total
        ]);
    }

    

	public static function handleCancelCustomExport() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'cancel_custom_export_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$process_id = isset( $_POST['process_id'] ) ? sanitize_text_field( wp_unslash( $_POST['process_id'] ) ) : null;

		if ( ! $process_id ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
			return;
		}

		update_option( 'meliconnect_export_cancel_requested', true );

		sleep( 2 );

		Process::cancelProcess( $process_id );

		// unlock custom export process cron
		delete_option( 'meliconnect_custom_export_lock' );

		wp_send_json_success();
	}

	public static function handleBulkExportAction() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'export_bulk_action_nonce' ) ) {
			Helper::logData( 'Invalid nonce', 'bulk-actions-export' );
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			Helper::logData( 'Permission denied', 'bulk-actions-export' );
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$selected_ids = isset( $_POST['products_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['products_ids'] ) ) : '';
		$action       = isset( $_POST['action_to_do'] ) ? sanitize_text_field( wp_unslash( $_POST['action_to_do'] ) ) : '';

		if ( ! $selected_ids || ! $action || $action == -1 ) {
			Helper::logData( 'Invalid data: missing selected_ids or action', 'bulk-actions-export' );
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
		}

		$selected_ids_arr = explode( ',', $selected_ids );
		Helper::logData( 'Processing action: ' . $action, 'bulk-actions-export' );
		Helper::logData( 'Selected IDs: ' . implode( ',', $selected_ids_arr ), 'bulk-actions-export' );

		switch ( $action ) {
			case 'export-selected':
				Helper::logData( 'Initiating export process', 'bulk-actions-export' );
				self::initExportProcess( $selected_ids_arr );
				break;

			case 'desvinculate-products':
			case 'desvinculate-products-and-pause':
			case 'desvinculate-products-and-delete':
				$deleting   = ( $action == 'desvinculate-products-and-delete' );
				$pausing    = ( $action == 'desvinculate-products-and-pause' );
				$new_status = $pausing ? 'paused' : ( $deleting ? 'closed' : '' );

				Helper::logData( 'Unlinking listings', 'bulk-actions-export' );
				Helper::logData( 'Deleting: ' . ( $deleting ? 'yes' : 'no' ), 'bulk-actions-export' );
				Helper::logData( 'Pausing: ' . ( $pausing ? 'yes' : 'no' ), 'bulk-actions-export' );

				foreach ( $selected_ids_arr as $woo_product_id ) {
					$update_status = false;

					if ( ! empty( $new_status ) ) {
						// Actualizar el estado del producto en MercadoLibre
						$update_status = self::updateListingStatus( $woo_product_id, $new_status );

						if ( $update_status ) {
							Helper::logData( "Product {$woo_product_id} status updated to {$new_status}", 'bulk-actions-export' );
						} else {
							Helper::logData( "Failed to update status for product {$woo_product_id}", 'bulk-actions-export' );
						}
					}

					// Solo desvincula si no se requiere cambio de estado o si el estado se actualizó correctamente
					if ( empty( $new_status ) || $update_status ) {
						Helper::unlinkProduct( $woo_product_id );
						ProductToExport::unlink_woo_product( $woo_product_id );
						Helper::logData( "Successfully unlinked product {$woo_product_id} from WooCommerce", 'bulk-actions-export' );
					} else {
						Helper::logData( "Failed to unlink product {$woo_product_id} in WooCommerce due to status update failure", 'bulk-actions-export' );
					}
				}
				break;

			default:
				Helper::logData( 'Unknown action', 'bulk-actions-export' );
				break;
		}

		wp_send_json_success( array( 'message' => 'Bulk action processed successfully.' ) );
	}


	private static function updateListingStatus( $woo_product_id, string $status ) {
		$updated_status = Helper::change_meli_listing_status( $woo_product_id, $status );

		if ( ! $updated_status ) {
			Helper::logData( "Error updating listing status: {$status} for product {$woo_product_id}", 'bulk-actions-export' );
			return false;
		} else {
			Helper::logData( "Updated listing status for product {$woo_product_id} to {$status}", 'bulk-actions-export' );
			return true;
		}
	}

	public static function initExportProcess( $products_ids = array() ) {

        $items = ProductToExport::get_products_to_export( $products_ids );

        $default_seller_id = get_option('meliconnect_default_seller_id', '');


        if ( empty( $items ) ) {
            return false;
        }

        $formatedItems = array();

        foreach ( $items as $item ) {
            $meli_user_id = !empty($item->meli_seller_id) ? $item->meli_seller_id : $default_seller_id;

            $formatedItems[] = array(
                'meli_user_id'    => $meli_user_id,
                'meli_listing_id' => $item->vinculated_listing_id,
                'woo_product_id'  => $item->woo_product_id,
                'template_id'     => $item->vinculated_template_id,
                'process_status'  => 'pending',
            );
        }

        $process_id = Process::createProcess( 'custom-export', $formatedItems );

        if ( ! $process_id ) {
            return false;
        }

        $woo_product_ids = array_column( $items, 'woo_product_id' );
        ProductToExport::update_product_to_export_status( $woo_product_ids, 'processing' );

        // Limpiar flag de cancelación
        delete_option( 'meliconnect_export_cancel_requested' );

        /**
         * DISPARAR EXPORT
         */
        wp_schedule_single_event(
            time(),
            'meliconnect_process_user_custom_export',
            [$process_id]
        );

        return true;
    }

	public static function handleDesvinculateListing() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'desvinculate_product_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$wooProductId = isset( $_POST['wooProductId'] ) ? sanitize_text_field( wp_unslash( $_POST['wooProductId'] ) ) : '';

		if ( ! $wooProductId ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
		}

		Helper::unlinkProduct( $wooProductId );

		wp_send_json_success( array( 'message' => esc_html__( 'Product desvinculated successfully.', 'meliconnect' ) ) );
	}

	public static function handleCleanCustomExportProcess() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'clean_custom_export_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$process_id = isset( $_POST['processId'] ) ? sanitize_text_field( wp_unslash( $_POST['processId'] ) ) : '';

		if ( ! $process_id ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
		}

		ProcessItems::deleteItems( $process_id );

		$deleted = Process::cancelFinishedProcesses( 'custom-export' );

		if ( ! $deleted ) {
			wp_send_json_error();
		}

		ProductToExport::update_product_to_export_status( 'all', 'pending', '' );

		// unlock custom import process cron
		delete_option( 'meliconnect_custom_export_lock' );

		wp_send_json_success();
	}



	/* START CUSTOM METHODS */
}
