<?php

if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       tatvic.com
 * @since      1.0.0
 *
 * @package    Enhanced_Ecommerce_Google_Analytics
 * @subpackage Enhanced_Ecommerce_Google_Analytics/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Enhanced_Ecommerce_Google_Analytics
 * @subpackage Enhanced_Ecommerce_Google_Analytics/admin
 * @author     Tatvic
 */
if (class_exists('Conversios_Admin') === FALSE) {
  class Conversios_Admin extends TVC_Admin_Helper
  {

    //Google Detail variable
    protected $google_detail;

    //Url onboarding
    protected $url;

    //Version variable
    protected $version;
    public function __construct()
    {
      $this->version = PLUGIN_TVC_VERSION;
      $this->includes();
      $this->url = $this->get_onboarding_page_url(); // use in setting page
      $this->google_detail = $this->get_ee_options_data();
      add_action('admin_menu', array($this, 'add_admin_pages'));
      add_action('admin_init', array($this, 'init'));
      add_action("admin_print_styles", [$this, 'dequeue_css']);
      add_action('wp_ajax_conv_get_ore_data', [$this, 'conv_get_ore_data_handler']);
    }

    /********Include Header and Footer **************************/
    public function includes()
    {
      if (class_exists('Conversios_Header') === FALSE) {
        require_once(ENHANCAD_PLUGIN_DIR . 'admin/partials/class-conversios-header.php');
      }

      if (class_exists('Conversios_Footer') === FALSE) {
        require_once(ENHANCAD_PLUGIN_DIR . 'admin/partials/class-conversios-footer.php');
      }
    }

    /*******Add scripts and styles to every page *******************/
    public function init()
    {
      add_action('admin_enqueue_scripts', array($this, 'enqueue_styles'));
      add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));

      $optionValue = get_option("conv_active_domain");
      if (!$optionValue) {
        $activeDomain = '';
      } else {
        $decoded = base64_decode($optionValue, true);
        $activeDomain = ($decoded !== false) ? $decoded : '';
      }
      
      if (empty($activeDomain)) {
        if (!class_exists('CustomApi.php')) {
          require_once(ENHANCAD_PLUGIN_DIR . 'includes/setup/CustomApi.php');
        }
        $customApiObj = new CustomApi();
        $caller = "init_function";
        $google_detail_res = $customApiObj->getGoogleAnalyticDetail($caller);
        $activeDomain = $google_detail_res->data->active_domain ?? '';
        update_option("conv_active_domain", base64_encode($activeDomain));
      }

      $normalizedActiveDomain = $this->domainNormalize($activeDomain);
      $originalsiteurl = $this->conv_getoriginalsiteurl();
      $normalizedCurrentDomain = $this->domainNormalize($originalsiteurl);
      if ($normalizedActiveDomain != $normalizedCurrentDomain) {
        if (!class_exists('CustomApi.php')) {
          require_once(ENHANCAD_PLUGIN_DIR . 'includes/setup/CustomApi.php');
        }
        $customApiObj = new CustomApi();
        $customApiObj->createNewSubscription();
      }
    }

    function dequeue_css()
    {
      $screen = get_current_screen();
      global $wp_styles;
      if (strpos($screen->id, CONV_SCREEN_ID) !== false || $screen->id === 'toplevel_page_conversios') {
        $not_allowed_css = array('porto_admin', 'flashy');
        foreach ($wp_styles->queue as $key => $value) {
          if (in_array($value, $not_allowed_css)) {
            wp_deregister_style($value);
            wp_dequeue_style($value);
          }
        }
      }
    }


    /**
     * Register the stylesheets for the admin area.
     *
     * @since    4.1.4
     */
    public function enqueue_styles()
    {
      $screen = get_current_screen();
      if ($screen->id === 'toplevel_page_conversios'  || (isset($_GET['page']) === TRUE && strpos(sanitize_text_field(wp_unslash($_GET['page'])), 'conversios') !== false)) {
        do_action('add_conversios_css_' . sanitize_text_field(wp_unslash($_GET['page'])));
        $page = sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'page')));
        if ($page == "conversios-analytics-reports" || $page == "conversios" || $page == "conversios-purchase-tracking") {
          wp_register_style('conversios-daterangepicker-css', esc_url(ENHANCAD_PLUGIN_URL . '/admin/css/daterangepicker.css'));
          wp_enqueue_style('conversios-daterangepicker-css');
        }
        wp_enqueue_style('conversios-responsive-css', esc_url(ENHANCAD_PLUGIN_URL . '/admin/css/responsive.css'), array(), esc_attr($this->version), 'all');
        if (sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'wizard'))) == "campaignManagement" || $page == "conversios-purchase-tracking" || $page == "conversios-audience-manager") {
          wp_register_style('tvc-dataTables-css', esc_url(ENHANCAD_PLUGIN_URL . '/admin/css/dataTables.bootstrap5.min.css'));
          wp_enqueue_style('tvc-dataTables-css');
        }
      }
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    4.1.4
     */
    public function enqueue_scripts()
    {
      $screen = get_current_screen();
      $page = sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'page')));
      if ($page === 'conversios-analytics-reports' || $page === 'conversios') {
        wp_enqueue_script('conversios-chart-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/chart.js'));
        wp_enqueue_script('conversios-chart-datalabels-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/chartjs-plugin-datalabels.js'));
        wp_enqueue_script('conversios-basictable-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/jquery.basictable.min.js'));
        wp_enqueue_script('conversios-htmlcanvas', esc_url_raw(ENHANCAD_PLUGIN_URL . '/admin/js/html2canvas.min.js'));
        wp_enqueue_script('conversios-jspdf', esc_url_raw(ENHANCAD_PLUGIN_URL . '/admin/js/jspdf.umd.min.js'));
        wp_enqueue_media();
        // Use official WordPress core moment.js script
        wp_enqueue_script('moment');
        wp_enqueue_script('conversios-daterangepicker-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/daterangepicker.js'));
        wp_enqueue_script('conversios-custom-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/tvc-ee-custom.js'), array('jquery'), esc_attr($this->version), false);
      } else if (isset($_GET['page']) === TRUE && sanitize_text_field(wp_unslash($_GET['page'])) === "conversios") {
        wp_enqueue_script('moment');
      } else if (isset($_GET['page']) === TRUE && sanitize_text_field(wp_unslash($_GET['page'])) === "conversios-audience-manager") {
        wp_enqueue_script('tvc-ee-dataTables-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/jquery.dataTables.min.js'), array('jquery'), esc_attr($this->version), false);
        wp_enqueue_script('tvc-ee-dataTables-v5-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/dataTables.bootstrap5.min.js'), array('jquery'), esc_attr($this->version), false);
      } else if (isset($_GET['page']) === TRUE && sanitize_text_field(wp_unslash($_GET['page'])) === "conversios-purchase-tracking") {
        // Enqueue required scripts for ORE table and daterange picker
        wp_enqueue_script('moment');
        wp_enqueue_script('conversios-daterangepicker-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/daterangepicker.js'), array('jquery', 'moment'), esc_attr($this->version), false);
        wp_enqueue_script('tvc-ee-dataTables-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/jquery.dataTables.min.js'), array('jquery'), esc_attr($this->version), false);
        wp_enqueue_script('tvc-ee-dataTables-v5-js', esc_url(ENHANCAD_PLUGIN_URL . '/admin/js/dataTables.bootstrap5.min.js'), array('jquery'), esc_attr($this->version), false);
      }
    }

    /**
     * Display Admin Page.
     *
     * @since    4.1.4
     */
    public function add_admin_pages()
    {
      $google_detail = $this->google_detail;
      if (isset($google_detail['setting'])) {
        $googleDetail = $google_detail['setting'];
      }
      $icon = ENHANCAD_PLUGIN_URL . "/admin/images/offer.png";
      $freevspro = ENHANCAD_PLUGIN_URL . "/admin/images/freevspro.png";

      add_menu_page(
        esc_html(CONV_TOP_MENU, 'enhanced-e-commerce-for-woocommerce-store'),
        esc_html(CONV_TOP_MENU, 'enhanced-e-commerce-for-woocommerce-store') . '',
        'manage_options',
        CONV_MENU_SLUG,
        array($this, 'showPage'),
        esc_url(plugin_dir_url(__FILE__) . 'images/tatvic_logo.png'),
        26
      );
      if (!function_exists('is_plugin_active_for_network')) {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
      }

      add_submenu_page(
        CONV_MENU_SLUG,
        esc_html__('Dashboard', 'enhanced-e-commerce-for-woocommerce-store'),
        esc_html__('Dashboard', 'enhanced-e-commerce-for-woocommerce-store'),
        'manage_options',
        'conversios',
        '',
        0
      );
      if (CONV_APP_ID == 1) {
        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Pixels & Analytics', 'enhanced-e-commerce-for-woocommerce-store'),
          esc_html__('Pixels & Analytics', 'enhanced-e-commerce-for-woocommerce-store'),
          'manage_options',
          'conversios-google-analytics',
          array($this, 'showPage'),
          2
        );
      }

      if (class_exists('WooCommerce') || is_plugin_active_for_network('woocommerce/woocommerce.php') || in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
        if (CONV_APP_ID == 1) {
          add_submenu_page(
            CONV_MENU_SLUG,
            esc_html__('Analytics Report', 'enhanced-e-commerce-for-woocommerce-store'),
            esc_html__('Analytics Report', 'enhanced-e-commerce-for-woocommerce-store'),
            'manage_options',
            'conversios-analytics-reports',
            array($this, 'showPage'),
            1
          );
        }

        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Product Feed', 'enhanced-e-commerce-for-woocommerce-store'),
          '<span class="product_feed_menu"> ' . esc_html__('Product Feed', 'enhanced-e-commerce-for-woocommerce-store') . ' </span>',
          'manage_options',
          'conversios-google-shopping-feed',
          array($this, 'showPage'),
          3
        );
        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Order Recovery Engine', 'enhanced-e-commerce-for-woocommerce-store'),
          esc_html__('Order Recovery Engine', 'enhanced-e-commerce-for-woocommerce-store'),
          'manage_options',
          'conversios-purchase-tracking',
          array($this, 'showPage'),
          5
        );
      } else { // When no wc

        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Analytics Report', 'enhanced-e-commerce-for-woocommerce-store'),
          esc_html__('Analytics Report', 'enhanced-e-commerce-for-woocommerce-store'),
          'manage_options',
          'conversios-analytics-reports',
          array($this, 'showPage'),
          1
        );
      }

      if (CONV_APP_ID == 1) {
        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Account Summary', 'enhanced-e-commerce-for-woocommerce-store'),
          esc_html__('Account Summary', 'enhanced-e-commerce-for-woocommerce-store'),
          'manage_options',
          'conversios-account',
          array($this, 'showPage'),
          12
        );

        add_submenu_page(
          CONV_MENU_SLUG,
          esc_html__('Free Vs Pro', 'enhanced-e-commerce-for-woocommerce-store'),
          esc_html__('Free Vs Pro', 'enhanced-e-commerce-for-woocommerce-store') . '<img style="position: absolute; height: 30px;bottom: 5px; right: 10px;" src="' . esc_url($freevspro) . '">',
          'manage_options',
          'conversios-pricings',
          array($this, 'showPage'),
          13
        );
      }
    }

    /**
     * Display page.
     *
     * @since    4.1.4
     */
    public function showPage()
    {
      do_action('add_conversios_header');
      if (!empty(sanitize_text_field(wp_unslash($_GET['page'])))) {
        $get_action = str_replace("-", "_", sanitize_text_field(wp_unslash($_GET['page'])));
      } else {
        $get_action = "conversios";
      }
      if (method_exists($this, $get_action)) {
        $this->$get_action();
      }
      $html = $this->get_tvc_popup_message();
      echo wp_kses($html, array(
        "div" => array(
          'class' => array(),
          'style' => array(),
          'id' => array(),
          'title' => array(),
        ),
        "span" => array(
          'class' => array(),
          'style' => array(),
          'id' => array(),
          'title' => array(),
          'onclick' => array(),
        ),
        "h4" => array(
          'id' => array(),
        ),
        "p" => array(
          'id' => array(),
        ),
      ));
      do_action('add_conversios_footer');
    }

    /**
     * Free vs Pro Comparison Page
     */
    public function conversios_pricings()
    {
      require_once(ENHANCAD_PLUGIN_DIR . 'admin/partials/conversios-pricings.php');
    }

    /**
     * Web Reports ( No WC ) page.
     *
     * @since    4.1.4
     */
    public function callback_conversios_web_reports()
    {
      do_action('add_conversios_header');
?>
      <div style="position:relative;">
        <div class="card coming-soon-card shadow-lg" style="position: fixed; top: 25%; left: 40%; z-index: 999;max-width: 400px; margin: 2rem auto; text-align: center;">
          <div class="card-body" style="padding: 2rem;">
            <h5 class="card-title" style="font-size: 1.5rem; margin-bottom: 1rem;"><?php esc_html_e( 'Feature Coming Soon', 'enhanced-e-commerce-for-woocommerce-store' ); ?></h5>
            <p class="card-text" style="font-size: 1rem; margin-bottom: 1.5rem;"><?php esc_html_e( 'We\'re working hard to bring this feature to you. Stay tuned!', 'enhanced-e-commerce-for-woocommerce-store' ); ?></p>
            <a target="_blank" href="https://www.conversios.io/pricing/?utm_source=woo_aiofree_plugin&utm_medium=use_your_own_gtm&utm_campaign=pixel_list" class="btn btn-primary"><?php esc_html_e( 'Learn More', 'enhanced-e-commerce-for-woocommerce-store' ); ?></a>
          </div>
        </div>
        <?php echo wp_kses(
          enhancad_get_plugin_image('/admin/images/web-reports-placeholder.png', 'reports', '', 'filter:opacity(0.7) blur(2px); margin-top:20px;'),
          array(
            'img' => array(
              'src' => true,
              'alt' => true,
              'class' => true,
              'style' => true,
            ),
          )
        ); ?>
      </div>
<?php
      do_action('add_conversios_footer');
    }

    // public function conversios()
    // {
    //   require_once(ENHANCAD_PLUGIN_DIR.'includes/setup/class-conversios-dashboard.php');
    // }

    public function conversios()
    {
      $get_tab = filter_input(INPUT_GET, 'tab');
      $is_inner_page = $get_tab ? str_replace("-", "_", sanitize_text_field(wp_unslash($get_tab))) : "";

      $get_wizard = filter_input(INPUT_GET, 'wizard');
      $is_wizard = $get_wizard ? sanitize_text_field(wp_unslash($get_wizard)) : "";

      // Call inner page method if specified
      if (!empty($is_inner_page) && method_exists($this, $is_inner_page)) {
        $this->$is_inner_page();
        return;
      }

      $ee_options = maybe_unserialize(get_option('ee_options'));
      $gm_id = $ee_options['gm_id'] ?? "";
      $google_ads_id = $ee_options['google_ads_id'] ?? "";
      $conv_onboarding_done_step = $ee_options['conv_onboarding_done_step'] ?? "";
      $conv_onboarding_done = $ee_options['conv_onboarding_done'] ?? "";

      // Load onboarding wizard if applicable
      if (
        version_compare(PLUGIN_TVC_VERSION, "7.1.2", ">") &&
        (empty($gm_id) || empty($google_ads_id)) &&
        (empty($conv_onboarding_done_step) || $conv_onboarding_done_step != "6") &&
        empty($conv_onboarding_done)
      ) {
        require_once 'partials/wizard_pixelandanalytics.php';
        return;
      }

      // Load wizard page directly if requested
      if ($is_wizard === "pixelandanalytics") {
        require_once 'partials/wizard_pixelandanalytics.php';
        return;
      }

      // Default: load dashboard
      require_once(ENHANCAD_PLUGIN_DIR . 'includes/setup/class-conversios-analytics-reports.php');

      // Load subpage if specified
      $sub_page = filter_input(INPUT_GET, 'subpage', FILTER_DEFAULT);
      if ($sub_page === "pixelandanalytics") {
        require_once 'partials/wizard_pixelandanalytics.php';
      } elseif ($sub_page === "productfeed") {
        require_once 'partials/wizard_productfeed.php';
      }
    }

    public function conversios_account()
    {
      require_once(ENHANCAD_PLUGIN_DIR . 'includes/setup/account.php');
      new TVC_Account();
    }
    public function conversios_google_analytics()
    {
      $sub_page = (isset($_GET['subpage']) === TRUE) ? sanitize_text_field(wp_unslash($_GET['subpage'])) : "";
      if (!empty($sub_page)) {
        require_once('partials/single-pixel-settings.php');
      } else {
        require_once('partials/general-fields.php');
      }
    }

    public function conversios_analytics_reports()
    {
      require_once(ENHANCAD_PLUGIN_DIR . 'includes/setup/class-conversios-analytics-reports.php');
    }
    public function conversios_google_shopping_feed()
    {
      $action_tab = (isset($_GET['tab'])) ? sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'tab'))) : "";
      if ($action_tab == "product_list") {
        $this->product_list();
      }
      if (!isset($_GET['subpage']) && $action_tab !== 'product_list') {
        wp_safe_redirect(admin_url('admin.php?page=conversios-google-shopping-feed&subpage=gmc'));
        exit;
      }
      $action_tab = isset($_GET['subpage']) ? sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'subpage'))) : '';
      // $sub_page = (isset($_GET['subpage'])) ? sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'subpage'))) : "";
      if ($action_tab != "") {
        $this->load_channel_feed();
      } else {
        //new GoogleShoppingFeed();
        require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/class-tvc-product-sync-helper.php';
        //require_once 'partials/product-feed-list.php';
      }
    }
    public function gaa_config_page()
    {
      require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/class-tvc-product-sync-helper.php';
    }
    public function load_channel_feed()
    {
      require_once ENHANCAD_PLUGIN_DIR . 'admin/class-tvc-admin-helper.php';
      require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/CustomApi.php';
      require_once 'partials/productfeed/product-feed-list.php';
    }
    public function product_list()
    {
      require_once ENHANCAD_PLUGIN_DIR . 'admin/class-tvc-admin-helper.php';
      require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/CustomApi.php';
      require_once ENHANCAD_PLUGIN_DIR . 'admin/class-tvc-admin-db-helper.php';
      require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/tatvic-category-wrapper.php';
      require_once ENHANCAD_PLUGIN_DIR . 'includes/setup/class-tvc-product-sync-helper.php';
      require_once 'partials/productfeed/feedwise-product-list.php';
    }
    public function conversios_purchase_tracking()
    {
      require_once(ENHANCAD_PLUGIN_DIR . 'admin/partials/purchase-tracking/purchase-tracking-settings.php');
      if (class_exists('Conv_Purchase_Tracking_Settings')) {
        new Conv_Purchase_Tracking_Settings();
      }
    }

    public function conv_get_ore_data_handler() {
      check_ajax_referer('conversios_nonce', 'conversios_nonce');
      if (!current_user_can('manage_options')) {
          wp_send_json_error(['message' => 'Unauthorized']);
      }
      $start_date = isset($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : date('Y-m-d', strtotime('-30 days'));
      $end_date   = isset($_POST['end_date'])   ? sanitize_text_field($_POST['end_date'])   : date('Y-m-d');
      $draw       = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
      
      $start_timestamp = strtotime($start_date);
      $end_timestamp = strtotime($end_date . ' 23:59:59'); // Include the full end day
      
      $install_date = get_option('conversiosaiofree_install_date');
      if ($install_date) {
          $install_timestamp = strtotime($install_date);
          if ($install_timestamp > $start_timestamp) {
              $start_timestamp = $install_timestamp;
          }
      }
      
      $date_query_string = $start_timestamp . '...' . $end_timestamp;

      $total = 0;
      $data = [];
      
      if (class_exists('WooCommerce')) {
          $valid_statuses = ['processing', 'completed'];
          $args = [
              'type'          => 'shop_order',
              'status'        => $valid_statuses,
              'date_created'  => $date_query_string,
              'limit'         => -1,
              'return'        => 'ids',
          ];
          $order_ids = wc_get_orders($args);
          $total = count($order_ids);
          
          // Find orders WITHOUT _tracked meta (Missed Conversions)
          $args_untracked = $args;
          $args_untracked['meta_query'] = [
              [
                  'key'     => '_tracked',
                  'compare' => 'NOT EXISTS'
              ]
          ];
          $untracked_ids = wc_get_orders($args_untracked);
          $server_missed = count($untracked_ids);
          $client_tracked = $total - $server_missed;
          
          $total_loss = 0;
          // Calculate missed revenue for up to 1000 recent orders to maintain performance
          $loss_ids = array_slice($untracked_ids, 0, 1000);
          foreach ($loss_ids as $oid) {
              $order = wc_get_order($oid);
              if ($order) {
                  $total_loss += (float) $order->get_total();
              }
          }
          
          // Slice for pagination
          $start = isset($_POST['start']) ? intval($_POST['start']) : 0;
          $length = isset($_POST['length']) ? intval($_POST['length']) : 25;
          if ($length == -1) $length = $total;
          $page_ids = array_slice($order_ids, $start, $length);
          
          foreach ($page_ids as $order_id) {
              $order = wc_get_order($order_id);
              if (!$order) continue;
              
              $data[] = [
                  'number'                 => $order->get_order_number(),
                  'edit_url'               => $order->get_edit_order_url(),
                  'date'                   => $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i') : '',
                  'total'                  => $order->get_total(),
                  'status'                 => '<mark class="order-status status-' . esc_attr($order->get_status()) . '"><span>' . esc_html(wc_get_order_status_name($order->get_status())) . '</span></mark>',
                  'conv_order_tracked'     => 'none',
                  '_tracked'               => $order->get_meta('_tracked') ? true : false,
                  '_ore_synced_channels'   => null,
                  'conv_gclid'             => '',
                  'conv_fbclid'            => '',
                  'conv_wbraid'            => '',
                  'conv_gbraid'            => '',
                  '_fbp'                   => '',
                  '_fbc'                   => '',
                  '_ga'                    => '',
                  'conv_ga4_session_id'    => '',
                  'conv_ga4_session_number'=> '',
                  '_ga_sessions'           => []
              ];
          }
      }

      $response = [
          'draw' => $draw,
          'recordsTotal' => $total,
          'recordsFiltered' => $total,
          'data' => $data,
          'report' => [
              'total' => $total,
              'client' => $client_tracked,
              'server' => $server_missed,
              'recovered_revenue' => number_format($total_loss, 2, '.', ''),
              'synced' => 0
          ]
      ];
      
      wp_send_json($response);
    }
  }
}
if (is_admin()) {
  new Conversios_Admin();
}
