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

class SIMPINBY_Ajax {

  public function __construct() {
    add_action("wp_ajax_simpinby_search_customers", [$this, "search_customers"]);
    add_action("wp_ajax_simpinby_search_products", [$this, "search_products"]);
  }

 public function search_customers() {
    
      check_ajax_referer( 'simpinby_ajax_nonce', 'nonce' );

      if ( ! current_user_can("manage_options") ) {
          wp_send_json_error(['message' => 'Unauthorized']);
      }

      global $wpdb;

      $q = isset($_POST["q"])
          ? sanitize_text_field( wp_unslash($_POST["q"]) )
          : "";

      if ( strlen($q) < 2 ) {
          wp_send_json_success([]);
      }

      $table = $wpdb->prefix . "simpinby_customers";

      $like = "%" . $wpdb->esc_like($q) . "%";

      $rows = $wpdb->get_results(
          $wpdb->prepare(
              "SELECT id, name, phone, email, address 
              FROM $table 
              WHERE name LIKE %s OR phone LIKE %s 
              LIMIT 10",
              $like,
              $like
          ),
          ARRAY_A
      );

      wp_send_json_success($rows);
  }




  public function search_products() {
      check_ajax_referer( 'simpinby_ajax_nonce', 'nonce' );

      if ( ! current_user_can("manage_options") ) {
          wp_send_json_error(['message' => 'Unauthorized']);
      }

      global $wpdb;

      $q = isset($_POST["q"])
          ? sanitize_text_field( wp_unslash($_POST["q"]) )
          : "";

      if ( strlen($q) < 2 ) {
          wp_send_json_success([]);
      }

      $table = $wpdb->prefix . "simpinby_products";

      $like = "%" . $wpdb->esc_like($q) . "%";

      $rows = $wpdb->get_results(
          $wpdb->prepare(
              "SELECT id, name 
              FROM $table 
              WHERE name LIKE %s 
              LIMIT 10",
              $like
          ),
          ARRAY_A
      );

      wp_send_json_success($rows);
  }

}
