<?php
/**
 * Dashboard Template
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Templates\Admin\Dashboard;

use DDWCPointsAndRewards\Helper\Dashboard\DDWCPR_Dashboard_Helper;
use DevDiggers\Framework\Includes\DDFW_SVG;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Dashboard_Template' ) ) {
	/**
	 * Dashboard template class
	 */
	class DDWCPR_Dashboard_Template {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Dashboard Helper Variable
		 *
		 * @var object
		 */
		protected $dashboard_helper;

		/**
		 * Dashboard Data Variable
		 *
		 * @var array
		 */
		protected $dashboard_data;

		/**
		 * Construct
		 * 
		 * @param array $ddwcpr_configuration
		 */
		public function __construct( $ddwcpr_configuration ) {
			$this->ddwcpr_configuration = $ddwcpr_configuration;
			$this->dashboard_helper     = new DDWCPR_Dashboard_Helper( $ddwcpr_configuration );
			$this->dashboard_data       = $this->dashboard_helper->get_dashboard_data();

			$this->render();
		}

		/**
		 * Render dashboard
		 *
		 * @return void
		 */
		protected function render() {
			wp_enqueue_script( 'ddwcpr-dashboard-script' );

			// Localize dashboard script with chart data, WordPress date format and translations
			wp_localize_script(
				'ddwcpr-dashboard-script',
				'ddwcprDashboardData',
				[
					'pointsChart'           => $this->dashboard_data['charts']['points_earned_vs_redeemed'],
					'revenueImpactChart'    => $this->dashboard_data['charts']['revenue_impact'],
					'dateRange'             => $this->dashboard_data['date_range'],
					'i18n'                  => [
						'pointsEarned'   => esc_html__( 'Points Earned', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'pointsRedeemed' => esc_html__( 'Points Redeemed', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'points'         => esc_html__( 'Points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'revenue'        => esc_html__( 'Revenue', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noPerformanceData' => esc_html__( 'No performance data available', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noPerformanceDataDesc' => esc_html__( 'Start earning and redeeming points to see your performance trends here.', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noEarningSourcesData' => esc_html__( 'No earning sources data', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noEarningSourcesDataDesc' => esc_html__( 'Points will appear here once customers start earning through various activities.', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noRevenueData' => esc_html__( 'No revenue data available', 'loyaltyx-points-and-rewards-for-woocommerce' ),
						'noRevenueDataDesc' => esc_html__( 'Revenue comparison will appear once orders are placed with and without rewards.', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					]
				]
			);

			$current_user = wp_get_current_user();

			?>
			<div class="ddwcpr-dashboard">
				<!-- Enhanced Dashboard Header -->
				<div class="ddwcpr-dashboard-header">
					<!-- Header Top Section -->
					<div class="ddwcpr-header-top">
						<div class="ddwcpr-header-left">
							<div class="ddwcpr-welcome-section">
								<div class="ddwcpr-welcome-content">
									<div class="ddwcpr-admin-avatar">
										<img src="<?php echo esc_url( get_avatar_url( $current_user->ID, [ 'size' => 48 ] ) ); ?>" alt="<?php echo esc_attr( $current_user->display_name ); ?>" class="ddwcpr-avatar-image" />
									</div>
									<div class="ddwcpr-welcome-message">
										<h1><?php printf( esc_html__( 'Welcome back, %s! 👋🏻', 'loyaltyx-points-and-rewards-for-woocommerce' ), $current_user->display_name ); ?></h1>
										<p class="ddwcpr-welcome-subtitle"><?php esc_html_e( 'Here\'s what\'s happening with your points and rewards program', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
									</div>
								</div>
							</div>
						</div>

						<div class="ddwcpr-header-right">
							<div class="ddwcpr-dashboard-filters">
								<form method="get" class="ddwcpr-date-filter-form">
									<input type="hidden" name="page" value="<?php echo esc_attr( ! empty( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '' ); ?>" />
									<input type="hidden" name="menu" value="<?php echo esc_attr( ! empty( $_GET['menu'] ) ? sanitize_text_field( wp_unslash( $_GET['menu'] ) ) : '' ); ?>" />

									<div class="ddwcpr-date-range-container">
										<input type="text"
											id="ddwcpr-date-range-picker"
											class="ddwcpr-date-range-picker"
											value="<?php echo esc_attr( $this->dashboard_data['date_range']['label'] ); ?>"
											readonly />

										<div class="ddwcpr-date-range-dropdown" id="ddwcpr-date-range-dropdown">
											<div class="ddwcpr-dropdown-content">
												<div class="ddwcpr-date-presets">
													<div class="ddwcpr-presets-header">
														<h4><?php esc_html_e( 'Quick Select', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h4>
													</div>
													<button type="button" class="ddwcpr-date-preset" data-range="today"><?php esc_html_e( 'Today', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="7_days"><?php esc_html_e( 'This Week', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="last_week"><?php esc_html_e( 'Last Week', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="30_days"><?php esc_html_e( 'This Month', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="last_month"><?php esc_html_e( 'Last Month', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="90_days"><?php esc_html_e( 'Last 3 Months', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="180_days"><?php esc_html_e( 'Last 6 Months', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="year_to_date"><?php esc_html_e( 'Year to Date', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="last_year"><?php esc_html_e( 'Last Year', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
													<button type="button" class="ddwcpr-date-preset" data-range="all_time"><?php esc_html_e( 'All Time', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
												</div>

												<div class="ddwcpr-custom-date-range">
													<div class="ddwcpr-custom-header">
														<h4><?php esc_html_e( 'Custom Range', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></h4>
														<p><?php esc_html_e( 'Select specific start and end dates for your analysis', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></p>
													</div>
													<div class="ddwcpr-date-inputs">
														<div class="ddwcpr-date-input-group">
															<label for="ddwcpr-from-date"><?php esc_html_e( 'From Date', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label>
															<input type="date" name="from_date" id="ddwcpr-from-date" value="<?php echo esc_attr( ! empty( $_GET['from_date'] ) ? sanitize_text_field( wp_unslash( $_GET['from_date'] ) ) : sanitize_text_field( wp_unslash( $this->dashboard_data['date_range']['from'] ) ) ); ?>" />
														</div>
														<div class="ddwcpr-date-input-group">
															<label for="ddwcpr-to-date"><?php esc_html_e( 'To Date', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label>
															<input type="date" name="to_date" id="ddwcpr-to-date" value="<?php echo esc_attr( ! empty( $_GET['to_date'] ) ? sanitize_text_field( wp_unslash( $_GET['to_date'] ) ) : sanitize_text_field( wp_unslash( $this->dashboard_data['date_range']['to'] ) ) ); ?>" />
														</div>
													</div>
													<button type="button" class="ddwcpr-apply-custom-range button button-primary"><?php esc_html_e( 'Apply Custom Range', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
												</div>
											</div>
										</div>

										<input type="hidden" name="date_range" id="ddwcpr-selected-range" value="<?php echo esc_attr( ! empty( $_GET['date_range'] ) ? sanitize_text_field( wp_unslash( $_GET['date_range'] ) ) : '30_days' ); ?>" />
									</div>
								</form>
							</div>
						</div>
					</div>
				</div>

				<div class="ddwcpr-dashboard-top-section">
					<!-- Summary Cards -->
					<div class="ddwcpr-summary-cards">
						<?php
						$this->render_summary_card(
							esc_html__( 'Total Points Issued', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							$this->dashboard_data['summary']['total_points_issued']['value'],
							$this->dashboard_data['summary']['total_points_issued']['change'],
							$this->dashboard_data['summary']['total_points_issued']['is_positive'],
							DDFW_SVG::get_svg_icon( 'total_earned_points', true ),
						);

						$this->render_summary_card(
							esc_html__( 'Total Points Redeemed', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							$this->dashboard_data['summary']['total_points_redeemed']['value'],
							$this->dashboard_data['summary']['total_points_redeemed']['change'],
							$this->dashboard_data['summary']['total_points_redeemed']['is_positive'],
							DDFW_SVG::get_svg_icon( 'redeemed_points', true ),
						);

						$this->render_summary_card(
							esc_html__( 'Outstanding Points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							$this->dashboard_data['summary']['outstanding_points']['value'],
							$this->dashboard_data['summary']['outstanding_points']['change'],
							$this->dashboard_data['summary']['outstanding_points']['is_positive'],
							DDFW_SVG::get_svg_icon( 'available_points', true ),
						);

						$this->render_summary_card(
							esc_html__( 'Active Coupons', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							$this->dashboard_data['summary']['active_coupons']['value'],
							$this->dashboard_data['summary']['active_coupons']['change'],
							$this->dashboard_data['summary']['active_coupons']['is_positive'],
							DDFW_SVG::get_svg_icon( 'converted_coupons', true ),
						);

						$this->render_summary_card(
							esc_html__( 'Revenue from Rewards', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							wc_price( $this->dashboard_data['summary']['revenue_with_rewards']['value'] ),
							$this->dashboard_data['summary']['revenue_with_rewards']['change'],
							$this->dashboard_data['summary']['revenue_with_rewards']['is_positive'],
							'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
							'html'
						);

						$this->render_summary_card(
							esc_html__( 'Total Discount Given', 'loyaltyx-points-and-rewards-for-woocommerce' ),
							wc_price( $this->dashboard_data['summary']['total_discount_value']['value'] ),
							$this->dashboard_data['summary']['total_discount_value']['change'],
							false,
							'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 5L5 19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="7" cy="7" r="2" stroke="currentColor" stroke-width="2"/><circle cx="17" cy="17" r="2" stroke="currentColor" stroke-width="2"/></svg>',
							'html'
						);
						?>
					</div>
					</div>

				<!-- Charts Section - Revenue full width above -->
				<div class="ddwcpr-dashboard-charts-section">
					<div class="ddwcpr-chart-container">
						<h3>
							<?php esc_html_e( 'Revenue Impact Analysis', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
							<span class="ddwcpr-chart-date-range"><?php echo esc_html( $this->dashboard_data['date_range']['label'] ); ?></span>
						</h3>
						<div class="ddwcpr-chart" id="ddwcpr-revenue-chart">
							<canvas id="revenue-impact-chart"></canvas>
						</div>
					</div>
					<div class="ddwcpr-chart-container">
						<h3>
							<?php esc_html_e( 'Points Performance', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
							<span class="ddwcpr-chart-date-range"><?php echo esc_html( $this->dashboard_data['date_range']['label'] ); ?></span>
						</h3>
						<div class="ddwcpr-chart" id="ddwcpr-points-chart">
							<canvas id="points-earned-redeemed-chart"></canvas>
						</div>
					</div>
				</div>

				<!-- Tables Section - 2 Column Layout -->
				<div class="ddwcpr-dashboard-tables-section">
					<!-- Recent Activities -->
					<div class="ddwcpr-sidebar-widget">
						<h3>
							<?php esc_html_e( 'Recent Activities', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
						</h3>
						<?php $this->render_recent_activities_list(); ?>
					</div>

					<!-- Top Customers -->
					<div class="ddwcpr-sidebar-widget">
						<h3>
							<?php esc_html_e( 'Top Customers', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
						</h3>
						<?php $this->render_top_customers_list(); ?>
					</div>
				</div>
			</div>
			<?php
		}

		/**
		 * Render summary card
		 *
		 * @param string $title
		 * @param mixed $value
		 * @param float $change
		 * @param bool $is_positive
		 * @param string $icon_svg
		 * @param string $value_type
		 * @return void
		 */
		protected function render_summary_card( $title, $value, $change, $is_positive, $icon_svg, $value_type = 'number' ) {
			?>
			<div class="ddwcpr-summary-card">
				<div class="ddwcpr-card-header">
					<div class="ddwcpr-card-icon"><?php echo wp_kses( $icon_svg, ddfw_kses_allowed_svg_tags() ); ?></div>
					<?php
					if ( $change !== 0 ) {
						?>
						<div class="ddwcpr-change-indicator <?php echo esc_attr( $is_positive ? 'positive' : 'negative' ); ?>">
							<?php
							if ( $is_positive ) {
								?>
								<svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
									<path d="M23 6l-9.5 9.5-5-5L1 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M17 6h6v6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
								</svg>
								<?php
							} else {
								?>
								<svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
									<path d="M23 18l-9.5-9.5-5 5L1 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M17 18h6v-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
								</svg>
								<?php
							}
							?>
							<span><?php echo esc_html( $change ); ?>%</span>
						</div>
						<?php
					}
					?>
				</div>
					<div class="ddwcpr-card-content">
					<h4><?php echo esc_html( $title ); ?></h4>
					<div class="ddwcpr-card-value">
						<?php
						if ( 'number' === $value_type ) {
							?>
							<span class="ddwcpr-value-number"><?php echo esc_html( number_format( $value ) ); ?></span>
							<?php
						} elseif ( 'html' === $value_type ) {
							?>
							<span class="ddwcpr-value-text"><?php echo wp_kses_post( $value ); ?></span>
							<?php
						} else {
							?>
							<span class="ddwcpr-value-text"><?php echo esc_html( $value ); ?></span>
							<?php
						}
						?>
					</div>
				</div>
			</div>
			<?php
		}

		/**
		 * Render recent activities list
		 *
		 * @return void
		 */
		protected function render_recent_activities_list() {
			$activities = $this->dashboard_data['tables']['recent_activities'];
			?>
			<div class="ddwcpr-recent-items">
				<?php
				if ( ! empty( $activities ) ) {
					foreach ( array_slice( $activities, 0, 5 ) as $activity ) {
						?>
						<div class="ddwcpr-recent-item">
							<div class="ddwcpr-recent-info">
								<div class="ddwcpr-recent-customer">
									<?php
									if ( ! empty( $activity['display_name'] ) ) {
										?>
										<strong><?php echo esc_html( $activity['display_name'] ); ?></strong>
										<?php
									} else {
										?>
										<strong><?php esc_html_e( 'Guest', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong>
										<?php
									}
									?>
								</div>
								<div class="ddwcpr-recent-action">
									<?php echo esc_html( ddwcpr_get_translation( $activity['event'] ) ); ?>
									<span class="ddwcpr-recent-date">
										• <?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $activity['date'] ) ) ); ?>
									</span>
								</div>
							</div>
							<div class="ddwcpr-recent-points">
								<?php
								if ( $activity['points'] > 0 ) {
									?>
									<span class="ddwcpr-added">+<?php echo esc_html( $activity['points'] ); ?></span>
									<?php
								} else {
									?>
									<span class="ddwcpr-deducted"><?php echo esc_html( $activity['points'] ); ?></span>
									<?php
								}
								?>
							</div>
						</div>
						<?php
					}
				} else {
					?>
					<div class="ddwcpr-no-data">
						<?php esc_html_e( 'No recent activities', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
					</div>
					<?php
				}
				?>
			</div>
			<?php
		}

		/**
		 * Render top customers list
		 *
		 * @return void
		 */
		protected function render_top_customers_list() {
			$customers = $this->dashboard_helper->get_top_customers_by_points( 5 );
			?>
			<div class="ddwcpr-customers-items">
				<?php
				if ( ! empty( $customers ) ) {
					foreach ( $customers as $customer ) {
						?>
						<div class="ddwcpr-customer-item">
							<div class="ddwcpr-customer-avatar">
								<?php echo get_avatar( $customer['ID'], 32 ); ?>
							</div>
							<div class="ddwcpr-customer-info">
								<div class="ddwcpr-customer-name">
									<strong><?php echo esc_html( $customer['display_name'] ); ?></strong>
								</div>
								<div class="ddwcpr-customer-balance">
									<?php echo esc_html( number_format( $customer['current_balance'] ) ); ?> <?php esc_html_e( 'points', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
								</div>
							</div>
						</div>
						<?php
					}
				} else {
					?>
					<div class="ddwcpr-no-data">
						<?php esc_html_e( 'No customer data', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>
					</div>
					<?php
				}
				?>
			</div>
			<?php
		}
	}
}
