<?php
namespace FuseCommerce\Controllers;
if ( ! defined( 'ABSPATH' ) ) exit;

use FuseCommerce\Jobs\IndexProducts;
use FuseCommerce\Services\ProductIndexerService;
use FuseCommerce\Services\ProductSerializerService;
use FuseCommerce\Services\CategoryIndexerService;
use FuseCommerce\Services\AttributeIndexerService;
use FuseCommerce\Services\TagIndexerService;
use FuseCommerce\Services\FileStorageService;
use FuseCommerce\Repositories\ProductRepository;

class ProductsCtrl {

    static function indexProducts() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'fusecomm_app_settings_nonce')) {
            wp_send_json_error(['message' => esc_html__('Security check failed', 'ftlcommerce-instant-product-search')], 403);
            return;
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions', 'ftlcommerce-instant-product-search')], 403);
            return;
        }

        $indexProdJob = new IndexProducts();
        if ( $indexProdJob->canRun() ) {
            $indexProdJob->run();
            wp_send_json_success( [ 'message' => 'Indexing started' ] );
        } else {
            wp_send_json_error( [ 'message' => 'Cannot start indexing. WooCommerce may not be active.' ], 400 );
        }
    }

    /**
     * Reset the indexing process
     * AJAX handler for fuse_comm_reset_index
     */
    static function resetIndexing() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'fusecomm_app_settings_nonce' ) ) {
            wp_send_json_error( [ 'message' => esc_html__( 'Security check failed', 'ftlcommerce-instant-product-search' ) ], 403 );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => esc_html__( 'Insufficient permissions', 'ftlcommerce-instant-product-search' ) ], 403 );
            return;
        }

        // Initialize service
        $indexer_service = self::getIndexerService();

        // Reset process
        $indexer_service->resetProcess();

        wp_send_json_success( [ 'message' => 'Indexing process reset successfully' ] );
    }

    /**
     * Get indexing status
     * AJAX handler for fuse_comm_get_index_status
     */
    static function getIndexingStatus() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'fusecomm_app_settings_nonce' ) ) {
            wp_send_json_error( [ 'message' => esc_html__( 'Security check failed', 'ftlcommerce-instant-product-search' ) ], 403 );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => esc_html__( 'Insufficient permissions', 'ftlcommerce-instant-product-search' ) ], 403 );
            return;
        }

        // Initialize service
        $indexer_service = self::getIndexerService();

        // Get status
        $status = $indexer_service->getStatus();

        wp_send_json_success( $status );
    }

    /**
     * Helper method to create indexer service instance
     *
     * @return ProductIndexerService
     */
    private static function getIndexerService(): ProductIndexerService {
        $product_repository = new ProductRepository();
        $serializer         = new ProductSerializerService();
        $category_indexer   = new CategoryIndexerService( $product_repository );
        $attribute_indexer  = new AttributeIndexerService( $product_repository );
        $tag_indexer        = new TagIndexerService( $product_repository );
        $file_storage       = new FileStorageService();

        return new ProductIndexerService(
            $product_repository,
            $serializer,
            $category_indexer,
            $attribute_indexer,
            $tag_indexer,
            $file_storage
        );
    }
}