<?php

namespace Rtc\PlantShopWC\Admin\Helpers;

use Exception;
use Rtc\PlantShopWC\Admin\Controllers\LabelEditorController;
use Rtc\PlantShopWC\Admin\Models\GeneralSettingsModel;
use Rtc\PlantShopWC\Admin\Models\LabelEditorModel;
use Rtc\PlantShopWC\Admin\Views\Templates\EditorLabels;
use Rtc\PlantShopWC\Admin\Views\Templates\PackingList;
use WP_Query;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class AjaxHelper {
    public function __construct() {
        $this->register_route( 'plantshop-wc_get_neighbors', array($this, 'plantshop_wc_get_neighbors_action') );
    }

    private function register_route( $name, $callback ) : void {
        add_action( 'wp_ajax_' . $name, $callback );
    }

    public function plantshop_wc_get_neighbors_action() : void {
        $nonce = ( isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '' );
        if ( !wp_verify_nonce( $nonce, 'ajax-tabs-nonce' ) ) {
            wp_send_json_error( esc_html__( 'Invalid nonce!', 'plantshop-wc' ) );
            wp_die();
        }
        $title = ( isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '' );
        if ( empty( $title ) ) {
            wp_send_json_error( esc_html__( 'No title!', 'plantshop-wc' ) );
            wp_die();
        }
        $current_id = ( isset( $_POST['current_id'] ) ? absint( wp_unslash( $_POST['current_id'] ) ) : 0 );
        $query = new WP_Query(array(
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => 10,
            's'              => $title,
        ));
        $products = array();
        foreach ( $query->posts as $product ) {
            if ( (int) $product->ID === (int) $current_id ) {
                continue;
            }
            $product_info = array(
                'id'   => $product->ID,
                'name' => $product->post_title,
            );
            $products[] = $product_info;
        }
        if ( empty( $products ) ) {
            wp_send_json_error( esc_html__( 'No products found.', 'plantshop-wc' ) );
            wp_die();
        }
        wp_send_json_success( array(
            'success' => true,
            'data'    => $products,
        ) );
        wp_die();
    }

}
