[FRAMEWORK] Xây dựng page Account Phần 3 (ok)

Tab Activity to Tab Business

Tab Deal

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\inc\functions\function-global.php

<?php
/**
 *
 * @return HTML - option list tỉnh thành
 */
function reder_province_option($default = "") {
  $json_file = get_stylesheet_directory() . "/json/tinh_tp.json";
  if (file_exists($json_file)) {
    $json       = file_get_contents($json_file);
    $tinh_thanh = json_decode($json, true);
    foreach ($tinh_thanh as $key => $value) {
      if ($key == $default) {$select = "selected";} else { $select = "";}
      echo "<option " . $select . " value='" . $key . "'>" . $value["name"] . "</option>";
    }
  }
}
/**
 * @return HTML - option list quận huyện
 */
function reder_quan_huyen_option($tinh_thanh, $default) {
  $default    = sprintf('%02d', intval($default));
  $tinh_thanh = sprintf('%02d', intval($tinh_thanh));
  $json_file  = get_stylesheet_directory() . "/json/quan-huyen/" . $tinh_thanh . ".json";
  if (file_exists($json_file)) {
    $json       = file_get_contents($json_file);
    $quan_huyen = json_decode($json, true);
    foreach ($quan_huyen as $key => $value) {
      if ($key == $default) {
        $select = "selected";
      } else {
        $select = "";
      }
      echo "<option " . $select . " value='" . $key . "'>" . $value["name_with_type"] . "</option>";
    }
  }
}
/**
 * @return HTML - option list xã phường
 */
function reder_xa_phuong_option($quan_huyen, $default) {
  $default    = intval($default);
  $quan_huyen = sprintf('%03d', intval($quan_huyen));
  $json_file  = get_stylesheet_directory() . "/json/xa-phuong/" . $quan_huyen . ".json";
  if (file_exists($json_file)) {
    $json      = file_get_contents($json_file);
    $xa_phuong = json_decode($json, true);
    foreach ($xa_phuong as $key => $value) {
      if ($key == $default) {$select = "selected";} else { $select = "";}
      echo "<option " . $select . " value='" . $key . "'>" . $value["name_with_type"] . "</option>";
    }
  }
}
/**
 * AJAX load quận huyện khi select tỉnh thành phố
 */
add_action('wp_ajax_load_quan_huyen', 'load_quan_huyen');
function load_quan_huyen() {
  $tinh_thanh = $_POST['id'];
  $type       = $_POST['type'];
  $json_file  = get_stylesheet_directory() . "/json/quan-huyen/" . $tinh_thanh . ".json";
  if (file_exists($json_file)) {
    $json       = file_get_contents($json_file);
    $quan_huyen = json_decode($json, true);
    echo '<option value="" disabled selected >' . __("Select", "golf") . '</option>';
    foreach ($quan_huyen as $key => $value) {
      if ($type) {
        echo "<option value='" . $value["name_with_type"] . "'>" . $value["name_with_type"] . "</option>";
      } else {
        echo "<option value='" . $key . "'>" . $value["name_with_type"] . "</option>";
      }
    }
  }
  die();
}
/**
 * AJAX load danh sách xã phường khi select tỉnh thành phố
 */
add_action('wp_ajax_load_xa_phuong', 'load_xa_phuong');
function load_xa_phuong() {
  $quan_huyen = $_POST['id'];
  $json_file  = get_stylesheet_directory() . "/json/xa-phuong/" . $quan_huyen . ".json";
  if (file_exists($json_file)) {
    $json      = file_get_contents($json_file);
    $xa_phuong = json_decode($json, true);
    foreach ($xa_phuong as $key => $value) {
      echo "<option value='" . $key . "'>" . $value["name_with_type"] . "</option>";
    }
  }
  die();
}
/**
 *
 * Get địa chỉ của user bởi id
 * Nếu chưa update địa chỉ, thì gán mặc định là: '90 Đường Lê Lợi, Phường Bến Thành, Quận 1, Thành phố Hồ Chí Minh'
 */
function get_address_by_id_user($user_id = null) {
  if (!$user_id) {
    $user_id = get_current_user_id();
  }
  $province_address = get_user_meta($user_id, "province_address", true);
  if ($province_address) {
    return json_decode($province_address, true);
  }
  return array(
    'province' => 79,
    'district' => 760,
    'ward'     => 26743,
    'street'   => '90 Đường Lê Lợi',
  );
}
/**
 * Get địa chỉ text
 * @return array
 */
function atw_load_province_address($user_id = null) {
  $province = '';
  $district = '';
  $ward     = '';
  if (!$user_id) {
    $user_id = get_current_user_id();
  }
  $province_address = get_address_by_id_user($user_id);
  if ($province_address && is_array($province_address)) {
    $json_file = get_stylesheet_directory() . "/json/tinh_tp.json";
    if (file_exists($json_file)) {
      $json_tinh_tp = file_get_contents($json_file);
      $tinh_thanh   = json_decode($json_tinh_tp, true);
      foreach ($tinh_thanh as $key => $value) {
        if ($key == $province_address['province']) {
          $province = $tinh_thanh[$key]['name'];
          break;
        }
      }
    }
    if ($province_address['province']):
      $json_file = get_stylesheet_directory() . "/json/quan-huyen/" . $province_address['province'] . ".json";
      if (file_exists($json_file)) {
        $json_quan_huyen = file_get_contents($json_file);
        $quan_huyen      = json_decode($json_quan_huyen, true);
        foreach ($quan_huyen as $key => $value) {
          if ($key == $province_address['district']) {
            $district = $quan_huyen[$key]['name_with_type'];
            break;
          }
        }
      }
    endif;
    if ($province_address['district']):
      $json_file = get_stylesheet_directory() . "/json/xa-phuong/" . $province_address['district'] . ".json";
      if (file_exists($json_file)) {
        $json_xa_phuong = file_get_contents($json_file);
        $xa_phuong      = json_decode($json_xa_phuong, true);
        foreach ($xa_phuong as $key => $value) {
          if ($key == $province_address['ward']) {
            $ward = $xa_phuong[$key]['name_with_type'];
            break;
          }
        }
      }
    endif;
  }
  return array(
    'province' => $province,
    'district' => $district,
    'ward'     => $ward,
    'street'   => $province_address['street'],
  );
}
/**
 *
 * Crop image
 */
function resize_image($method, $image_loc, $new_loc, $width, $height) {
  $exif = exif_read_data($image_loc);
  if (isset($exif['Orientation']) && $exif['Orientation'] === 6) {
    $rotate = -90;
  } else if (isset($exif['Orientation']) && $exif['Orientation'] === 3) {
    $rotate = 180;
  } else if (isset($exif['Orientation']) && $exif['Orientation'] === 8) {
    $rotate = 90;
  }
  if (!is_array(@$GLOBALS['errors'])) {$GLOBALS['errors'] = array();}
  if (!in_array($method, array('force', 'max', 'crop'))) {$GLOBALS['errors'][] = 'Invalid method selected.';}
  if (!$image_loc) {$GLOBALS['errors'][] = 'No source image location specified.';} else {
    if ((substr(strtolower($image_loc), 0, 7) == 'http://') || (substr(strtolower($image_loc), 0, 7) == 'https://')) { /*don't check to see if file exists since it's not local*/} elseif (!file_exists($image_loc)) {$GLOBALS['errors'][] = 'Image source file does not exist.';}
    $extension = strtolower(substr($image_loc, strrpos($image_loc, '.')));
    if (!in_array($extension, array('.jpg', '.jpeg', '.png', '.gif', '.bmp'))) {$GLOBALS['errors'][] = 'Invalid source file extension!';}
  }
  if (!$new_loc) {$GLOBALS['errors'][] = 'No destination image location specified.';} else {
    $new_extension = strtolower(substr($new_loc, strrpos($new_loc, '.')));
    if (!in_array($new_extension, array('.jpg', '.jpeg', '.png', '.gif', '.bmp'))) {$GLOBALS['errors'][] = 'Invalid destination file extension!';}
  }
  $width = abs(intval($width));
  if (!$width) {$GLOBALS['errors'][] = 'No width specified!';}
  $height = abs(intval($height));
  if (!$height) {$GLOBALS['errors'][] = 'No height specified!';}
  if (count($GLOBALS['errors']) > 0) {echo_errors();return false;}
  if (in_array($extension, array('.jpg', '.jpeg'))) {$image = @imagecreatefromjpeg($image_loc);} elseif ($extension == '.png') {$image = @imagecreatefrompng($image_loc);} elseif ($extension == '.gif') {$image = @imagecreatefromgif($image_loc);} elseif ($extension == '.bmp') {$image = @imagecreatefromwbmp($image_loc);}
  if (!$image) {$GLOBALS['errors'][] = 'Image could not be generated!';} else {
    $current_width  = imagesx($image);
    $current_height = imagesy($image);
    if ((!$current_width) || (!$current_height)) {$GLOBALS['errors'][] = 'Generated image has invalid dimensions!';}
  }
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);
    echo_errors();return false;}
  if ($method == 'force') {$new_image = resize_image_force($image, $width, $height);} elseif ($method == 'max') {$new_image = resize_image_max($image, $width, $height);} elseif ($method == 'crop') {$new_image = resize_image_crop($image, $width, $height);}
  if ((!$new_image) && (count($GLOBALS['errors'] == 0))) {$GLOBALS['errors'][] = 'New image could not be generated!';}
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);
    echo_errors();return false;}
  $save_error = false;
  if (in_array($extension, array('.jpg', '.jpeg'))) {
    if (isset($rotate)) {$new_image = imagerotate($new_image, $rotate, 0);}
    imagejpeg($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.png') {
    if (isset($rotate)) {$new_image = imagerotate($new_image, $rotate, 0);}
    imagepng($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.gif') {imagegif($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.bmp') {imagewbmp($new_image, $new_loc) or ($save_error = true);}
  if ($save_error) {$GLOBALS['errors'][] = 'New image could not be saved!';}
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);@imagedestroy($new_image);
    echo_errors();return false;}
  imagedestroy($image);
  imagedestroy($new_image);
  return true;
}
function echo_errors() {
  if (!is_array(@$GLOBALS['errors'])) {$GLOBALS['errors'] = array('Unknown error!');}
  foreach ($GLOBALS['errors'] as $error) {echo '<p style="color:red;font-weight:bold;">Error: ' . $error . '</p>';}
}
function resize_image_force($image, $width, $height) {
  $w = @imagesx($image); //current width
  $h = @imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w == $width) && ($h == $height)) {return $image;} //no resizing needed
  $image2 = imagecreatetruecolor($width, $height);
  imagecopyresampled($image2, $image, 0, 0, 0, 0, $width, $height, $w, $h);
  return $image2;
}
function resize_image_max($image, $max_width, $max_height) {
  $w = imagesx($image); //current width
  $h = imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w <= $max_width) && ($h <= $max_height)) {return $image;} //no resizing needed
  //try max width first...
  $ratio = $max_width / $w;
  $new_w = $max_width;
  $new_h = $h * $ratio;
  //if that didn't work
  if ($new_h > $max_height) {
    $ratio = $max_height / $h;
    $new_h = $max_height;
    $new_w = $w * $ratio;
  }
  $new_image = imagecreatetruecolor($new_w, $new_h);
  imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
  return $new_image;
}
function resize_image_crop($image, $width, $height) {
  $w = @imagesx($image); //current width
  $h = @imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w == $width) && ($h == $height)) {return $image;} //no resizing needed
  //try max width first...
  $ratio = $width / $w;
  $new_w = $width;
  $new_h = $h * $ratio;
  //if that created an image smaller than what we wanted, try the other way
  if ($new_h < $height) {
    $ratio = $height / $h;
    $new_h = $height;
    $new_w = $w * $ratio;
  }
  $image2 = imagecreatetruecolor($new_w, $new_h);
  imagecopyresampled($image2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
  //check to see if cropping needs to happen
  if (($new_h != $height) || ($new_w != $width)) {
    $image3 = imagecreatetruecolor($width, $height);
    if ($new_h > $height) {
      //crop vertically
      $extra = $new_h - $height;
      $x     = 0; //source x
      $y     = round($extra / 2); //source y
      imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
    } else {
      $extra = $new_w - $width;
      $x     = round($extra / 2); //source x
      $y     = 0; //source y
      imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
    }
    imagedestroy($image2);
    return $image3;
  } else {
    return $image2;
  }
}
function upload_image($file) {
  $targetDir      = wp_upload_dir()["basedir"] . '/image-files/';
  $allowTypes     = array('jpg', 'png', 'jpeg');
  $fileName       = round(microtime(true)) . "_" . basename($file['name']);
  $targetFilePath = $targetDir . $fileName;
  // Check whether file type is valid
  $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
  if (in_array($fileType, $allowTypes)) {
    if ($file["size"] > 10000000) {
      return array("status" => "error", "content" => "Maximum 10Mb");
    }
    if (move_uploaded_file($file['tmp_name'], $targetFilePath)) {
      resize_image('crop', $targetDir . $fileName, $targetDir . '200x200/' . $fileName, 200, 200);
      $file_id = umm_model_insert_img($fileName);
      return array("status" => "success", "content" => $file_id);
    }
  } else {
    return array("status" => "error", "content" => "Allow jpg, png, jpeg");
  }
}
function umm_model_insert_img($file_name) {
  global $wpdb;
  $table  = $wpdb->prefix . 'images';
  $data   = array('image_name' => $file_name, 'user_id' => get_current_user_id());
  $format = array('%s', '%d');
  $wpdb->insert($table, $data, $format);
  return $wpdb->insert_id;
}
function get_image_url_by_id($id, $size = "full") {
  $url = wp_get_upload_dir()["baseurl"] . "/image-files/";
  if ($size != "full") {
    $url = wp_get_upload_dir()["baseurl"] . "/image-files/200x200/";
  }
  global $wpdb;
  $table  = $wpdb->prefix . "images";
  $result = $wpdb->get_results($wpdb->prepare(" SELECT image_name  FROM  {$table} WHERE id = %d ", $id), ARRAY_A, 1);
  return $url . $result[0]["image_name"];
}
/**
 *
 * Delete uploaded images file, database
 */
function delete_img_by_id($img_id) {
  global $wpdb;
  $table     = $wpdb->prefix . "images";
  $result    = $wpdb->get_results($wpdb->prepare(" SELECT image_name  FROM  {$table} WHERE id = %d ", $img_id), ARRAY_A, 1);
  $file_name = $result[0]["image_name"];
  $folder    = wp_upload_dir()["basedir"] . '/image-files/';
  unlink($folder . $file_name);
  unlink($folder . "200x200/" . $file_name);
  $wpdb->delete($table, array('id' => $img_id), array('%d'));
}
/**
 *
 * Get image url avatar  by user id
 */
function get_url_avatar($user_id = '') {
  if ($user_id === '') {
    $user_id = get_current_user_id();
  }
  $id_avatar = get_user_meta($user_id, 'id_img_avatar', true);
  if ($id_avatar) {
    return get_image_url_by_id($id_avatar, 'thumbnail');
  }
  return AVATAR_DF;
}
/**
 *
 * Check user exists
 * @return boolean
 */
function is_user_exist($user_id) {
  $user       = get_userdata($user_id);
  $user_roles = !empty($user) ? $user->roles[0] : "";
  if ($user === false or $user_roles != USER) {
    return false;
  } else {
    return true;
  }
}
/**
 *
 * Check View other account
 * @return boolean
 */
function is_view_other_account() {
  if (is_page('account') && isset($_GET['id']) && intval($_GET['id']) !== get_current_user_id()) {
    return true;
  }
  return false;
}
/**
 *
 * Get list user follow
 * @return array
 */
function list_user_follow($user_id = null) {
  if (!$user_id) {
    $user_id = get_current_user_id();
  }
  $list_user_follow = get_user_meta($user_id, 'list_user_follow', true);
  if (!$list_user_follow) {
    return array();
  }
  return json_decode($list_user_follow, true);
}
/**
 *
 * Nhận danh sách người theo dõi tôi
 * @return array
 */
function get_list_follower($current_user_id = null) {
  if (!$current_user_id) {
    $current_user_id = get_current_user_id();
  }
  $args              = array('role' => USER);
  $users             = get_users($args);
  $list_follower_arr = [];
  foreach ($users as $value) {
    $user_id         = $value->ID;
    $list_follow_arr = list_user_follow($user_id);
    if ($list_follow_arr):
      if (in_array($current_user_id, $list_follow_arr)) {
        $list_follower_arr[] = $user_id;
      }
    endif;
  }
  return $list_follower_arr;
}
/**
 *
 * Nhận tổng số người tôi đang theo dõi
 * @return int
 */
function get_total_following($current_user_id = null) {
  if (!$current_user_id) {
    $current_user_id = get_current_user_id();
  }
  return count(list_user_follow($current_user_id));
}
/**
 * tăng lên 1 so tổng thông báo mới hiện tại của user ID
 */
function update_total_notify_user($user_id){
  $total = (int)get_user_meta( $user_id, 'total_notify', true ) + 1;
  update_user_meta( $user_id, 'total_notify', $total);
}
// ==
function get_market_image_url($img_id){
  $url = wp_get_upload_dir()["baseurl"]."/market-images/";
  global $wpdb;
  $table = $wpdb->prefix."bj_market_image";
  $result = $wpdb->get_results ( $wpdb->prepare(" SELECT image_name FROM  {$table} WHERE id = %d ",$img_id) ,ARRAY_A  );
  if(!empty($result)){
    return $url."__".$result[0]["image_name"];
  }else{
    return THEME_URL."assets/images/default.jpg";
  }
}

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\functions.php

<?php
add_action('after_setup_theme', 'blankslate_setup');
function blankslate_setup() {
  load_theme_textdomain('blankslate', get_template_directory() . '/languages');
  add_theme_support('title-tag');
  add_theme_support('post-thumbnails');
  add_theme_support('responsive-embeds');
  add_theme_support('automatic-feed-links');
  add_theme_support('html5', array('search-form', 'navigation-widgets'));
  add_theme_support('woocommerce');
  global $content_width;
  if (!isset($content_width)) {$content_width = 1920;}
  register_nav_menus(array('main-menu' => esc_html__('Main Menu', 'blankslate')));
}
add_filter('document_title_separator', 'blankslate_document_title_separator');
function blankslate_document_title_separator($sep) {
  $sep = esc_html('|');
  return $sep;
}
add_filter('the_title', 'blankslate_title');
function blankslate_title($title) {
  if ($title == '') {
    return esc_html('...');
  } else {
    return wp_kses_post($title);
  }
}
function blankslate_schema_type() {
  $schema = 'https://schema.org/';
  if (is_single()) {
    $type = "Article";
  } elseif (is_author()) {
    $type = 'ProfilePage';
  } elseif (is_search()) {
    $type = 'SearchResultsPage';
  } else {
    $type = 'WebPage';
  }
  echo 'itemscope itemtype="' . esc_url($schema) . esc_attr($type) . '"';
}
add_filter('nav_menu_link_attributes', 'blankslate_schema_url', 10);
function blankslate_schema_url($atts) {
  $atts['itemprop'] = 'url';
  return $atts;
}
if (!function_exists('blankslate_wp_body_open')) {
  function blankslate_wp_body_open() {
    do_action('wp_body_open');
  }
}
add_action('wp_body_open', 'blankslate_skip_link', 5);
function blankslate_skip_link() {
  echo '<a href="#content" class="skip-link screen-reader-text">' . esc_html__('Skip to the content', 'blankslate') . '</a>';
}
add_filter('the_content_more_link', 'blankslate_read_more_link');
function blankslate_read_more_link() {
  if (!is_admin()) {
    return ' <a href="' . esc_url(get_permalink()) . '" class="more-link">' . sprintf(__('...%s', 'blankslate'), '<span class="screen-reader-text">  ' . esc_html(get_the_title()) . '</span>') . '</a>';
  }
}
add_filter('excerpt_more', 'blankslate_excerpt_read_more_link');
function blankslate_excerpt_read_more_link($more) {
  if (!is_admin()) {
    global $post;
    return ' <a href="' . esc_url(get_permalink($post->ID)) . '" class="more-link">' . sprintf(__('...%s', 'blankslate'), '<span class="screen-reader-text">  ' . esc_html(get_the_title()) . '</span>') . '</a>';
  }
}
add_filter('big_image_size_threshold', '__return_false');
add_filter('intermediate_image_sizes', 'remove_default_img_sizes', 10, 1);
function remove_default_img_sizes($sizes) {
  $targets = ['medium_large', 'large', '1536x1536', '2048x2048', 'woocommerce_thumbnail', 'woocommerce_single', 'woocommerce_gallery_thumbnail', 'shop_catalog', 'shop_single', 'shop_thumbnail'];
  foreach ($sizes as $size_index => $size) {
    if (in_array($size, $targets)) {
      unset($sizes[$size_index]);
    }
  }
  return $sizes;
}
// == Start Script
add_action('wp_enqueue_scripts', 'ecademy_enqueue_style');
function ecademy_enqueue_style() {
  wp_enqueue_script('jquery');
  wp_enqueue_style("custom_css", get_stylesheet_directory_uri() . "/css/custom.css", array(), '1.1.0', 'all');
  $script_data_array = array(
    'ajaxurl'  => admin_url('admin-ajax.php'),
    'security' => wp_create_nonce('file_upload'),
  );
  wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '123', 'all', true);
  wp_localize_script('custom_js', 'app', $script_data_array);
}
function wpdocs_selectively_enqueue_admin_script($hook) {
  wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/js/admin.js', array('jquery'), '123', 'all', true);
  wp_enqueue_style("custom_css", get_stylesheet_directory_uri() . "/css/admin.css", array(), '1.1.0', 'all');
}
add_action('admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script');
// == End Script
// Start App
require get_template_directory() . '/inc/define.php';
require get_template_directory() . '/framework/init.php';
require get_template_directory() . '/inc/functions/function-setup.php';
require get_template_directory() . '/inc/functions/function-global.php';
require_once get_template_directory().'/framework/ajax/business.php';
// End App

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\ajax\business.php

<?php
add_action('wp_ajax_account_activity_load_list_deal', 'account_activity_load_list_deal');
function account_activity_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("business");
  $list_deal = $model->activity_load_deal_id(5);
  if(!empty($list_deal)){
    $deal_model = $bj_controller->Model("deal");
    foreach ($list_deal as  $value) {
      $deal_detail = $deal_model->get_deal_detail($value["deal_id"]);
      echo '<div class="col-6">';
        get_template_part("framework/views/deal/item","",$deal_detail);
      echo '</div>';
    }
  }else{
    echo '<p class="p-3">'.__("No data","umm").'</p>';
  }
  wp_die();
}
add_action('wp_ajax_account_activity_get_tab_number', 'account_activity_get_tab_number');
function account_activity_get_tab_number() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  if(!isset($_POST["type"]) or !in_array($_POST["type"],["activity","business"])) die("error");
  global $bj_controller, $wpdb;
  $return = array(
    "deal" => 0,
    "event" => 0
  );
  if($_POST["type"] == "activity"){
    $list_deal = $bj_controller->Model("business")->activity_load_deal_id(10000);
    if(!empty($list_deal)) $return["deal"] = count($list_deal);
  }else{
    $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
    if(!empty($list_business_arr)) {
      $arr = [];
      foreach ($list_business_arr as $value) {
        $arr[] = $value["id"];
      }
      $table = $wpdb->prefix."bj_business_deal";
      $business_id_arr = implode("','",$arr);
      $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
      if(!empty($list_deal)) $return["deal"] = count($list_deal);
    };
  }
  die(json_encode($return));
}

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\models\deal.php

<?php
class BJ_deal_Model {
  private $table_business_deal = 'bj_business_deal';
  public function get_deal_detail($deal_id) {
    global $wpdb;
    $table  = $wpdb->prefix . $this->table_business_deal;
    $result = $wpdb->get_results($wpdb->prepare(" SELECT * FROM  {$table} WHERE id = %d", $deal_id), ARRAY_A);
    if (!empty($result)) {
      return $result[0];
    }
  }
  public function deal_get_list_user_id_saved($deal_id) {
    global $wpdb;
    $table  = $wpdb->prefix . "bj_business_deal_saved";
    $result = $wpdb->get_results($wpdb->prepare(" SELECT user_id FROM  {$table} WHERE deal_id = %d ", $deal_id), ARRAY_A);
    $arr    = [];
    if (!empty($result)) {
      foreach ($result as $value) {
        $arr[] = $value["user_id"];
      }
    }
    return $arr;
  }
} 

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\models\business.php

<?php 
class BJ_business_Model{
	private $table_business = 'bj_business';
	public function activity_load_deal_id($number = 20,$offset = 0){
		$current_user_id = get_current_user_id();
		global $wpdb;
		$table = $wpdb->prefix."bj_business_deal_saved";
		$result = $wpdb->get_results ( $wpdb->prepare(" SELECT deal_id FROM  {$table} WHERE user_id = %d ORDER BY id DESC LIMIT %d,%d",$current_user_id,$offset,$number) ,ARRAY_A);
		if(!empty($result)) return $result;
	}
	public function get_list_business_by_user_id($user_id){
		global $wpdb;
		$table = $wpdb->prefix.$this->table_business;
		$result = $wpdb->get_results ( $wpdb->prepare(" SELECT * FROM  {$table} WHERE user_id = %d ORDER BY id DESC",$user_id) ,ARRAY_A);
		if(!empty($result)) return $result;
	}
}// end class

C:\Users\Administrator\Downloads\wp_bj_business.sql

-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 27, 2022 at 09:43 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wordpress8`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_bj_business`
--
CREATE TABLE `wp_bj_business` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `description` text NOT NULL,
  `open_hour` varchar(255) NOT NULL,
  `province` varchar(5) NOT NULL,
  `district` varchar(5) NOT NULL,
  `ward` varchar(7) NOT NULL,
  `street` varchar(255) NOT NULL,
  `price_from` int(11) NOT NULL,
  `price_to` int(11) NOT NULL,
  `category_id` int(4) NOT NULL,
  `website_link` varchar(255) NOT NULL,
  `facebook_link` varchar(255) NOT NULL,
  `images` varchar(255) NOT NULL,
  `rate` int(1) NOT NULL,
  `n_o_rate` int(8) NOT NULL,
  `saved` int(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `wp_bj_business`
--
INSERT INTO `wp_bj_business` (`id`, `user_id`, `name`, `phone`, `description`, `open_hour`, `province`, `district`, `ward`, `street`, `price_from`, `price_to`, `category_id`, `website_link`, `facebook_link`, `images`, `rate`, `n_o_rate`, `saved`) VALUES
(1, 2, 'Kiwooza Planet', '0123456789', 'Description: We buy clothes. To update scientific information and new recommendations for optimal...', '[[\"mon\",\"Monday\",\"08:00\",\"21:00\"],[\"tue\",\"Tuesday\",\"08:00\",\"21:00\"],[\"wed\",\"Wednesday\",\"08:00\",\"21:00\"],[\"thu\",\"Thursday\",\"08:00\",\"21:00\"],[\"fri\",\"Friday\",\"08:00\",\"21:00\"]]', '79', '760', '26734', 'Nguyễn Xí', 200000, 400000, 4, 'Kiwooza.com', '#', '[4,5]', 0, 0, 0),
(2, 2, 'Kiwooza Planet 02', '0367676128', 'Description: We buy clothes. To update scientific information and new recommendations for optimal...', '[[\"wed\",\"Wednesday\",\"08:00\",\"21:00\"],[\"thu\",\"Thursday\",\"08:00\",\"21:00\"]]', '01', '001', '00004', '128 Nguyễn Đình Chiểu', 300000, 900000, 3, '#', '#', '[6]', 5, 1, 0),
(3, 2, 'Add from app', '0123456789', 'Description ', '[[\"mon\",\"Monday\",\"08:00\",\"21:00\"],[\"tue\",\"Tuesday\",\"08:00\",\"21:00\"],[\"wed\",\"Wednesday\",\"08:00\",\"21:00\"],[\"thu\",\"Thursday\",\"08:00\",\"21:00\"],[\"fri\",\"Friday\",\"08:00\",\"21:00\"]]', '79', '769', '26815', 'Vo van ngan', 120000, 500000, 1, '#', '#', '[7]', 0, 0, 0),
(4, 2, 'Landmark 81', '0356214413', 'Tòa nhà cao nhất Việt Nam The Landmark 81 của Tập đoàn Vingroup', '[[\"mon\",\"Monday\",\"07:30\",\"22:00\"],[\"tue\",\"Tuesday\",\"08:00\",\"21:00\"],[\"wed\",\"Wednesday\",\"08:00\",\"21:00\"],[\"thu\",\"Thursday\",\"08:00\",\"21:00\"],[\"fri\",\"Friday\",\"08:00\",\"21:00\"]]', '79', '765', '26956', '208 Nguyễn Hữu Cảnh', 100000, 900000, 1, 'landmark.com', 'facebook.com/landmark', '[8,9,10]', 4, 4, 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `wp_bj_business`
--
ALTER TABLE `wp_bj_business`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `wp_bj_business`
--
ALTER TABLE `wp_bj_business`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

C:\Users\Administrator\Downloads\wp_bj_business_deal_saved.sql

-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 27, 2022 at 09:46 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wordpress8`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_bj_business_deal_saved`
--
CREATE TABLE `wp_bj_business_deal_saved` (
  `id` int(11) NOT NULL,
  `deal_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `wp_bj_business_deal_saved`
--
INSERT INTO `wp_bj_business_deal_saved` (`id`, `deal_id`, `user_id`) VALUES
(5, 1, 2),
(10, 3, 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `wp_bj_business_deal_saved`
--
ALTER TABLE `wp_bj_business_deal_saved`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `wp_bj_business_deal_saved`
--
ALTER TABLE `wp_bj_business_deal_saved`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;img

C:\Users\Administrator\Downloads\wp_bj_business_deal.sql

-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 27, 2022 at 09:48 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wordpress8`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_bj_business_deal`
--
CREATE TABLE `wp_bj_business_deal` (
  `id` int(11) NOT NULL,
  `business_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `date_from` date NOT NULL,
  `date_to` date NOT NULL,
  `quantity` int(7) NOT NULL,
  `images` varchar(255) NOT NULL,
  `saved` int(5) NOT NULL,
  `district` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `wp_bj_business_deal`
--
INSERT INTO `wp_bj_business_deal` (`id`, `business_id`, `title`, `description`, `date_from`, `date_to`, `quantity`, `images`, `saved`, `district`) VALUES
(1, 4, '10% Sale Off ', 'We buy clothes. To update scientific information and new recomm-endations for optimal management of elderly patients; ', '2022-02-16', '2022-02-20', 10, '[11,12,13]', 1, ''),
(2, 2, 'Kiwiooza 10% Sale Off', 'Kiwiooza 10% Sale Off For All Orders', '2022-02-26', '2022-02-28', 100, '[14,15]', 0, ''),
(3, 4, 'flower', 'nice flower', '2022-02-19', '2022-02-19', 12, '[16]', 1, '765'),
(4, 2, 'test', '123', '2022-02-21', '2022-02-24', 19, '[25]', 0, '001');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `wp_bj_business_deal`
--
ALTER TABLE `wp_bj_business_deal`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `wp_bj_business_deal`
--
ALTER TABLE `wp_bj_business_deal`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\views\deal\item.php

<?php  
	global $bj_controller;
	$token = wp_create_nonce(BJ_NONCE_KEY."deal".$args["id"]);
	$link = get_site_url()."/deals/?id=".$args["id"]."&token=".$token."&appt=N";
	$thumb_url = THEME_URL."images/default.jpg";
	if(!empty($args["images"])){
		$images_arr = json_decode($args["images"],true);
		if(!empty($images_arr)){
			$thumb_url = get_market_image_url($images_arr[0]);
		}
	}
	$list_deal_favorite_arr = $bj_controller->Model("deal")->deal_get_list_user_id_saved($args["id"]);
	$added_class = !empty($list_deal_favorite_arr) && in_array(get_current_user_id(),$list_deal_favorite_arr) ? " added" : "";
	$n_o_saved = !empty($list_deal_favorite_arr) ? count($list_deal_favorite_arr) : 0;
?>
<div class="deal-item">
  <a href="<?php echo $link ?>">
    <img src="<?php echo $thumb_url ?>" alt="">
    <div class="info">
      <h6><?php echo $bj_controller->Model("directory")->get_business_detail($args["business_id"])["name"] ?></h6>
      <h5><?php echo $args["title"] ?></h5>
      <p><?php echo $n_o_saved.__(" neighbors saved","umm") ;?></p>
    </div>
  </a>  
  <button class="deal add-favorite<?php echo $added_class ?>" data-id="<?php echo $args["id"] ?>" data-token="<?php echo $token ?>">
    <svg width="15" height="27" viewBox="0 0 20 27" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M19 26L10 19.0556L1 26V3.77778C1 3.04107 1.27092 2.33453 1.75315 1.81359C2.23539 1.29266 2.88944 1 3.57143 1H16.4286C17.1106 1 17.7646 1.29266 18.2468 1.81359C18.7291 2.33453 19 3.04107 19 3.77778V26Z" fill="#686868" stroke="#686868" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
    </svg>
  </button>     
</div>

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\models\directory.php

<?php 
class BJ_directory_Model{
	private $table_business = 'bj_business';
	public function get_business_detail($business_id){
		global $wpdb;
		$table = $wpdb->prefix.$this->table_business;
		$result = $wpdb->get_results ( $wpdb->prepare(" SELECT * FROM  {$table} WHERE id = %d",$business_id) ,ARRAY_A);
		if(!empty($result)) return $result[0];
	}
}

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\js\account-business.js

jQuery(document).ready(function($) {
  function account_activity_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  function account_get_tab_number(type = "activity") {
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_get_tab_number',
        type: type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        if (output != "error") {
          const obj = JSON.parse(output, function(key, value) {
            $(".account-load-btn[data-id='" + key + "'] span").text(value);
          });
        }
      }
    });
  }
  function account_business_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_business_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        //is_busy = false;
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  // ==
  account_activity_load("deal");
  account_get_tab_number();
  // ==
  $('body').on('click', '#change-acc', function(e) {
    const $this = $(this);
    const btnScan = $('#scan-voucher');
    const type = $this.attr('data-type');
    const userId = $this.attr('data-id');
    const tab_active = $(".tab-active").data("tab-id");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'change_business_activity',
        token: $('#nonce_token').val(),
        type: type,
        id: userId,
      },
      beforeSend: function() {
        $(".account-list-item:not('.news') .col-6").not(".col-addnew").remove();
        $this.find('svg').addClass('spin');
      },
      success: function(response) {
        $(".menu-tab-account .li").not(".active").find("a").addClass("load");
        $this.find('svg').removeClass('spin');
        btnScan.toggle();
        if (type == 'activity') {
          // xử lý data business
          account_get_tab_number("business");
          $this.attr('data-type', 'business').find('span').text(app.business);
          $(".account-list-item .col-addnew").removeClass("d-none");
          if (tab_active != "news") { 
            account_business_load(tab_active); 
          }
          $(".menu-tab-account ul li:last-child,.tab-news").addClass("d-none");
          $(".col-activity-event").remove();
          return;
        }
        $this.attr('data-type', 'activity').find('span').text(app.activity);
        $(".account-list-item .col-addnew").addClass("d-none");
        account_get_tab_number();
        if (tab_active != "news") { 
          account_activity_load(tab_active); 
        }
        $(".menu-tab-account ul li:last-child,.tab-news").removeClass("d-none");
      },
      error: function() {
        $this.find('svg').removeClass('spin');
        alert('Error');
      }
    })
    return false;
  });
});

Change Tab Activity <=> Business

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\js\account-business.js

jQuery(document).ready(function($) {
  function account_activity_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  function account_get_tab_number(type = "activity") {
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_get_tab_number',
        type: type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        if (output != "error") {
          const obj = JSON.parse(output, function(key, value) {
            $(".account-load-btn[data-id='" + key + "'] span").text(value);
          });
        }
      }
    });
  }
  function account_business_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_business_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        //is_busy = false;
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  // ==
  account_activity_load("deal");
  account_get_tab_number();
  // ==
  $('body').on('click', '#change-acc', function(e) {
    const $this = $(this);
    const btnScan = $('#scan-voucher');
    const type = $this.attr('data-type');
    const userId = $this.attr('data-id');
    const tab_active = $(".tab-active").data("tab-id");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'change_business_activity',
        token: $('#nonce_token').val(),
        type: type,
        id: userId,
      },
      beforeSend: function() {
        $(".account-list-item:not('.news') .col-6").not(".col-addnew").remove();
        $this.find('svg').addClass('spin');
      },
      success: function(response) {
        $(".menu-tab-account .li").not(".active").find("a").addClass("load");
        $this.find('svg').removeClass('spin');
        btnScan.toggle();
        if (type == 'activity') {
          // xử lý data business
          account_get_tab_number("business");
          $this.attr('data-type', 'business').find('span').text(app.business);
          $(".account-list-item .col-addnew").removeClass("d-none");
          if (tab_active != "news") { 
            account_business_load(tab_active); 
          }
          $(".menu-tab-account ul li:last-child,.tab-news").addClass("d-none");
          $(".col-activity-event").remove();
          return;
        }
        $this.attr('data-type', 'activity').find('span').text(app.activity);
        $(".account-list-item .col-addnew").addClass("d-none");
        account_get_tab_number();
        if (tab_active != "news") { 
          account_activity_load(tab_active); 
        }
        $(".menu-tab-account ul li:last-child,.tab-news").removeClass("d-none");
      },
      error: function() {
        $this.find('svg').removeClass('spin');
        alert('Error');
      }
    })
    return false;
  });
});

C:\xampp\htdocs\wordpress8\wp-content\themes\addframwork\framework\ajax\business.php

<?php
add_action('wp_ajax_account_activity_load_list_deal', 'account_activity_load_list_deal');
function account_activity_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("business");
  $list_deal = $model->activity_load_deal_id(5);
  if(!empty($list_deal)){
    $deal_model = $bj_controller->Model("deal");
    foreach ($list_deal as  $value) {
      $deal_detail = $deal_model->get_deal_detail($value["deal_id"]);
      echo '<div class="col-6">';
        get_template_part("framework/views/deal/item","",$deal_detail);
      echo '</div>';
    }
  }else{
    echo '<p class="p-3">'.__("No data","umm").'</p>';
  }
  wp_die();
}
add_action('wp_ajax_account_activity_get_tab_number', 'account_activity_get_tab_number');
function account_activity_get_tab_number() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  if(!isset($_POST["type"]) or !in_array($_POST["type"],["activity","business"])) die("error");
  global $bj_controller, $wpdb;
  $return = array(
    "deal" => 0,
    "event" => 0
  );
  if($_POST["type"] == "activity"){
    $list_deal = $bj_controller->Model("business")->activity_load_deal_id(10000);
    if(!empty($list_deal)) $return["deal"] = count($list_deal);
  }else{
    $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
    if(!empty($list_business_arr)) {
      $arr = [];
      foreach ($list_business_arr as $value) {
        $arr[] = $value["id"];
      }
      $table = $wpdb->prefix."bj_business_deal";
      $business_id_arr = implode("','",$arr);
      $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
      if(!empty($list_deal)) $return["deal"] = count($list_deal);
    };
  }
  die(json_encode($return));
}
add_action('wp_ajax_account_business_load_list_deal', 'account_business_load_list_deal');
function account_business_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  global $wpdb;
  $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
  if(!empty($list_business_arr)) {
    $arr = [];
    foreach ($list_business_arr as $value) {
      $arr[] = $value["id"];
    }
    $table = $wpdb->prefix."bj_business_deal";
    $business_id_arr = implode("','",$arr);
    $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
    if(!empty($list_deal)){
      $deal_model = $bj_controller->Model("deal");
      foreach ($list_deal as  $value) {
        $deal_detail = $deal_model->get_deal_detail($value["id"]);
        $deal_detail["account"] = true;
        echo '<div class="col-6">';
        get_template_part("framework/views/deal/item","",$deal_detail);
        echo '</div>';
      }
    }else{
      echo '<p class="p-3">'.__("No data","umm").'</p>';
    }
  };
  die();
}

Last updated