<?php
/**
 * Admin Menu functionality
 *
 * @link       https://mediahubster.in
 * @since      1.0.0
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin Menu class
 *
 * Handles dashboard submenu functionality and statistics.
 *
 * @since      1.0.0
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 * @author     Joe Youngblood <support@subscriptionplugin.com>
 */
class Subs_Sys_Admin_Menu {

	/**
	 * Add Dashboard submenu to the Subscriptions menu
	 *
	 * @since 1.0.0
	 */
	public function add_dashboard_submenu() {
		add_submenu_page(
			'edit.php?post_type=subscription', // Parent menu slug
			__( 'Dashboard', 'subscription-system' ), // Page title
			__( 'Dashboard', 'subscription-system' ), // Menu title
			'manage_options', // Capability
			'subscription-dashboard', // Menu slug
			array( $this, 'render_dashboard_page' ) // Callback function
		);
	}

	/**
	 * Render the Dashboard page content
	 *
	 * @since 1.0.0
	 */
	public function render_dashboard_page() {
		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'subscription-system' ) );
		}

		// Get subscription statistics
		$active_subscriptions = $this->get_subscription_count( 'active' );
		$paused_subscriptions = $this->get_subscription_count( 'paused' );
		$total_revenue = $this->get_total_revenue();
		
		// Include the dashboard template
		include plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/dashboard-display.php';
	}

	/**
	 * Get subscription count by status
	 * 
	 * @since 1.0.0
	 * @param string $status The subscription status to count.
	 * @return int The number of subscriptions with the given status.
	 */
	private function get_subscription_count( $status ) {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'subscriptions';
		
		$count = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table_name} WHERE status = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				$status
			)
		);
		
		return $count ? (int) $count : 0;
	}

	/**
	 * Get total revenue from all subscriptions
	 * 
	 * @since 1.0.0
	 * @return float The total revenue.
	 */
	private function get_total_revenue() {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'subscriptions';
		
		$total = $wpdb->get_var($wpdb->prepare(
			"SELECT SUM(amount) FROM `{$table_name}` WHERE status = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			'active'
		));
		
		return $total ? (float) $total : 0.0;
	}
} 