<?php

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

class R123_WC_Admin {
	public static function init(): void {
		add_action('admin_post_r123_wc_manual_sync', [self::class, 'handle_manual_sync']);

		add_action('admin_menu', [self::class, 'add_menu']);
		add_action('admin_notices', [self::class, 'render_admin_notice']);
		add_action('admin_enqueue_scripts', [self::class, 'enqueue_admin_assets']);

		add_action('add_meta_boxes', [self::class, 'add_order_meta_box']);
		add_action('add_meta_boxes_woocommerce_page_wc-orders', [self::class, 'add_hpos_order_meta_box']);

		add_filter('manage_edit-shop_order_columns', [self::class, 'add_shop_order_column'], 20);
		add_action('manage_shop_order_posts_custom_column', [self::class, 'render_shop_order_column'], 20, 2);

		add_filter('manage_woocommerce_page_wc-orders_columns', [self::class, 'add_hpos_order_column'], 20);
		add_action('manage_woocommerce_page_wc-orders_custom_column', [self::class, 'render_hpos_order_column'], 20, 2);
	}

	public static function add_menu(): void {
		add_submenu_page(
			'woocommerce',
			'Račun123',
			'Račun123',
			'manage_woocommerce',
			'r123-wc-settings',
			[self::class, 'render_settings_page']
		);
	}

	public static function enqueue_admin_assets(string $hook): void {
		$allowed_hooks = [
			'woocommerce_page_r123-wc-settings',
			'post.php',
			'shop_order',
			'woocommerce_page_wc-orders',
		];

		if (!in_array($hook, $allowed_hooks, true)) {
			return;
		}

		wp_register_style('r123-wc-admin-inline', false, [], defined('R123_WC_VERSION') ? R123_WC_VERSION : '1.0.0');
		wp_enqueue_style('r123-wc-admin-inline');

		$css = '
			.r123-onboarding-wrap {
				margin: 24px 0 28px;
				padding: 28px;
				border-radius: 24px;
				background: linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(248,250,252,0.98) 100%);
				border: 1px solid #e7ebf0;
				box-shadow: 0 10px 30px rgba(15, 23, 42, 0.05), 0 2px 8px rgba(15, 23, 42, 0.04);
			}

			.r123-onboarding-hero {
				max-width: 860px;
				margin-bottom: 24px;
			}

			.r123-onboarding-badge {
				display: inline-flex;
				align-items: center;
				padding: 8px 12px;
				border-radius: 999px;
				background: rgba(22, 163, 74, 0.08);
				color: #15803d;
				font-size: 12px;
				font-weight: 600;
				letter-spacing: 0.02em;
				margin-bottom: 14px;
			}

			.r123-onboarding-hero h1 {
				margin: 0 0 10px;
				font-size: 32px;
				line-height: 1.1;
				font-weight: 700;
				color: #111827;
			}

			.r123-onboarding-hero p {
				margin: 0;
				font-size: 15px;
				line-height: 1.7;
				color: #4b5563;
				max-width: 760px;
			}

			.r123-onboarding-actions {
				display: flex;
				gap: 12px;
				margin-top: 18px;
				flex-wrap: wrap;
			}

			.r123-onboarding-grid {
				display: grid;
				grid-template-columns: repeat(3, minmax(0, 1fr));
				gap: 16px;
				margin-bottom: 24px;
			}

			.r123-step-card {
				position: relative;
				padding: 22px 20px 20px;
				border-radius: 20px;
				background: rgba(255,255,255,0.9);
				border: 1px solid #edf1f5;
				box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
			}

			.r123-step-number {
				width: 34px;
				height: 34px;
				border-radius: 50%;
				background: linear-gradient(135deg, #16a34a 0%, #22c55e 100%);
				color: #fff;
				font-weight: 700;
				font-size: 14px;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 14px;
			}

			.r123-step-card h3 {
				margin: 0 0 8px;
				font-size: 17px;
				line-height: 1.3;
				color: #111827;
			}

			.r123-step-card p {
				margin: 0;
				font-size: 14px;
				line-height: 1.7;
				color: #4b5563;
			}

			.r123-onboarding-preview {
				display: grid;
				grid-template-columns: repeat(3, minmax(0, 1fr));
				gap: 16px;
				margin-bottom: 18px;
			}

			.r123-preview-card {
				background: rgba(255,255,255,0.9);
				border: 1px solid #edf1f5;
				border-radius: 20px;
				overflow: hidden;
				box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
			}

			.r123-preview-card img {
				display: block;
				width: 100%;
				height: auto;
			}

			.r123-preview-caption {
				padding: 12px 14px 14px;
				font-size: 13px;
				color: #4b5563;
			}

			.r123-onboarding-note {
				padding: 14px 16px;
				border-radius: 16px;
				background: #f7faf8;
				border: 1px solid #e4efe7;
				color: #374151;
				font-size: 14px;
				line-height: 1.6;
			}

			.r123-status-card {
				margin: 18px 0 0;
				padding: 18px 20px;
				border-radius: 18px;
				border: 1px solid #e7ebf0;
				background: #fff;
				box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
				max-width: 900px;
			}

			.r123-status-pill {
				display: inline-flex;
				align-items: center;
				gap: 8px;
				padding: 8px 12px;
				border-radius: 999px;
				font-size: 13px;
				font-weight: 600;
			}

			.r123-status-pill--success {
				background: rgba(22, 163, 74, 0.08);
				color: #15803d;
			}

			.r123-status-pill--warning {
				background: rgba(245, 158, 11, 0.12);
				color: #b45309;
			}

			.r123-status-pill--error {
				background: rgba(220, 38, 38, 0.08);
				color: #b91c1c;
			}

			.r123-meta-actions {
				display: flex;
				flex-wrap: wrap;
				gap: 8px;
				margin-top: 8px;
			}

			@media (max-width: 1200px) {
				.r123-onboarding-grid,
				.r123-onboarding-preview {
					grid-template-columns: 1fr;
				}
			}
		';

		wp_add_inline_style('r123-wc-admin-inline', $css);
	}

	public static function render_settings_page(): void {
		$client        = new R123_WC_API_Client();
		$is_configured = $client->is_configured();
		$last_error    = method_exists($client, 'get_last_error') ? (string) $client->get_last_error() : '';

		$api_key = get_option('r123_wc_api_key', '');
		$api_url = get_option('r123_wc_api_url', '');

		if (empty($api_key)) {
			$api_key = get_option('r123_api_key', '');
		}

		if (empty($api_url)) {
			$api_url = get_option('r123_api_url', '');
		}

		$show_onboarding = empty($api_key) || empty($api_url);
		?>
		<div class="wrap">
			<h1>Račun123 for WooCommerce</h1>

			<?php if ($show_onboarding) : ?>
				<?php self::render_onboarding(); ?>
			<?php else : ?>
				<div class="r123-status-card">
					<p style="margin-top:0;">
						<span class="r123-status-pill <?php echo esc_attr(self::get_connection_status_class($is_configured, $last_error)); ?>">
							<?php echo esc_html(self::get_connection_status_label($is_configured, $last_error)); ?>
						</span>
					</p>
					<p style="margin-bottom:0;color:#4b5563;">
						Povezava je nastavljena. Preverite podatke v Račun123 integracijah, nato spodaj uredite ali posodobite nastavitve v pluginu.
					</p>
				</div>
			<?php endif; ?>

			<form id="r123-settings-form" method="post" action="options.php" style="margin-top:24px;">
				<?php
				settings_fields('r123_wc_settings_group');
				do_settings_sections('r123-wc-settings');
				submit_button('Shrani nastavitve');
				?>
			</form>
		</div>
		<?php
	}

	private static function render_onboarding(): void {
		$screenshot_1 = plugins_url('../assets/screenshots/screenshot-1.png', __FILE__);
		$screenshot_2 = plugins_url('../assets/screenshots/screenshot-2.png', __FILE__);
		$screenshot_3 = plugins_url('../assets/screenshots/screenshot-3.png', __FILE__);
		?>
		<div class="r123-onboarding-wrap">
			<div class="r123-onboarding-hero">
				<div class="r123-onboarding-badge">Račun123 × WooCommerce</div>
				<h1>Povežite trgovino z Račun123</h1>
				<p>
					Nastavitev traja le nekaj minut. Ko povezavo aktivirate, se lahko WooCommerce naročila
					samodejno pošiljajo v Račun123 za ustvarjanje računov.
				</p>

				<div class="r123-onboarding-actions">
					<a href="#r123-settings-form" class="button button-primary">Začni nastavitev</a>
					<a href="https://moj.racun123.si/dashboard/company/settings/integrations" target="_blank" rel="noopener noreferrer" class="button">Odpri Račun123 Integracije</a>
				</div>
			</div>

			<div class="r123-onboarding-grid">
				<div class="r123-step-card">
					<div class="r123-step-number">1</div>
					<h3>Odprite integracije v Račun123</h3>
					<p>
						V aplikaciji Račun123 odprite <strong>Integracije</strong> in kopirajte
						<strong>API ključ</strong> ter <strong>Webhook URL</strong>.
					</p>
				</div>

				<div class="r123-step-card">
					<div class="r123-step-number">2</div>
					<h3>Vnesite podatke v plugin</h3>
					<p>
						Spodaj vnesite oba podatka v ustrezni polji, nato kliknite
						<strong>Shrani nastavitve</strong>.
					</p>
				</div>

				<div class="r123-step-card">
					<div class="r123-step-number">3</div>
					<h3>Zaključite testno naročilo</h3>
					<p>
						Ustvarite testno naročilo in ga označite kot <strong>Completed / Zaključeno</strong>.
						Plugin bo naročilo poslal v Račun123.
					</p>
				</div>
			</div>

			<div class="r123-onboarding-preview">
				<div class="r123-preview-card">
					<img src="<?php echo esc_url($screenshot_1); ?>" alt="Račun123 integracije z API ključem in API URL">
					<div class="r123-preview-caption">1. Račun123 integracije z API ključem in API URL</div>
				</div>

				<div class="r123-preview-card">
					<img src="<?php echo esc_url($screenshot_2); ?>" alt="Račun123 for WooCommerce dashboard z navodili">
					<div class="r123-preview-caption">2. Račun123 for WooCommerce dashboard z navodili</div>
				</div>

				<div class="r123-preview-card">
					<img src="<?php echo esc_url($screenshot_3); ?>" alt="Ustvarjen račun v aplikaciji Račun123">
					<div class="r123-preview-caption">3. Ustvarjen račun v aplikaciji Račun123</div>
				</div>
			</div>

			<div class="r123-onboarding-note">
				<strong>Namig:</strong> če želite, da se računi ustvarjajo samodejno, naj bo WooCommerce
				naročilo po plačilu označeno kot <strong>Completed</strong>.
			</div>
		</div>
		<?php
	}

	public static function render_admin_notice(): void {
		if (empty($_GET['r123_notice'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only notice display.
			return;
		}

		$notice = sanitize_text_field(
			wp_unslash($_GET['r123_notice']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only notice display.
		);

		if ($notice === 'manual_sync_success') {
			echo '<div class="notice notice-success is-dismissible"><p>Račun123: naročilo je bilo uspešno poslano v Račun123.</p></div>';
		}

		if ($notice === 'manual_sync_warning') {
			echo '<div class="notice notice-warning is-dismissible"><p>Račun123: račun je bil ustvarjen, vendar je API vrnil opozorilo. Preverite podrobnosti pri naročilu.</p></div>';
		}

		if ($notice === 'manual_sync_error') {
			echo '<div class="notice notice-error is-dismissible"><p>Račun123: pošiljanje ni uspelo. Preverite podrobnosti pri naročilu.</p></div>';
		}

		if ($notice === 'manual_sync_already_sent') {
			echo '<div class="notice notice-info is-dismissible"><p>Račun123: to naročilo je že uspešno poslano v Račun123.</p></div>';
		}

		if ($notice === 'manual_sync_not_completed') {
			echo '<div class="notice notice-warning is-dismissible"><p>Račun123: račun lahko ustvarite šele, ko je naročilo označeno kot Zaključeno (Completed).</p></div>';
		}

		if ($notice === 'manual_sync_too_soon') {
			echo '<div class="notice notice-warning is-dismissible"><p>Račun123: počakajte nekaj sekund, preden znova pošljete naročilo.</p></div>';
		}
	}

	public static function add_order_meta_box(): void {
		add_meta_box(
			'r123_wc_order_box',
			'Račun123',
			[self::class, 'render_order_meta_box_classic'],
			'shop_order',
			'side',
			'high'
		);
	}

	public static function add_hpos_order_meta_box(): void {
		add_meta_box(
			'r123_wc_order_box',
			'Račun123',
			[self::class, 'render_order_meta_box_hpos'],
			'woocommerce_page_wc-orders',
			'side',
			'high'
		);
	}

	public static function render_order_meta_box_classic($post): void {
		$order_id = isset($post->ID) ? (int) $post->ID : 0;
		self::render_order_box_by_order_id($order_id);
	}

	public static function render_order_meta_box_hpos($object): void {
		$order_id = 0;

		if (is_object($object)) {
			if (method_exists($object, 'get_id')) {
				$order_id = (int) $object->get_id();
			} elseif (isset($object->id)) {
				$order_id = (int) $object->id;
			}
		}

		if (
			!$order_id &&
			isset($_GET['id']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen context.
		) {
			$order_id = absint($_GET['id']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen context.
		}

		self::render_order_box_by_order_id($order_id);
	}

	private static function render_order_box_by_order_id(int $order_id): void {
		if (!$order_id) {
			echo '<p>Order ID ni na voljo.</p>';
			return;
		}

		$invoice_id     = (string) get_post_meta($order_id, '_r123_invoice_id', true);
		$invoice_number = (string) get_post_meta($order_id, '_r123_invoice_number', true);
		$pdf_url        = (string) get_post_meta($order_id, '_r123_pdf_url', true);
		$sync_status    = (string) get_post_meta($order_id, '_r123_invoice_status', true);
		$last_error     = (string) get_post_meta($order_id, '_r123_last_error', true);
		$last_synced_at = (string) get_post_meta($order_id, '_r123_last_synced_at', true);

		echo '<p><strong>Status:</strong> ' . esc_html(self::human_sync_status($sync_status, $last_error, $last_synced_at)) . '</p>';
		echo '<p><strong>ID v Račun123:</strong> ' . esc_html($invoice_id !== '' ? $invoice_id : '—') . '</p>';
		echo '<p><strong>Št. računa:</strong> ' . esc_html($invoice_number !== '' ? $invoice_number : '—') . '</p>';
		echo '<p><strong>Zadnja sinhronizacija:</strong> ' . esc_html($last_synced_at !== '' ? $last_synced_at : '—') . '</p>';

		if ($last_error !== '') {
			$color = $sync_status === 'warning' ? '#b45309' : '#b32d2e';
			echo '<p style="color:' . esc_attr($color) . ';"><strong>' . esc_html($sync_status === 'warning' ? 'Opozorilo:' : 'Napaka:') . '</strong><br>' . esc_html($last_error) . '</p>';
		}

		if ($pdf_url !== '') {
			echo '<div class="r123-meta-actions">';
			echo '<a href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener noreferrer" class="button">Prenesi PDF</a>';
			echo '</div>';
		}

		$client        = new R123_WC_API_Client();
		$is_configured = $client->is_configured();

		$order  = wc_get_order($order_id);
		$status = $order ? (string) $order->get_status() : '';

		$manual_sync_url = wp_nonce_url(
			admin_url('admin-post.php?action=r123_wc_manual_sync&order_id=' . $order_id),
			'r123_wc_manual_sync_' . $order_id
		);

		if (!$is_configured) {
			echo '<p><button type="button" class="button button-primary" disabled>Pošlji v Račun123</button></p>';
			echo '<p><em>Najprej nastavite API URL in API ključ.</em></p>';
			return;
		}

		if ($status !== 'completed') {
			echo '<p><em>Račun se ustvari, ko je naročilo označeno kot Zaključeno (Completed).</em></p>';
			return;
		}

		echo '<div class="r123-meta-actions">';
		echo '<a class="button button-primary" href="' . esc_url($manual_sync_url) . '">Pošlji v Račun123</a>';
		echo '</div>';
	}

	public static function handle_manual_sync(): void {
		if (!current_user_can('manage_woocommerce')) {
			wp_die('Access denied');
		}

		$order_id = isset($_GET['order_id']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked below.
			? absint($_GET['order_id']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked below.
			: 0;

		if (!$order_id) {
			wp_die('Invalid order');
		}

		check_admin_referer('r123_wc_manual_sync_' . $order_id);

		$order = wc_get_order($order_id);

		if (!$order) {
			wp_die('Woo order not found');
		}

		$last_synced_at = (string) get_post_meta($order_id, '_r123_last_synced_at', true);

		if ($last_synced_at !== '') {
			$last_timestamp = strtotime($last_synced_at);

			if ($last_timestamp && (time() - $last_timestamp) < 10) {
				$base_redirect = wp_get_referer() ?: admin_url('admin.php?page=wc-orders&action=edit&id=' . $order_id);
				$redirect      = add_query_arg(
					['r123_notice' => 'manual_sync_too_soon'],
					$base_redirect
				);

				wp_safe_redirect($redirect);
				exit;
			}
		}

		if ($order->get_status() !== 'completed') {
			$base_redirect = wp_get_referer() ?: admin_url('admin.php?page=wc-orders&action=edit&id=' . $order_id);
			$redirect      = add_query_arg(
				['r123_notice' => 'manual_sync_not_completed'],
				$base_redirect
			);

			wp_safe_redirect($redirect);
			exit;
		}

		$invoice_id  = (string) get_post_meta($order_id, '_r123_invoice_id', true);
		$sync_status = (string) get_post_meta($order_id, '_r123_invoice_status', true);

		if ($sync_status === 'received' && $invoice_id !== '') {
			$base_redirect = wp_get_referer() ?: admin_url('admin.php?page=wc-orders&action=edit&id=' . $order_id);
			$redirect      = add_query_arg(
				['r123_notice' => 'manual_sync_already_sent'],
				$base_redirect
			);

			wp_safe_redirect($redirect);
			exit;
		}

		$success = R123_WC_Order_Sync::sync_order($order_id, 'manual', true);

		$new_status = (string) get_post_meta($order_id, '_r123_invoice_status', true);
		$notice     = $success ? 'manual_sync_success' : 'manual_sync_error';

		if ($success && $new_status === 'warning') {
			$notice = 'manual_sync_warning';
		}

		$base_redirect = wp_get_referer() ?: admin_url('admin.php?page=wc-orders&action=edit&id=' . $order_id);
		$redirect      = add_query_arg(
			['r123_notice' => $notice],
			$base_redirect
		);

		wp_safe_redirect($redirect);
		exit;
	}

	public static function add_shop_order_column(array $columns): array {
		$new_columns = [];

		foreach ($columns as $key => $label) {
			$new_columns[$key] = $label;

			if ($key === 'order_status') {
				$new_columns['r123_status'] = 'Račun123';
			}
		}

		if (!isset($new_columns['r123_status'])) {
			$new_columns['r123_status'] = 'Račun123';
		}

		return $new_columns;
	}

	public static function render_shop_order_column(string $column, int $post_id): void {
		if ($column !== 'r123_status') {
			return;
		}

		self::render_order_status_badge($post_id);
	}

	public static function add_hpos_order_column(array $columns): array {
		$new_columns = [];

		foreach ($columns as $key => $label) {
			$new_columns[$key] = $label;

			if ($key === 'status') {
				$new_columns['r123_status'] = 'Račun123';
			}
		}

		if (!isset($new_columns['r123_status'])) {
			$new_columns['r123_status'] = 'Račun123';
		}

		return $new_columns;
	}

	public static function render_hpos_order_column(string $column, $order): void {
		if ($column !== 'r123_status') {
			return;
		}

		$order_id = 0;

		if (is_object($order) && method_exists($order, 'get_id')) {
			$order_id = (int) $order->get_id();
		}

		self::render_order_status_badge($order_id);
	}

	private static function render_order_status_badge(int $order_id): void {
		if (!$order_id) {
			echo '—';
			return;
		}

		$sync_status = (string) get_post_meta($order_id, '_r123_invoice_status', true);
		$last_error  = (string) get_post_meta($order_id, '_r123_last_error', true);
		$invoice_id  = (string) get_post_meta($order_id, '_r123_invoice_id', true);

		if ($sync_status === 'warning') {
			echo '<span style="color:#b45309;font-weight:600;">Opozorilo</span>';
			return;
		}

		if ($last_error !== '') {
			echo '<span style="color:#b32d2e;font-weight:600;">Napaka</span>';
			return;
		}

		if ($sync_status === 'received' && $invoice_id !== '') {
			echo '<span style="color:#0a7a2f;font-weight:600;">Poslano</span>';
			return;
		}

		echo '<span style="color:#666;">Čaka</span>';
	}

	private static function human_sync_status(string $sync_status = '', string $last_error = '', string $last_synced_at = ''): string {
		if ($sync_status === 'warning') {
			return 'Ustvarjeno z opozorilom';
		}

		if ($last_error !== '') {
			return 'Napaka – potrebna ponovna pošiljka';
		}

		if ($sync_status === 'received') {
			return 'Uspešno poslano v Račun123';
		}

		if ($last_synced_at !== '') {
			return 'V obdelavi...';
		}

		return 'Čaka na sinhronizacijo';
	}

	private static function get_connection_status_class(bool $is_configured, string $last_error): string {
		if ($last_error !== '') {
			return 'r123-status-pill--error';
		}

		if ($is_configured) {
			return 'r123-status-pill--success';
		}

		return 'r123-status-pill--warning';
	}

	private static function get_connection_status_label(bool $is_configured, string $last_error): string {
		if ($last_error !== '') {
			return 'Povezava ima napako';
		}

		if ($is_configured) {
			return 'Povezava pripravljena';
		}

		return 'Povezava še ni nastavljena';
	}
}