<?php
/**
 * Preciousuite alert center view.
 *
 * @package Preciousuite
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
$gpbw_modules = PreciousSuite_Registry::instance()->all();
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$gpbw_catalog = pt_gold_get_catalog();
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$gpbw_installed = count($gpbw_modules);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$gpbw_total = count($gpbw_catalog);

$rates_configured = '' !== get_option('gold', '') && '' !== get_option('silver', '') && '' !== get_option('platinum', '');
$product_total = 0;
$product_selected_count = 0;
$physical_product_total = 0;
$product_weight_count = 0;

if (post_type_exists('product')) {
	$product_statuses = array('publish', 'draft', 'pending', 'private');
	$product_query = new WP_Query(
		array(
			'post_type' => 'product',
			'post_status' => $product_statuses,
			'fields' => 'ids',
			'posts_per_page' => 1,
		)
	);
	$product_selected_query = new WP_Query(
		array(
			'post_type' => 'product',
			'post_status' => $product_statuses,
			'fields' => 'ids',
			'posts_per_page' => 1,
			'meta_query' => array(
				array(
					'key' => 'jewellery_field',
					'value' => array('1', '2', '3'),
					'compare' => 'IN',
				),
			),
		)
	);
	$physical_product_query = new WP_Query(
		array(
			'post_type' => 'product',
			'post_status' => $product_statuses,
			'fields' => 'ids',
			'posts_per_page' => 1,
			'meta_query' => array(
				'relation' => 'OR',
				array(
					'key' => '_virtual',
					'compare' => 'NOT EXISTS',
				),
				array(
					'key' => '_virtual',
					'value' => 'yes',
					'compare' => '!=',
				),
			),
		)
	);
	$product_weight_query = new WP_Query(
		array(
			'post_type' => 'product',
			'post_status' => $product_statuses,
			'fields' => 'ids',
			'posts_per_page' => 1,
			'meta_query' => array(
				'relation' => 'AND',
				array(
					'relation' => 'OR',
					array(
						'key' => '_virtual',
						'compare' => 'NOT EXISTS',
					),
					array(
						'key' => '_virtual',
						'value' => 'yes',
						'compare' => '!=',
					),
				),
				array(
					'key' => '_weight',
					'value' => '',
					'compare' => '!=',
				),
				array(
					'key' => '_weight',
					'value' => '0',
					'compare' => '!=',
				),
			),
		)
	);
	$product_total = (int) $product_query->found_posts;
	$product_selected_count = (int) $product_selected_query->found_posts;
	$physical_product_total = (int) $physical_product_query->found_posts;
	$product_weight_count = (int) $product_weight_query->found_posts;
}

$product_remaining_count = max(0, $product_total - $product_selected_count);
$weight_remaining_count = max(0, $physical_product_total - $product_weight_count);

$gold_price_has_remaining = !$rates_configured || ($product_total > 0 && 0 < $product_remaining_count) || ($physical_product_total > 0 && 0 < $weight_remaining_count);

$buyback_has_remaining = false;
if (isset($gpbw_modules['buyback-calculator'])) {
	$buyback_rate_done = '' !== get_option('preciousuite_manual_gold_rate', '');
	$buyback_margin_done = '' !== get_option('preciousuite_buyback_margin', '');
	$buyback_currency_done = '' !== get_option('preciousuite_currency', '');
	$whatsapp_done = '' !== get_option('preciousuite_whatsapp_number', '');
	$smtp_enabled = get_option('preciousuite_smtp_enable', '');
	$smtp_host = get_option('preciousuite_smtp_host', '');
	$smtp_port = get_option('preciousuite_smtp_port', '');
	$smtp_user = get_option('preciousuite_smtp_username', '');
	$smtp_pass = get_option('preciousuite_smtp_password', '');
	$smtp_done = ('1' === $smtp_enabled) || ('' !== $smtp_host && '' !== $smtp_port && '0' !== $smtp_port && '' !== $smtp_user && '' !== $smtp_pass);

	$buyback_has_remaining = !$buyback_rate_done || !$buyback_margin_done || !$buyback_currency_done || !$whatsapp_done || !$smtp_done;
}

$invoice_has_remaining = false;
if (isset($gpbw_modules['invoice-generator'])) {
	$shop_name_done = '' !== get_option('jicg_shop_name', '');
	$invoice_prefix_done = '' !== get_option('jicg_invoice_prefix', '');
	$tax_done = '' !== get_option('jicg_tax_mode', '');
	$cert_done = '' !== get_option('jicg_cert_title', '');
	$currency_done = true;
	$template_done = true;
	$whatsapp_done_inv = '' !== get_option('jicg_whatsapp_message', '');

	$invoice_has_remaining = !$shop_name_done || !$invoice_prefix_done || !$tax_done || !$cert_done || !$currency_done || !$template_done || !$whatsapp_done_inv;
}

$savings_has_remaining = false;
if (isset($gpbw_modules['gold-savings-scheme'])) {
	$razorpay_key_done = '' !== get_option('ps_gs_razorpay_key_id', '');
	$razorpay_secret_done = '' !== get_option('ps_gs_razorpay_secret_key', '');
	$manual_price_done = '' !== get_option('ps_gs_manual_gold_price', '');

	$savings_has_remaining = !$razorpay_key_done || !$razorpay_secret_done || !$manual_price_done;
}

$problems = array();
if ($gpbw_installed < $gpbw_total) {
	$problems[] = array(
		'plugin_name' => '',
		'type' => 'missing_modules',
	);
}
if ($gold_price_has_remaining) {
	$problems[] = array(
		'plugin_name' => __('Gold Price Based on Weight', 'preciousuite-metal-rate-charts'),
		'type' => 'remaining_tasks',
	);
}
if ($buyback_has_remaining) {
	$problems[] = array(
		'plugin_name' => __('Gold Buyback Quote Calculator', 'preciousuite-metal-rate-charts'),
		'type' => 'remaining_tasks',
	);
}
if ($invoice_has_remaining) {
	$problems[] = array(
		'plugin_name' => __('Jewelry Invoice & Certificate Generator', 'preciousuite-metal-rate-charts'),
		'type' => 'remaining_tasks',
	);
}
if ($savings_has_remaining) {
	$problems[] = array(
		'plugin_name' => __('Gold Savings Scheme', 'preciousuite-metal-rate-charts'),
		'type' => 'remaining_tasks',
	);
}

$gpbw_alert_count = count($problems);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$gpbw_notifications = array(
	// array(
	// 	'title' => __('Keep pricing accurate before customers browse.', 'preciousuite-metal-rate-charts'),
	// 	'desc' => __('Review gold, silver, and platinum rates regularly so product prices, and buyback quotes stay aligned.', 'preciousuite-metal-rate-charts'),
	// 	'url' => isset($gpbw_modules['gold-price']) ? $gpbw_modules['gold-price']['settings_url'] : admin_url('admin.php?page=gold-price'),
	// 	'label' => __('Review rates', 'preciousuite-metal-rate-charts'),
	// ),
	// array(
	// 	'title' => __('Publish customer-facing shortcodes.', 'preciousuite-metal-rate-charts'),
	// 	'desc' => __('Buyback calculators, and helpful quote widgets on the pages where shoppers make decisions.', 'preciousuite-metal-rate-charts'),
	// 	'url' => admin_url('admin.php?page=preciousuite-support'),
	// 	'label' => __('View guide', 'preciousuite-metal-rate-charts'),
	// ),
	// array(
	// 	'title' => __('Protect private store and customer data.', 'preciousuite-metal-rate-charts'),
	// 	'desc' => __('When asking for support, include the page name and expected result, but avoid API keys, passwords, and customer records.', 'preciousuite-metal-rate-charts'),
	// 	'url' => admin_url('admin.php?page=preciousuite-support'),
	// 	'label' => __('Support tips', 'preciousuite-metal-rate-charts'),
	// ),
);
?>

<div class="wrap precioussuite-wrap preciousuite-wrap preciousuite-dashboard preciousuite-alert-center-page">
	<div class="preciousuite-dashboard-shell">
		<aside class="preciousuite-dashboard-nav">
			<div class="preciousuite-dashboard-brand">
				<div class="preciousuite-page-brand">
					<div class="preciousuite-box preciousuite-logo">
						<a href="<?php echo esc_url("https://www.preciousuite.com"); ?>" target="_blank"
							rel="noopener noreferrer" class="preciousuite-page-title">
							<img src="<?php echo esc_url(PMRCGOLD_URL . 'includes/precioussuite/assets/' . 'uploads/Preciousuite_Logo.png'); ?>"
								alt="<?php esc_attr_e('Preciousuite Logo', 'preciousuite-metal-rate-charts'); ?>">
						</a>
					</div>
				</div>
			</div>
			<nav>
				<a href="<?php echo esc_url(admin_url('admin.php?page=preciousuite')); ?>">
					<img src="<?php echo esc_url(PMRCGOLD_URL . 'includes/precioussuite/assets/' . '/uploads/dashboard-icon.png'); ?>"
						alt="<?php esc_attr_e('General', 'preciousuite-metal-rate-charts'); ?>" width="20" height="20"
						loading="lazy" style="margin-right: .75rem;" />
					<?php esc_html_e('General', 'preciousuite-metal-rate-charts'); ?>
				</a>
				<a href="<?php echo esc_url(admin_url('admin.php?page=preciousuite-tasks')); ?>">
					<img src="<?php echo esc_url(PMRCGOLD_URL . 'includes/precioussuite/assets/' . '/uploads/task-list-icon.png'); ?>"
						alt="<?php esc_attr_e('General', 'preciousuite-metal-rate-charts'); ?>" width="20" height="20"
						loading="lazy" style="margin-right: .75rem;" />
					<?php esc_html_e('Task list', 'preciousuite-metal-rate-charts'); ?>
				</a>
				<a class="is-active" href="<?php echo esc_url(admin_url('admin.php?page=preciousuite-alerts')); ?>">
					<img src="<?php echo esc_url(PMRCGOLD_URL . 'includes/precioussuite/assets/' . '/uploads/alert-center-icon.png'); ?>"
						alt="<?php esc_attr_e('General', 'preciousuite-metal-rate-charts'); ?>" width="20" height="20"
						loading="lazy" style="margin-right: .75rem;" />
					<?php esc_html_e('Alert center', 'preciousuite-metal-rate-charts'); ?></a>
				<a href="<?php echo esc_url(admin_url('admin.php?page=preciousuite-configuration')); ?>">
					<img src="<?php echo esc_url(PMRCGOLD_URL . 'includes/precioussuite/assets/' . '/uploads/first-time-configuration-icon.png'); ?>"
						alt="<?php esc_attr_e('General', 'preciousuite-metal-rate-charts'); ?>" width="20" height="20"
						loading="lazy" style="margin-right: .75rem;" />
					<?php esc_html_e('First-time configuration', 'preciousuite-metal-rate-charts'); ?>
				</a>
			</nav>
		</aside>

		<main class="preciousuite-dashboard-main">
			<section class="preciousuite-dashboard-hero">
				<h1><?php esc_html_e('Alert center', 'preciousuite-metal-rate-charts'); ?></h1>
				<p><?php esc_html_e('Monitor setup issues and important Preciousuite recommendations for pricing, buyback quotes, invoices, and certificates.', 'preciousuite-metal-rate-charts'); ?>
				</p>
			</section>

			<section class="preciousuite-dashboard-card preciousuite-alert-card">
				<div class="preciousuite-alert-list">
					<div class="preciousuite-alert-group">
						<div class="preciousuite-alert-heading">
							<span class="dashicons dashicons-warning" aria-hidden="true"></span>
							<?php /* translators: %d: Number of problem found.
							  */ ?>
							<h2><?php echo esc_html(sprintf(__('Problems (%d)', 'preciousuite-metal-rate-charts'), $gpbw_alert_count)); ?>
							</h2>
						</div>
						<?php if (!empty($problems)): ?>
							<?php foreach ($problems as $problem): ?>
								<?php if ('missing_modules' === $problem['type']): ?>
									<div class="preciousuite-alert-row is-warning">
										<strong><?php esc_html_e('Some toolkit modules are not installed', 'preciousuite-metal-rate-charts'); ?></strong>
										<?php /* translators: 1: Number of installed tools, 2: Total number of tools.
										  */ ?>
										<p><?php echo esc_html(sprintf(__('%1$d of %2$d Preciousuite tools are active. Install the remaining tools to complete pricing, quotes, invoices, and certificates.', 'preciousuite-metal-rate-charts'), $gpbw_installed, $gpbw_total)); ?>
										</p>
									</div>
								<?php else: ?>
									<div class="preciousuite-alert-row is-warning">
										<strong><?php
										// translators: %s: Plugin name.
										echo esc_html(sprintf(__('In %s plugin, complete remaining setup tasks.', 'preciousuite-metal-rate-charts'), $problem['plugin_name']));
										?></strong>
										<p>
											<a href="<?php echo esc_url(admin_url('admin.php?page=preciousuite-tasks')); ?>">
												<?php esc_html_e('Go to task list to complete the setup.', 'preciousuite-metal-rate-charts'); ?>
											</a>
										</p>
									</div>
								<?php endif; ?>
							<?php endforeach; ?>
						<?php else: ?>
							<div class="preciousuite-alert-row is-good">
								<strong><?php esc_html_e('Good job! No serious setup problems detected.', 'preciousuite-metal-rate-charts'); ?></strong>
								<p><?php esc_html_e('Your Preciousuite ecosystem is ready for pricing, quotes, invoices, and certificates.', 'preciousuite-metal-rate-charts'); ?>
								</p>
							</div>
						<?php endif; ?>
					</div>

					<div class="preciousuite-alert-group preciousuite-notification-group">
						<div class="preciousuite-alert-heading">
							<span class="dashicons dashicons-bell" aria-hidden="true"></span>
							<?php /* translators: %d: Number of notifications.
							  */ ?>
							<h2><?php echo esc_html(sprintf(__('Notifications (%d)', 'preciousuite-metal-rate-charts'), count($gpbw_notifications))); ?>
							</h2>
						</div>
						<?php
						// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
						foreach ($gpbw_notifications as $gpbw_notification): ?>
							<div class="preciousuite-notification-row">
								<span aria-hidden="true"></span>
								<div>
									<strong><?php echo esc_html($gpbw_notification['title']); ?></strong>
									<p><?php echo esc_html($gpbw_notification['desc']); ?></p>
									<a
										href="<?php echo esc_url($gpbw_notification['url']); ?>"><?php echo esc_html($gpbw_notification['label']); ?></a>
								</div>
								<button type="button" class="button preciousuite-alert-dismiss"
									aria-label="<?php esc_attr_e('Dismiss notification', 'preciousuite-metal-rate-charts'); ?>">
									<span class="dashicons dashicons-hidden" aria-hidden="true"></span>
								</button>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			</section>
		</main>

		<aside class="preciousuite-dashboard-sidebar">
			<section class="preciousuite-sidebar-card preciousuite-side-card preciousuite-alert-help">
				<h2 style="display:flex; align-items:center; gap:8px;">
					<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#4f46e5" stroke-width="2"
						stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="10"></circle>
						<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
						<line x1="12" y1="17" x2="12.01" y2="17"></line>
					</svg>
					<?php esc_html_e('Alert help', 'preciousuite-metal-rate-charts'); ?>
				</h2>
				<p><?php esc_html_e('Use alerts as a setup checklist. They do not expose private store data and can be handled from your plugin settings pages.', 'preciousuite-metal-rate-charts'); ?>
				</p>
				<a
					href="<?php echo esc_url(admin_url('admin.php?page=preciousuite-support')); ?>"><?php esc_html_e('Open support guide →', 'preciousuite-metal-rate-charts'); ?></a>
			</section>
		</aside>
	</div>
</div>
<?php
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_query