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

// For woocommerce
function bwdcv_WooCommerce_register_required_plugins() {
    $w_check_display = get_current_screen();
	if (isset( $w_check_display->parent_file) && 'plugins.php' === $w_check_display->parent_file && 'update' === $w_check_display->id) {
		return;
	}
	$bwd_w_plugin_plugin = 'woocommerce/woocommerce.php';
	if (bwdcv_WooCommerce_addon_install()) {
		if (!current_user_can('activate_plugins')) {
			return;
		}
		$bwd_w_plugin_active_url = wp_nonce_url('plugins.php?action=activate&plugin=' . $bwd_w_plugin_plugin . '&plugin_status=all&paged=1&s', 'activate-plugin_' . $bwd_w_plugin_plugin );
		$bwd_w_plugin_the_notice_is = '<p><b>WP CV Builder</b> requires WooCommerce to be activated.</p>';
        $bwd_w_plugin_the_notice_is .= '<p><a href="'. $bwd_w_plugin_active_url .'" class="button-primary">Activate WooCommerce</a></p>';
	} else {
		if (!current_user_can('install_plugins')) {
			return;
		}
		$w_install_url = wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=woocommerce'), 'install-plugin_woocommerce');
		$bwd_w_plugin_the_notice_is = '<p><b>WP CV Builder</b> requires WooCommerce to be installed and activated.</p>';
		$bwd_w_plugin_the_notice_is .= '<p><a href="'. $w_install_url .'" class="button-primary">Install WooCommerce</a></p>';
	}
	if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ):
	echo '<div class="notice notice-error"><p>' . $bwd_w_plugin_the_notice_is . '</p></div>';
	endif;
}

function bwdcv_WooCommerce_addon_install() {
    $w_file_path = 'woocommerce/woocommerce.php';
    $w_installed_plugins = get_plugins();
    return isset($w_installed_plugins[$w_file_path]);
}

/**
 * Calculate and store expiry date for a WooCommerce order
 *
 * @param \WC_Order $order
 * @param int $product_id The product ID
 * @return string|null Calculated expiry date in Y-m-d format or null
 */
function calculate_subscription_expiry_date($order, $product_id) {
  if (!$order || !$product_id) {
      return null;
  }
  // Get purchase date
  $purchase_date = $order->get_date_created();
  $formatted_purchase_date = $purchase_date ?
      $purchase_date->setTimezone(new \DateTimeZone(wp_timezone_string()))->format('Y-m-d') : null;
  if (!$formatted_purchase_date) {
      return null;
  }
  // Get billing period
  $subscription_billing_period = (int) $order->get_meta('_subscription_billing_period', true);
  if (!$subscription_billing_period) {
      $subscription_billing_period = get_post_meta($product_id, '_subscription_billing_period', true);
      if ($subscription_billing_period) {
          $order->update_meta_data('_subscription_billing_period', $subscription_billing_period);
          $order->save();
      }
  }
  // Calculate expiry date
  $expire_date = '';
  if ($subscription_billing_period) {
      $billing_days = 0;
      switch ($subscription_billing_period) {
          case '1':
              $billing_days = 1;
              break;
          case '30':
              $billing_days = 30;
              break;
          case '90':
              $billing_days = 90;
              break;
          case '183':
              $billing_days = 183;
              break;
          case '365':
              $billing_days = 365;
              break;
      }
      if ($billing_days) {
          $purchase_date_obj = new \DateTime($formatted_purchase_date);
          $purchase_date_obj->modify("+$billing_days days");
          $expire_date = $purchase_date_obj->format('Y-m-d');
          // Store expiry date in order meta
          $order->update_meta_data('_subscription_expiry_date', $expire_date);
          $order->save();
          return $expire_date;
      }
  } else {
      return esc_html__('Unlimited', 'cv-builder');
  }
  return null;
}

/**
 * Setup subscription expiry notification cron job
 */
function setup_subscription_expiry_notification_cron() {
  // Schedule the event if it's not already scheduled
  if (!wp_next_scheduled('check_subscription_expiry_notifications')) {
      wp_schedule_event(time(), 'daily', 'check_subscription_expiry_notifications');
  }
}
add_action('wp', 'setup_subscription_expiry_notification_cron');

/**
* Check for subscriptions that are about to expire and send notifications
*/
function check_subscription_expiry_notifications() {
    // Get all users with 'cv_editor' role
    $editor_users = get_users(array('role' => 'cv_editor'));
    if (empty($editor_users)) {
        return;
    }
    foreach ($editor_users as $user) {
        /**
         *
         * In this plugin, all checks are done using the order statuses 'wc-completed' and 'wc-processing', so for now, I've included only those two.
         *
         */
        $args = [
            'customer' => $user->ID,
            'limit' => -1,
            'orderby' => 'date',
            'order' => 'DESC',
            'status' => ['wc-completed', 'wc-processing'],
            'tax_query' => [
			    [
				    'taxonomy' => 'product_cat',
				    'field'    => 'slug',
				    'terms'    => 'cv-subscription',
			    ]
		    ]
        ];
        $customer_orders = wc_get_orders($args);
        if (empty($customer_orders)) {
            continue;
        }
        foreach ($customer_orders as $order) {
            $order_id = $order->get_id();
            $items = $order->get_items();
            if (empty($items)) {
                continue;
            }
            // Check if $items count is greater than 1
            $product_id = 0;
            if (count($items) > 1) {
                foreach ($items as $item) {
                    $product_id = $item->get_product_id();
                }
            } else {
                // Get the first item ID
                $item_ids = array_keys($items);
                $first_item_id = $item_ids[0];
                // Retrieve the product ID using the first item ID
                $product_id = $items[$first_item_id]->get_product_id();
            }
            $expire_date = $order->get_meta('_subscription_expiry_date', true);
            if (!$expire_date) {
                $expire_date = calculate_subscription_expiry_date($order, $product_id);
            }
            if (!$expire_date || $expire_date === esc_html__('Unlimited', 'cv-builder')) {
                continue;
            }
            $today = date('Y-m-d');
            $mail_send_date = date('Y-m-d', strtotime($expire_date . ' -5 days'));
            $already_sent = get_post_meta($order_id, '_expiry_notification_sent', true);
            if ($today === $mail_send_date && $already_sent !== $today) {
                $to = $user->user_email;
                $subject = 'Your subscription is expiring soon!';
                $message = 'Dear ' . $user->display_name . ', your subscription (Order #' . $order_id . ') will expire on ' . $expire_date . '. Please renew it in time.';
                $headers = array('Content-Type: text/html; charset=UTF-8');
                $send = wp_mail($to, $subject, $message, $headers);
                if ($send){
                update_post_meta($order_id, '_expiry_notification_sent', $today);
                }
            }
        }
    }
}

add_action('check_subscription_expiry_notifications', 'check_subscription_expiry_notifications');

/**
* Cleanup cron job on plugin deactivation
*/
function subscription_notification_deactivation() {
  $timestamp = wp_next_scheduled('check_subscription_expiry_notifications');
  if ($timestamp) {
      wp_unschedule_event($timestamp, 'check_subscription_expiry_notifications');
  }
}
register_deactivation_hook(__FILE__, 'subscription_notification_deactivation');

function bwdcv_track_visitors() {
  if ( ! isset( $_SESSION['last_activity'] ) ) {
    $_SESSION['last_activity'] = time();
  }
  $current_time = time();
  $timeout = YEAR_IN_SECONDS * 10000;
  $visitors = get_transient( 'bwdcv_live_visitors' ) ?: [];
  foreach ( $visitors as $key => $last_activity ) {
    if ( ( $current_time - $last_activity ) > $timeout ) {
      unset( $visitors[ $key ] );
    }
  }
  $visitors[ session_id() ] = $current_time;
  set_transient( 'bwdcv_live_visitors', $visitors, $timeout );
}
add_action( 'wp', 'bwdcv_track_visitors' );

// For K, M, B count
function bwdcv_format_number($number) {
  if ($number >= 1000000000) {
      return round($number / 1000000000, 1) . 'B';
  } elseif ($number >= 1000000) {
      return round($number / 1000000, 1) . 'M';
  } elseif ($number >= 1000) {
      return round($number / 1000, 1) . 'K';
  }
  return $number;
}

function bwdcv_get_live_visitor_count() {
  $visitors = get_transient('bwdcv_live_visitors', 0);
  $count = is_array($visitors) ? count($visitors) : (int) $visitors;
  return bwdcv_format_number($count);
}

function bwdcv_track_total_visitors() {
  $total_visitors = get_option( 'lvc_total_visitors', 0 );
  if ( ! isset( $_COOKIE['lvc_visitor'] ) ) {
    $total_visitors++;
    update_option( 'lvc_total_visitors', $total_visitors );
    setcookie( 'lvc_visitor', '1', time() + DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
  }
}
add_action( 'wp', 'bwdcv_track_total_visitors' );

function bwdcv_get_total_visitor_count() {
  $visitors = get_option('lvc_total_visitors', 0);
  $count = is_array($visitors) ? count($visitors) : (int) $visitors;
  return bwdcv_format_number($count);
}

function bwdcv_track_logged_in_users() {
  if ( is_user_logged_in() ) {
    $_SESSION['logged_in_users'][ get_current_user_id() ] = time();
  }
}
add_action( 'wp', 'bwdcv_track_logged_in_users' );

function bwdcv_get_logged_in_user_count() {
  return isset( $_SESSION['logged_in_users'] ) ? count( $_SESSION['logged_in_users'] ) : 0;
}
