<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Handles AJAX requests related to Searching (products, customers).
 */
class KNSDD_Ajax_Search {

    public function __construct() {
        add_action( 'wp_ajax_knsdd_search_products', [ $this, 'search_products' ] );
        add_action( 'wp_ajax_knsdd_search_customers', [ $this, 'search_customers' ] );
        add_action( 'wp_ajax_knsdd_get_products_by_ids', [ $this, 'get_products_by_ids' ] );
    }

    private function check_permissions() {
        check_ajax_referer( 'knsdd_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __( 'Yetkiniz yok.', 'kns-dynamic-discounts-for-woocommerce' ) ], 403 );
        }
    }

    public function search_products() {
        $this->check_permissions();
        $search_term = isset( $_REQUEST['q'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['q'] ) ) : '';
        $category_id = isset( $_REQUEST['category'] ) ? absint( $_REQUEST['category'] ) : 0;

        // Performans: sadece ID'leri çek, sayım yapma, sonuçları sınırlı tut
        $MAX_RESULTS = 50;
        $args = [
            'post_type'        => 'product',
            'post_status'      => 'publish',
            'posts_per_page'   => $MAX_RESULTS,
            's'                => $search_term,
            'fields'           => 'ids',
            'no_found_rows'    => true,
            'suppress_filters' => false,
        ];
        if ( $category_id > 0 ) {
            $args['tax_query'] = [
                [
                    'taxonomy' => 'product_cat',
                    'field'    => 'term_id',
                    'terms'    => $category_id,
                ],
            ];
        }

        // Relevance-first ordering: Başta eşleşen > kelime sınırında > herhangi bir yerde > diğerleri
        // Yalnızca bu sorgu sırasında etkin olacak posts_orderby filtresi (global etki bırakmadan kaldırılır)
        $orderby_filter = null;
        if ( $search_term !== '' ) {
            global $wpdb;
            // Çok dilli ortamlarda boşluk normalizasyonu: birden fazla boşluğu tek boşluğa indir
            $normalized = trim( preg_replace( '/\s+/u', ' ', $search_term ) );
            $parts      = preg_split( '/\s+/u', $normalized, -1, PREG_SPLIT_NO_EMPTY );
            if ( empty( $parts ) ) { $parts = [ $normalized ]; }

            // Başlangıçtan çoklu token eşleşmesi (token1%token2%...%)
            $first_like   = $wpdb->esc_like( $parts[0] );
            $phrase_start = $first_like; // başlangıçta ilk token
            for ( $i = 1; $i < count( $parts ); $i++ ) {
                $phrase_start .= '%' . $wpdb->esc_like( $parts[$i] );
            }
            $phrase_start .= '%';

            // Kelime sınırı: ilk token için boşluk/tire/parantez önceliği
            $word1 = '% ' . $first_like . '%';
            $word2 = '%-' . $first_like . '%';
            $word3 = '%(' . $first_like . '%';

            // Herhangi bir yerde çoklu token sırası (NBSP vb. aradaki karakterler için esnek)
            $phrase_any = '%' . $phrase_start; // başına % koyarak "her yerde" yap

            $orderby_filter = function( $orderby, $q ) use ( $wpdb, $phrase_start, $word1, $word2, $word3, $phrase_any ) {
                $order = $wpdb->prepare(
                    "CASE\n                        WHEN {$wpdb->posts}.post_title LIKE %s THEN 0\n                        WHEN {$wpdb->posts}.post_title LIKE %s THEN 1\n                        WHEN {$wpdb->posts}.post_title LIKE %s THEN 1\n                        WHEN {$wpdb->posts}.post_title LIKE %s THEN 1\n                        WHEN {$wpdb->posts}.post_title LIKE %s THEN 2\n                        ELSE 3\n                    END, {$wpdb->posts}.post_title ASC",
                    $phrase_start, $word1, $word2, $word3, $phrase_any
                );
                return $order;
            };
            add_filter( 'posts_orderby', $orderby_filter, 10, 2 );
        }

        $query   = new WP_Query( $args );
        $results = [];
        $count   = 0;

        if ( ! empty( $query->posts ) && is_array( $query->posts ) ) {
            foreach ( $query->posts as $product_id ) {
                if ( $count >= $MAX_RESULTS ) {
                    break;
                }
                $product = wc_get_product( $product_id );
                if ( ! $product ) {
                    continue;
                }
                // Ana ürünü ekle (thumb + sku + stok durumu + adet)
                $img_id = method_exists( $product, 'get_image_id' ) ? $product->get_image_id() : 0;
                $thumb  = $img_id ? wp_get_attachment_image_url( $img_id, 'thumbnail' ) : '';
                $sku    = method_exists( $product, 'get_sku' ) ? (string) $product->get_sku() : '';
                $status = method_exists( $product, 'get_stock_status' ) ? (string) $product->get_stock_status() : '';
                $mstock = method_exists( $product, 'get_manage_stock' ) ? (bool) $product->get_manage_stock() : false;
                $qty    = ( $mstock && method_exists( $product, 'get_stock_quantity' ) ) ? $product->get_stock_quantity() : null;
                $results[] = [
                    'id'            => $product_id,
                    'text'          => wp_strip_all_tags( $product->get_name(), true ),
                    'thumb'         => $thumb ? esc_url_raw( $thumb ) : '',
                    'sku'           => $sku,
                    'stock_status'  => $status,
                    'manage_stock'  => $mstock ? 1 : 0,
                    'stock_qty'     => ( $qty === null ? null : intval( $qty ) ),
                ];
                $count++;
                if ( $count >= $MAX_RESULTS ) {
                    break;
                }
                // Varyasyonları (varsa) ekle
                if ( $product->is_type( 'variable' ) ) {
                    $children = $product->get_children();
                    if ( ! empty( $children ) ) {
                        foreach ( $children as $variation_id ) {
                            if ( $count >= $MAX_RESULTS ) {
                                break;
                            }
                            $variation = wc_get_product( $variation_id );
                            if ( ! $variation ) {
                                continue;
                            }
                            if ( method_exists( $variation, 'get_status' ) && 'publish' !== $variation->get_status() ) {
                                continue;
                            }
                            $label = method_exists( $variation, 'get_formatted_name' )
                                ? $variation->get_formatted_name()
                                : $variation->get_name();
                            $v_img_id = method_exists( $variation, 'get_image_id' ) ? $variation->get_image_id() : 0;
                            $v_thumb  = $v_img_id ? wp_get_attachment_image_url( $v_img_id, 'thumbnail' ) : '';
                            $v_sku    = method_exists( $variation, 'get_sku' ) ? (string) $variation->get_sku() : '';
                            $v_status = method_exists( $variation, 'get_stock_status' ) ? (string) $variation->get_stock_status() : '';
                            $v_mstock = method_exists( $variation, 'get_manage_stock' ) ? (bool) $variation->get_manage_stock() : false;
                            $v_qty    = ( $v_mstock && method_exists( $variation, 'get_stock_quantity' ) ) ? $variation->get_stock_quantity() : null;
                            $results[] = [
                                'id'            => $variation_id,
                                'text'          => wp_strip_all_tags( $label, true ),
                                'thumb'         => $v_thumb ? esc_url_raw( $v_thumb ) : '',
                                'sku'           => $v_sku,
                                'stock_status'  => $v_status,
                                'manage_stock'  => $v_mstock ? 1 : 0,
                                'stock_qty'     => ( $v_qty === null ? null : intval( $v_qty ) ),
                            ];
                            $count++;
                        }
                    }
                }
            }
        }
        // Sadece bu sorgu için eklenen orderby filtresini kaldır
        if ( $orderby_filter ) {
            remove_filter( 'posts_orderby', $orderby_filter, 10 );
        }
        wp_reset_postdata();
        wp_send_json_success( [ 'results' => $results ] );
    }

    public function search_customers() {
        $this->check_permissions();
        $search_term = isset( $_REQUEST['q'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['q'] ) ) : '';
        
        // Boş arama terimi için erken çık
        if ( empty( $search_term ) ) {
            wp_send_json_success( [ 'results' => [] ] );
        }
        
        $args = [
            'number'         => 50,
            'fields'         => [ 'ID', 'display_name', 'user_email' ],
            'search'         => '*' . esc_attr( $search_term ) . '*',
            'search_columns' => [ 'user_login', 'user_nicename', 'user_email', 'display_name' ],
        ];
        $users = get_users( $args );
        
        // Relevance-based sorting: Baştan eşleşen > içinde geçen
        $search_lower = mb_strtolower( $search_term, 'UTF-8' );
        
        $results = [];
        foreach ( $users as $user ) {
            $display_name_lower = mb_strtolower( $user->display_name, 'UTF-8' );
            $email_lower = mb_strtolower( $user->user_email, 'UTF-8' );
            
            // Sıralama skoru hesapla
            $score = 3; // Varsayılan: en düşük öncelik
            
            // Display name baştan eşleşiyor mu?
            if ( mb_strpos( $display_name_lower, $search_lower ) === 0 ) {
                $score = 0; // En yüksek öncelik
            }
            // Email baştan eşleşiyor mu?
            elseif ( mb_strpos( $email_lower, $search_lower ) === 0 ) {
                $score = 1;
            }
            // Display name içinde geçiyor mu?
            elseif ( mb_strpos( $display_name_lower, $search_lower ) !== false ) {
                $score = 2;
            }
            // Email içinde geçiyor mu?
            elseif ( mb_strpos( $email_lower, $search_lower ) !== false ) {
                $score = 2;
            }
            
            $results[] = [
                'id'    => $user->ID,
                'text'  => sprintf( '%s (%s)', $user->display_name, $user->user_email ),
                'score' => $score,
                'name'  => $display_name_lower, // Sıralama için
            ];
        }
        
        // Önce score'a göre, sonra isme göre sırala
        usort( $results, function( $a, $b ) {
            if ( $a['score'] !== $b['score'] ) {
                return $a['score'] - $b['score']; // Düşük score = yüksek öncelik
            }
            return strcmp( $a['name'], $b['name'] ); // Alfabetik
        });
        
        // Sıralama için kullanılan alanları temizle
        foreach ( $results as &$result ) {
            unset( $result['score'], $result['name'] );
        }
        
        wp_send_json_success( [ 'results' => $results ] );
    }

    /**
     * Get products by IDs for Select2 pre-population
     * Used when editing existing rules with selected products
     */
    public function get_products_by_ids() {
        $this->check_permissions();
        
        $ids = isset( $_REQUEST['ids'] ) ? (array) $_REQUEST['ids'] : [];
        $ids = array_filter( array_map( 'absint', $ids ) );
        
        if ( empty( $ids ) ) {
            wp_send_json_success( [ 'results' => [] ] );
        }
        
        $results = [];
        foreach ( $ids as $product_id ) {
            $product = wc_get_product( $product_id );
            if ( ! $product ) {
                continue;
            }
            
            $img_id = method_exists( $product, 'get_image_id' ) ? $product->get_image_id() : 0;
            $thumb  = $img_id ? wp_get_attachment_image_url( $img_id, 'thumbnail' ) : '';
            $sku    = method_exists( $product, 'get_sku' ) ? (string) $product->get_sku() : '';
            $status = method_exists( $product, 'get_stock_status' ) ? (string) $product->get_stock_status() : '';
            $mstock = method_exists( $product, 'get_manage_stock' ) ? (bool) $product->get_manage_stock() : false;
            $qty    = ( $mstock && method_exists( $product, 'get_stock_quantity' ) ) ? $product->get_stock_quantity() : null;
            
            // Ürün kategorilerini al
            $category_ids = wc_get_product_term_ids( $product_id, 'product_cat' );
            
            $results[] = [
                'id'            => $product_id,
                'text'          => wp_strip_all_tags( $product->get_name(), true ),
                'thumb'         => $thumb ? esc_url_raw( $thumb ) : '',
                'sku'           => $sku,
                'stock_status'  => $status,
                'manage_stock'  => $mstock ? 1 : 0,
                'stock_qty'     => ( $qty === null ? null : intval( $qty ) ),
                'categories'    => $category_ids,
            ];
        }
        
        wp_send_json_success( [ 'results' => $results ] );
    }
}
