<?php

namespace SmartSlotAppointmentScheduler;

if (! defined('ABSPATH')) {
	exit;
}

if (! class_exists('\SmartSlotAppointmentScheduler\Book_An_Appointment_Dashboard')) {

	/**
	 * Booking dashboard.
	 */
	class Book_An_Appointment_Dashboard {

		/**
		 * Cache group.
		 *
		 * @var string
		 */
		private const CACHE_GROUP = 'ssas_reports';

		/**
		 * Dashboard initialization.
		 *
		 * @return void
		 */
		public static function init() {
			add_action(
				'admin_menu',
				[__CLASS__, 'add_dashboard_menu'],
				9
			);
		}

		/**
		 * Add dashboard submenu.
		 *
		 * @return void
		 */
		public static function add_dashboard_menu() {

			add_submenu_page(
				'edit.php?post_type=ssas_schedule',
				esc_html__(
					'Dashboard',
					'smartslot-appointment-scheduler'
				),
				esc_html__(
					'Dashboard',
					'smartslot-appointment-scheduler'
				),
				'manage_options',
				'schedule-dashboard',
				[__CLASS__, 'render_dashboard_page'],
				0
			);
		}

		/**
		 * Render dashboard page.
		 *
		 * @return void
		 */
		public static function render_dashboard_page() {

			if (! current_user_can('manage_options')) {
				return;
			}

			global $wpdb;

			$table = 'pkart_' . 'ssas_booking_appointment';
			$today = current_time('Y-m-d');

			$cache_key = 'dashboard_data_' . md5(
				wp_json_encode(
					[
						'today'   => $today,
						'version' => self::get_cache_version(),
					]
				)
			);

			$dashboard_data = wp_cache_get(
				$cache_key,
				self::CACHE_GROUP
			);

			if (false === $dashboard_data) {

				// Pending appointments.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$pending = (int) $wpdb->get_var(
					$wpdb->prepare(
						'SELECT COUNT(*) FROM %i WHERE status = %d',
						$table,
						0
					)
				);

				// Approved upcoming appointments.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$approved = (int) $wpdb->get_var(
					$wpdb->prepare(
						'SELECT COUNT(*) FROM %i
						WHERE status = %d
						AND appointment_date >= %s',
						$table,
						1,
						$today
					)
				);

				// Cancelled appointments.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$cancelled = (int) $wpdb->get_var(
					$wpdb->prepare(
						'SELECT COUNT(*) FROM %i WHERE status = %d',
						$table,
						2
					)
				);

				// Completed appointments.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$completed = (int) $wpdb->get_var(
					$wpdb->prepare(
						'SELECT COUNT(*) FROM %i WHERE status = %d',
						$table,
						3
					)
				);

				// General booking statistics.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$stats = $wpdb->get_row(
					$wpdb->prepare(
						'SELECT
							COUNT(*) AS total,
							SUM(appointment_date = %s) AS today,
							SUM(appointment_date > %s) AS upcoming
						FROM %i',
						$today,
						$today,
						$table
					),
					ARRAY_A
				);

				$total_bookings = isset($stats['total'])
					? (int) $stats['total']
					: 0;

				$today_bookings = isset($stats['today'])
					? (int) $stats['today']
					: 0;

				$upcoming_bookings = isset($stats['upcoming'])
					? (int) $stats['upcoming']
					: 0;

				// Approved appointments.
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom plugin table requires direct query.
				$approved_items = $wpdb->get_results(
					$wpdb->prepare(
						'SELECT
							token_number,
							first_name,
							email,
							phone,
							notes,
							appointment_date,
							appointment_time
						FROM %i
						WHERE status = %d
						AND appointment_date >= %s
						ORDER BY appointment_date ASC
						LIMIT %d',
						$table,
						1,
						$today,
						10
					),
					ARRAY_A
				);

				$dashboard_data = [
					'pending'           => $pending,
					'approved'          => $approved,
					'cancelled'         => $cancelled,
					'completed'         => $completed,
					'total_bookings'    => $total_bookings,
					'today_bookings'    => $today_bookings,
					'upcoming_bookings' => $upcoming_bookings,
					'approved_items'    => $approved_items,
				];

				wp_cache_set(
					$cache_key,
					$dashboard_data,
					self::CACHE_GROUP,
					MINUTE_IN_SECONDS
				);
			}

			$pending = (int) $dashboard_data['pending'];
			$approved = (int) $dashboard_data['approved'];
			$cancelled = (int) $dashboard_data['cancelled'];
			$completed = (int) $dashboard_data['completed'];
			$total_bookings = (int) $dashboard_data['total_bookings'];
			$today_bookings = (int) $dashboard_data['today_bookings'];
			$upcoming_bookings = (int) $dashboard_data['upcoming_bookings'];
			$approved_items = (array) $dashboard_data['approved_items'];

			$report_url = add_query_arg(
				[
					'post_type'             => 'ssas_schedule',
					'page'                  => 'schedule-reports',
					'booking_report_nonce' => wp_create_nonce(
						'booking_report_filters'
					),
				],
				admin_url('edit.php')
			);

			?>
			<div class="wrap sbm-dashboard-wrapper">

				<?php
				$current_user = wp_get_current_user();
				$ssas_uname   = $current_user->display_name;
				?>

				<h1>
					<?php
					printf(
						/* translators: %s: Logged-in user's display name. */
						esc_html__(
							'Hello %s 👋',
							'smartslot-appointment-scheduler'
						),
						esc_html($ssas_uname)
					);
					?>
				</h1>

				<p>
					<?php
					printf(
						wp_kses_post(
							/* translators: 1: Number of approved appointments; 2: Number of upcoming bookings. */
							__(
								'You have %1$s approved appointments and %2$s upcoming bookings',
								'smartslot-appointment-scheduler'
							)
						),
						'<strong>' . esc_html($approved) . '</strong>',
						'<strong>' . esc_html($upcoming_bookings) . '</strong>'
					);
					?>
				</p>

				<div class="sbm-dashboard-grid">

					<?php
					$cards = [
						[
							'title' => __(
								'Total Bookings',
								'smartslot-appointment-scheduler'
							),
							'value' => $total_bookings,
							'url'   => $report_url,
						],
						[
							'title' => __(
								'Today Bookings',
								'smartslot-appointment-scheduler'
							),
							'value' => $today_bookings,
							'url'   => add_query_arg(
								'filter',
								'today',
								$report_url
							),
						],
						[
							'title' => __(
								'Upcoming Bookings',
								'smartslot-appointment-scheduler'
							),
							'value' => $upcoming_bookings,
							'url'   => add_query_arg(
								'filter',
								'upcoming',
								$report_url
							),
						],
					];

					foreach ($cards as $card) :
						?>

						<div class="sbm-grid-content">

							<h3>
								<?php echo esc_html($card['title']); ?>
							</h3>

							<div class="sbm-big-num">
								<span>
									<?php echo esc_html($card['value']); ?>
								</span>
							</div>

							<div class="sbm-redirection">
								<a href="<?php echo esc_url($card['url']); ?>">
									<?php echo esc_html($card['title']); ?>
								</a>
							</div>

						</div>

					<?php endforeach; ?>

				</div>

				<div class="sbm-dashboard-grid sbm-two-column-grid">

					<div class="sbm-grid-full-content">

						<div class="sbm-heading">

							<h3>
								<?php
								echo esc_html__(
									'Approved Appointments',
									'smartslot-appointment-scheduler'
								);
								?>
							</h3>

						</div>

					</div>

					<div class="sbm-grid-table">

						<?php if (! empty($approved_items)) : ?>

							<table class="widefat fixed striped">

								<thead>

									<tr>

										<th>
											<?php
											esc_html_e(
												'Token',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Name',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Email',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Phone',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Notes',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Date',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

										<th>
											<?php
											esc_html_e(
												'Time',
												'smartslot-appointment-scheduler'
											);
											?>
										</th>

									</tr>

								</thead>

								<tbody>

									<?php foreach ($approved_items as $row) : ?>

										<tr>

											<td>
												<?php
												echo esc_html(
													$row['token_number']
												);
												?>
											</td>

											<td>
												<?php
												echo esc_html(
													$row['first_name']
												);
												?>
											</td>

											<td>
												<?php
												echo esc_html(
													$row['email']
												);
												?>
											</td>

											<td>
												<?php
												echo esc_html(
													$row['phone']
												);
												?>
											</td>

											<td>
												<?php
												echo esc_html(
													$row['notes']
												);
												?>
											</td>

											<td>
												<?php
												echo esc_html(
													$row['appointment_date']
												);
												?>
											</td>

											<td>
												<?php
												$appointment_timestamp = strtotime(
													$row['appointment_time']
												);

												if (false !== $appointment_timestamp) {
													echo esc_html(
														wp_date(
															'h:i A',
															$appointment_timestamp
														)
													);
												} else {
													echo esc_html(
														$row['appointment_time']
													);
												}
												?>
											</td>

										</tr>

									<?php endforeach; ?>

								</tbody>

							</table>

						<?php else : ?>

							<p>
								<?php
								esc_html_e(
									'No approved bookings found.',
									'smartslot-appointment-scheduler'
								);
								?>
							</p>

						<?php endif; ?>

					</div>

				</div>

				<div class="sbm-dashboard-grid">

					<?php
					$appointment_cards = [
						[
							'title' => __(
								'Pending Appointments',
								'smartslot-appointment-scheduler'
							),
							'value' => $pending,
							'url'   => add_query_arg(
								'status',
								0,
								$report_url
							),
							'class' => 'free-version',
							'enable' => 'enabled_btn',
						],
						[
							'title' => __(
								'Cancelled Appointments',
								'smartslot-appointment-scheduler'
							),
							'value' => $cancelled,
							'url'   => add_query_arg(
								'status',
								2,
								$report_url
							),
							'class' => 'pro-version',
							'enable' => 'disable_btn',
						],
						[
							'title' => __(
								'Completed Appointments',
								'smartslot-appointment-scheduler'
							),
							'value' => $completed,
							'url'   => add_query_arg(
								'status',
								3,
								$report_url
							),
							'class' => 'free-version',
							'enable' => 'enabled_btn',
						],
					];

					foreach ($appointment_cards as $card) :
						?>

						<div class="sbm-grid-content <?php echo esc_attr($card['class']); ?>">

							<div class="sbm-title">

								<h3>
									<?php
									echo esc_html($card['title']);
									?>
								</h3>

							</div>

							<div class="sbm-big-num">

								<span>
									<?php
									echo esc_html($card['value']);
									?>
								</span>

							</div>

							<div class="sbm-redirection">

								<a
									href="<?php echo esc_url($card['url']); ?>"
									class="<?php echo esc_attr($card['enable']); ?>"
								>
									<?php
									echo esc_html($card['title']);
									?>
								</a>

							</div>

						</div>

					<?php endforeach; ?>

				</div>

			</div>
			<?php
		}

		/**
		 * Get dashboard cache version.
		 *
		 * @return int|float
		 */
		private static function get_cache_version() {

			$version = wp_cache_get(
				'reports_cache_version',
				self::CACHE_GROUP
			);

			if (false === $version) {

				$version = 1;

				wp_cache_set(
					'reports_cache_version',
					$version,
					self::CACHE_GROUP
				);
			}

			return $version;
		}
	}

	/**
	 * Initialize dashboard.
	 */
	Book_An_Appointment_Dashboard::init();
}
