<?php

namespace BerryPress\LiveCarts;

use BerryPressLiveCarts\Admin\Page as BerryPressPage;

defined( 'ABSPATH' ) || exit;

class AdminPage extends BerryPressPage {

	protected $table, $cartData;

	function __construct($table=null) {
		// Prepare data used in body()
		
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent
		if ( isset( $_GET['cart_id'] ) ) {
			global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.Security.NonceVerification.Recommended -- non-persistent
			$this->cartData = $wpdb->get_row( $wpdb->prepare( 'SELECT c.*, cc.contents_id, cc.ts FROM ' . $wpdb->prefix . 'phplugins_carts c LEFT JOIN ' . $wpdb->prefix . 'phplugins_cart_contents cc ON c.cart_id = cc.cart_id WHERE c.cart_id=%d AND archived=0 ORDER BY cc.contents_id DESC LIMIT 1', (int) $_GET['cart_id'] ) );
		} else if ($table) {
			$this->table = $table;
			$this->table->prepare_items();
		}

		add_action( get_plugin_page_hookname( 'live-carts-for-woocommerce', 'berrypress' ), function () {
			$this->render();
		} );
	}

	public static function getUrl( array $args = [] ) {
		return add_query_arg( $args, admin_url( 'admin.php?page=live-carts-for-woocommerce' ) );
	}

	private function renderAddonsPage() {
		include_once(plugin_dir_path(__FILE__) . '../includes/berrypress-admin-framework/addons-page.php');
	}

	public function body() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
		if ( isset( $_GET['cart_id'] ) ) {
			$this->cartPage();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
		} elseif ( isset( $_GET['settings'] ) ) {
			$this->settingsPage();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
		} elseif ( isset( $_GET['healthstatus'] ) ) {
			$this->statusPage();
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
        elseif ( isset( $_GET['addons'] ) && $this->showExternalLinks ) {
	        $this->renderAddonsPage();
		} else {
			$this->listPage();
		}

	}

	public function listPage() {
		?>
        <div class="wrap">
            <h2></h2>
            <div class="berrypress-page-content-header">
                <h1><?php esc_html_e( 'Live Carts', 'live-carts-for-woocommerce' ); ?></h1>
                <button id="berrypress-show-settings-link" class="berrypress-btn berrypress-btn-secondary">Table
                    Settings
                </button>
            </div>
            <form method="get">
                <input type="hidden" name="page" value="live-carts-for-woocommerce">
				<?php $this->table->views();
				do_action('phplugins_live_carts_list_after_view_links');
				$this->table->search_box( esc_html__( 'Search Cart ID', 'live-carts-for-woocommerce' ), 'phplugins-live-carts-search' );
				$this->table->display(); ?>
            </form>
            <p class="instructions"><?php esc_html_e( 'Carts are removed from this page approximately 30 days after they were last seen. Some cart data is retained in the database after this time.', 'live-carts-for-woocommerce' ); ?></p>
        </div>
		<?php
	}

	public function settingsPage() {
		?>
        <div id="phplugins-live-carts-settings" class="wrap">
            <h1><?php esc_html_e( 'Live Carts Settings', 'live-carts-for-woocommerce' ); ?></h1>
            <form action="" method="post">
				<?php wp_nonce_field( 'phplugins-carts-settings-save', 'phplugins_carts_settings_save' ); ?>

                <h2><?php esc_html_e( 'General', 'live-carts-for-woocommerce' ); ?></h2>
                <div class="berrypress-field">
                    <input type="checkbox" name="phplugins_carts_show_id" id="phplugins_carts_show_id"
                           value="1"<?php checked( get_option( 'phplugins_carts_show_id' ) ); ?>>
                    <div>
                        <label for="phplugins_carts_show_id">
							<?php esc_html_e( 'Show cart ID on the frontend', 'live-carts-for-woocommerce' ); ?>
                        </label>
                        <p class="description"><?php esc_html_e( 'Note: It may be necessary to refresh the page after adding the first item to cart to see the cart ID. The setting automatically appends the cart ID to the WooCommerce cart page and mini-cart.', 'live-carts-for-woocommerce' ); ?></p>
                    </div>
                </div>

                <div class="berrypress-field">
                    <div class="phplugins-cart-shortcode">
                        <label><?php esc_html_e( 'Cart ID Shortcode', 'live-carts-for-woocommerce' ); ?></label>
                        <p class="description">
                            <?php
                            printf(
                                /* translators: %s: documentation link */
                                esc_html__( 'Use this shortcode to display the current cart ID anywhere on your site (e.g. on a Contact Us or Support page). %s', 'live-carts-for-woocommerce' ),
                                '<a class="berrypress-link" href="https://berrypress.com/docs/live-carts-for-woocommerce/usage-guide/#displaying-cart-id-to-customers" target="_blank">' . esc_html__( 'Documentation', 'live-carts-for-woocommerce' ) . '</a>'
                            );
                            ?>
                        </p>
                        <div class="berrypress-flex-base berrypress-flex-wrap">
                            <code id="phplugins-cart-id-shortcode">[berrypress_live_cart_id]</code>
                            <button type="button" class="berrypress-btn berrypress-btn-secondary" id="phplugins-copy-shortcode"
                                    data-shortcode="[berrypress_live_cart_id]"
                                    data-label-copy="<?php esc_attr_e( 'Copy', 'live-carts-for-woocommerce' ); ?>"
                                    data-label-copied="<?php esc_attr_e( 'Copied!', 'live-carts-for-woocommerce' ); ?>">
                                <?php esc_html_e( 'Copy', 'live-carts-for-woocommerce' ); ?>
                            </button>
                        </div>
                    </div>
                </div>

		        <?php do_action( 'phplugins_live_carts_settings_general' ); ?>

                <h2><?php esc_html_e( 'Privacy', 'live-carts-for-woocommerce' ); ?></h2>

                <div class="berrypress-field">
                    <input type="checkbox" name="phplugins_carts_no_ip" id="phplugins_carts_no_ip"
                           value="1"<?php checked( get_option( 'phplugins_carts_no_ip' ) ); ?>>
                    <label for="phplugins_carts_no_ip">
						<?php esc_html_e( 'Don\'t collect site visitors\' IP addresses', 'live-carts-for-woocommerce' ); ?>
                    </label>
                </div>

                <div class="berrypress-field berrypress-mb-4">
                    <input type="checkbox" name="phplugins_carts_no_url" id="phplugins_carts_no_url"
                           value="1"<?php checked( get_option( 'phplugins_carts_no_url' ) ); ?>>
                    <label for="phplugins_carts_no_url">
						<?php esc_html_e( 'Don\'t collect visited URLs', 'live-carts-for-woocommerce' ); ?>
                    </label>
                </div>

                <button class="berrypress-btn berrypress-btn-primary"><?php esc_html_e( 'Save Settings', 'live-carts-for-woocommerce' ); ?></button>
            </form>
        </div>
		<?php
	}

	public function statusPage() {
		global $wpdb;
		$checks = [];

		$checks[] = [
			'label' => __( 'Plugin version', 'live-carts-for-woocommerce' ),
			'value' => LiveCarts::VERSION,
			'status' => 'ok',
		];
		
		$wpVer = get_bloginfo( 'version' );
		$checks[] = [
			'label' => __( 'WordPress version', 'live-carts-for-woocommerce' ),
			'value' => $wpVer,
			'status' => version_compare( $wpVer, '6.2', '>=' ) ? 'ok' : 'warning',
		];

		$checks[] = [
			'label' => __( 'PHP version', 'live-carts-for-woocommerce' ),
			'value' => PHP_VERSION,
			'status' => version_compare( PHP_VERSION, '8.0', '>=' ) ? 'ok' : 'warning',
		];

		$checks[] = [
			'label' => __( 'WooCommerce version', 'live-carts-for-woocommerce' ),
			'value' => defined( 'WC_VERSION' ) ? WC_VERSION : __( 'Not active', 'live-carts-for-woocommerce' ),
			'status' => defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '7.0', '>=' ) ? 'ok' : 'error',
		];

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$allTables = $wpdb->get_col( 'SHOW TABLES' );
		$requiredTables = [ 'phplugins_carts', 'phplugins_cart_contents', 'phplugins_cart_contents_items' ];
		foreach ( $requiredTables as $table ) {
			$fullName = $wpdb->prefix . $table;
			$exists = in_array( $fullName, $allTables );
			$checks[] = [
				'label' => sprintf( /* translators: %s: database table name */ __( 'Table: %s', 'live-carts-for-woocommerce' ), $table ),
				'value' => $exists ? __( 'Exists', 'live-carts-for-woocommerce' ) : __( 'Missing', 'live-carts-for-woocommerce' ),
				'status' => $exists ? 'ok' : 'error',
			];
		}

		$migrationNeeded = LiveCarts::isMigrationNeeded();
		$checks[] = [
			'label' => __( 'Database migration (1.2.0)', 'live-carts-for-woocommerce' ),
			'value' => $migrationNeeded ? __( 'Incomplete', 'live-carts-for-woocommerce' ) : __( 'Complete', 'live-carts-for-woocommerce' ),
			'status' => $migrationNeeded ? 'error' : 'ok',
		];

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$totalCarts = $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'phplugins_carts' );
		$checks[] = [
			'label' => __( 'Total carts in database', 'live-carts-for-woocommerce' ),
			'value' => number_format_i18n( (int) $totalCarts ),
			'status' => 'ok',
		];

		$cronScheduled = wp_next_scheduled( 'phplugins_livecarts_hourly' );
		$checks[] = [
			'label' => __( 'Scheduled tasks (WP Cron)', 'live-carts-for-woocommerce' ),
			'value' => $cronScheduled
				? sprintf( /* translators: %s: next run time */ __( 'Scheduled (next: %s)', 'live-carts-for-woocommerce' ), wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $cronScheduled ) )
				: __( 'Not scheduled', 'live-carts-for-woocommerce' ),
			'status' => $cronScheduled >= time() ? 'ok' : 'warning',
		];

		$pluginDirWritable = wp_is_writable( plugin_dir_path( __DIR__ ) );
		$checks[] = [
			'label' => __( 'Plugin directory writable', 'live-carts-for-woocommerce' ),
			'value' => $pluginDirWritable ? __( 'Yes', 'live-carts-for-woocommerce' ) : __( 'No', 'live-carts-for-woocommerce' ),
			'status' => $pluginDirWritable ? 'ok' : 'warning',
		];

		$checks = apply_filters( 'phplugins_live_carts_status_checks', $checks );
		?>
		<div id="phplugins-live-carts-health-status" class="wrap">
			<h1><?php esc_html_e( 'Status', 'live-carts-for-woocommerce' ); ?></h1>
            <div class="berrypress-mb-4">
                <h2 class="berrypress-fw-medium"><?php esc_html_e( 'Health Check', 'live-carts-for-woocommerce' ); ?></h2>
                <table class="berrypress-table phplugins-live-carts-table-status">
                    <tbody>
                    <?php
                    foreach ( $checks as $check ) {
                        ?>
                        <tr>
                            <th scope="row"><label><?php echo esc_html( $check['label'] ); ?></label></th>
                            <?php
                            $badgeColors = [ 'ok' => 'green', 'warning' => 'yellow', 'error' => 'red' ];
                            $badgeClass = 'phplugins-live-carts-status-' . ( $badgeColors[ $check['status'] ?? '' ] ?? 'green' );
                            ?>
                            <td class="phplugins-live-carts-status <?php echo esc_attr( $badgeClass ); ?>"><?php echo esc_html( $check['value'] ); ?></td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>

                <?php
                $migrationSuccess = get_transient( 'phplugins_carts_migration_success' );
                if ( $migrationSuccess ) {
                    delete_transient( 'phplugins_carts_migration_success' );
                ?>
                <div class="berrypress-notice berrypress-notice-success">
                    <span class="berrypress-notice-icon"><i class="berrypress-icon-check"></i></span>
                    <div>
                        <p><?php esc_html_e( 'Database migration completed successfully.', 'live-carts-for-woocommerce' ); ?></p>
                    </div>
                </div>
                <?php } ?>

                <?php
                $migrationErrors = get_transient( 'phplugins_carts_migration_errors' );
                if ( $migrationErrors ) {
                    delete_transient( 'phplugins_carts_migration_errors' );
                ?>
                <div class="berrypress-notice berrypress-notice-error">
                    <span class="berrypress-notice-icon"><i class="berrypress-icon-warning"></i></span>
                    <div>
                        <strong><?php esc_html_e( 'Migration failed with the following errors:', 'live-carts-for-woocommerce' ); ?></strong>
                        <ul>
                            <?php foreach ( $migrationErrors as $error ) { ?>
                                <li><code><?php echo esc_html( $error ); ?></code></li>
                            <?php } ?>
                        </ul>
                    </div>
                </div>
                <?php } ?>

                <?php
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display, capability verified in onCurrentScreen
				$forceMigrationNotice = isset( $_GET['migrate'] ) && sanitize_text_field( wp_unslash( $_GET['migrate'] ) ) === '1_2_0';
				?>
                <?php if ( $migrationNeeded || $forceMigrationNotice ) { ?>
                <div class="berrypress-notice berrypress-notice-error">
                    <span class="berrypress-notice-icon"><i class="berrypress-icon-error_outline "></i></span>
                    <div>
                        <p>
                            <?php esc_html_e( 'The database migration has not completed. This may cause cart details to not display correctly.', 'live-carts-for-woocommerce' ); ?>
                            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-ajax.php?action=phplugins_carts_rerun_migration' ), 'phplugins_carts_rerun_migration' ) ); ?>" ><?php esc_html_e( 'Re-run migration', 'live-carts-for-woocommerce' ); ?></a>
                        </p>

                    </div>
                </div>
                <?php } ?>
            </div>
            <span class="berrypress-seperator"></span>
            <div>
			<h2 class="berrypress-fw-medium berrypress-mt-4 berrypress-mb-4"><?php esc_html_e( 'Debug Log', 'live-carts-for-woocommerce' ); ?></h2>
			<form action="" method="post">
                <div class="berrypress-mb-3">
				<?php wp_nonce_field( 'phplugins-carts-settings-save', 'phplugins_carts_settings_save' ); ?>

				<div class="berrypress-field">
					<input type="checkbox" name="phplugins_carts_debug" id="phplugins_carts_debug"
						   value="1"<?php checked( get_option( 'phplugins_carts_debug' ) !== false ); ?>>
					<label for="phplugins_carts_debug">
						<?php esc_html_e( 'Enable debug mode', 'live-carts-for-woocommerce' ); ?>
					</label>
				</div>

                <div class="berrypress-field berrypress-mb-2">
                    <input type="checkbox" name="phplugins_carts_debug_clear" id="phplugins_carts_debug_clear" value="1">
                    <label for="phplugins_carts_debug_clear"><?php esc_html_e( 'Clear log on save', 'live-carts-for-woocommerce' ); ?></label>
                </div>


                <div class="berrypress-field berrypress-mb-2 berrypress-align-items-center" id="phplugins-carts-debug-level-field" style="<?php echo get_option( 'phplugins_carts_debug' ) === false ? 'display:none' : ''; ?>">
					<label for="phplugins_carts_debug_level"><?php esc_html_e( 'Log level', 'live-carts-for-woocommerce' ); ?></label>
					<select name="phplugins_carts_debug_level" id="phplugins_carts_debug_level">
						<option value="errors"<?php selected( get_option( 'phplugins_carts_debug_level', 'errors' ), 'errors' ); ?>><?php esc_html_e( 'Errors only', 'live-carts-for-woocommerce' ); ?></option>
						<option value="all"<?php selected( get_option( 'phplugins_carts_debug_level', 'errors' ), 'all' ); ?>><?php esc_html_e( 'All (verbose)', 'live-carts-for-woocommerce' ); ?></option>
					</select>
				</div>

				<?php
				$debugLogContents = LiveCarts::instance()->getDebugLogContents();
				if ( $debugLogContents ) {
					$debugLogPath = LiveCarts::instance()->getDebugLogPath();
					$debugLogSize = $debugLogPath && file_exists( $debugLogPath ) ? size_format( filesize( $debugLogPath ) ) : '';
				?>
				<div class="berrypress-field berrypress-mb-4">
					<label><?php esc_html_e( 'Log output', 'live-carts-for-woocommerce' ); ?></label>
					<div>
                        <textarea class="phplugins-lc-debug-log" readonly rows="14" ><?php echo esc_textarea( $debugLogContents ); ?></textarea>
                        <p>
                            <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-ajax.php?action=phplugins_carts_download_debug_log' ), 'phplugins_carts_download_debug_log' ) ); ?>" class="berrypress-link"><?php
                                esc_html_e( 'Download full log', 'live-carts-for-woocommerce' );
                                if ( $debugLogSize ) {
                                    echo ' (' . esc_html( $debugLogSize ) . ')';
                                }
                                ?></a>
                        </p>
                    </div>
				</div>
				<?php } ?>

                </div>

				<button class="berrypress-btn berrypress-btn-primary"><?php esc_html_e( 'Save', 'live-carts-for-woocommerce' ); ?></button>
			</form>
            </div>

			<script>document.getElementById('phplugins_carts_debug').addEventListener('change',function(){document.getElementById('phplugins-carts-debug-level-field').style.display=this.checked?'':'none';})</script>
        </div>
		<?php
	}

	public function cartPage() {
		global $wpdb;
		$tsFormat = LiveCarts::instance()->getTimestampFormat();
		$statuses = LiveCarts::instance()->getCartStatuses();

		if ( ! empty( $this->cartData ) ) {
			if ( ! empty( $this->cartData->user_id ) ) {
				$user = get_userdata( $this->cartData->user_id );
				if ( $user ) {
					$userDisplayName = trim( $user->first_name . ' ' . $user->last_name );
					if ( empty( $userDisplayName ) ) {
						$userDisplayName = $user->user_login;
					}
				}
			}
			// Check if migration has been completed
			if ( ! empty( $this->cartData->contents_id ) && get_option('phplugins_carts_migration_1_2_0_complete') ) {
				// Load cart items from the new table structure
				$contents = LiveCarts::getCartContentsArray($this->cartData->contents_id);
				$history = LiveCarts::getCartContentsHistory($this->cartData->cart_id);
			}
			if ( ! empty( $this->cartData->order_id ) ) {
				$order = wc_get_order( $this->cartData->order_id );
			}
		}
		?>
        <div id="phplugins-live-carts-details" class="wrap">
        <h2></h2>
        <div class="berrypress-page-content-header berrypress-lc-page-content-header">
        <a href="<?php echo( esc_url( remove_query_arg( 'cart_id' ) ) ); ?>" class="berrypress-btn-go-back"
           title="Go Back">
            <i class="berrypress-icon-keyboard_arrow_left"></i>
            <span class="berrypress-visually-hidden"><?php esc_html_e( 'Back to carts list', 'live-carts-for-woocommerce' ); ?></span>
        </a>
		<?php if ( empty( $this->cartData ) ) { ?>
            <h1><?php esc_html_e( 'Cart Not Found', 'live-carts-for-woocommerce' ); ?></h1>
            </div>
		<?php } else { ?>
            <h1>
				<?php
				// translators: %s is the cart ID
				echo( esc_html( sprintf( __( 'Cart #%s', 'live-carts-for-woocommerce' ), LiveCarts::formatCartId( $this->cartData->cart_id ) ) ) );
				?>
			</h1>
            </div>
            <div id="phplugins-live-carts-details-card">
                <table class="form-table phplugins-lc-table-2col">
                    <tbody>
                    <tr>
                        <th scope="row">
                            <label><?php esc_html_e( 'Created at', 'live-carts-for-woocommerce' ); ?></label>
                        </th>
                        <td>
							<?php echo( esc_html( get_date_from_gmt( $this->cartData->created, $tsFormat ) ) ); ?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label><?php esc_html_e( 'Last seen', 'live-carts-for-woocommerce' ); ?></label>
                        </th>
                        <td>
							<?php
							echo(
							$this->cartData->last_url
								? sprintf(
							// translators: first %s is a timestamp, second %s is a URL
								esc_html__( '%1$s at %2$s', 'live-carts-for-woocommerce' ),
								esc_html( get_date_from_gmt( $this->cartData->last_seen, $tsFormat ) ),
								'<a href="' . esc_url( $this->cartData->last_url ) . '" target="_blank">' . esc_url( $this->cartData->last_url ) . '</a>'
							)
								: esc_html( get_date_from_gmt( $this->cartData->last_seen, $tsFormat ) )
							);
							?>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label><?php esc_html_e( 'Status', 'live-carts-for-woocommerce' ); ?></label>
                        </th>
                        <td class="phplugins-live-carts-status phplugins-live-carts-<?php echo( esc_attr( $this->cartData->status ) ); ?>">
							<?php echo( esc_html( isset( $statuses[ $this->cartData->status ] ) ? $statuses[ $this->cartData->status ] : $this->cartData->status ) ); ?>
                        </td>
                    </tr>
					<?php if ( ! empty( $order ) ) { ?>
                        <tr>
                            <th scope="row">
                                <label><?php esc_html_e( 'Order', 'live-carts-for-woocommerce' ); ?></label>
                            </th>
                            <td>
                                <a href="<?php echo( esc_url( $order->get_edit_order_url() ) ); ?>"
                                   target="_blank"><?php echo( (int) $order->get_id() ); ?></a>
                            </td>
                        </tr>
					<?php } ?>
                    <tr>
                        <th scope="row">
                            <label><?php esc_html_e( 'User', 'live-carts-for-woocommerce' ); ?></label>
                        </th>
                        <td>
							<?php echo( empty( $user ) ? esc_html_e( 'Guest/Unknown', 'live-carts-for-woocommerce' ) : '<a href="' . esc_url( get_edit_user_link( $user->ID ) ) . '" target="_blank">' . esc_html( $userDisplayName ) . '</a>' ); ?>
                        </td>
                    </tr>
					<?php if ( ! get_option( 'phplugins_carts_no_ip' ) && ! empty( $this->cartData->ip_address ) ) { ?>
                        <tr>
                            <th scope="row">
                                <label><?php esc_html_e( 'IP address', 'live-carts-for-woocommerce' ); ?></label>
                            </th>
                            <td>
								<?php echo( esc_html( $this->cartData->ip_address ) ); ?>
                            </td>
                        </tr>
					<?php } ?>
					<?php if ( $this->cartData->coupon ) { ?>
                        <tr>
                            <th scope="row">
                                <label><?php esc_html_e( 'Cart coupon(s)', 'live-carts-for-woocommerce' ); ?></label>
                            </th>
                            <td>
								<?php echo( esc_html( $this->cartData->coupon ) ); ?>
                            </td>
                        </tr>
					<?php } ?>

                    </tbody>
                </table>

				<?php if ( isset( $contents ) ) { ?>

                <span class="berrypress-seperator"></span>
                <h2>Cart items</h2>
			<?php
				$contentsOverride = apply_filters('phplugins_live_carts_admin_cart_contents', null, $this->cartData, $contents);
				if ($contentsOverride === null) {
			?>

                    <div class="phplugins-lc-table-cart">
                        <table class="form-table berrypress-table">
                            <thead>
                            <tr>
                                <th><?php esc_html_e( 'Item Name', 'live-carts-for-woocommerce' ); ?></th>
                                <th><?php esc_html_e( 'Quantity', 'live-carts-for-woocommerce' ); ?></th>
                                <th><?php esc_html_e( 'Line Total', 'live-carts-for-woocommerce' ); ?></th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
							$cartSubtotal = 0;
							$cartDiscount = 0;
                            foreach ( $contents as $item ) {
                                if ( empty( $item['product_id'] ) ) {
                                    unset( $product );
                                } else {
                                    $product = wc_get_product( empty( $item['variation_id'] ) ? $item['product_id'] : $item['variation_id'] );
                                }
								
								$cartSubtotal += ($item['line_subtotal'] ?? 0);
								$cartDiscount += (isset($item['line_total']) && isset($item['line_subtotal'])) ? $item['line_total'] - $item['line_subtotal'] :  0;
                                ?>
                                <tr>
                                    <td>
                                        <?php if ( empty( $product ) ) { ?>
                                            <?php esc_html_e( 'Unknown item', 'live-carts-for-woocommerce' ); ?>
                                        <?php } else { ?>
                                            <a class="phplugins-lc-product-info" href="<?php echo( esc_url( $product->get_permalink() ) ); ?>" target="_blank">
                                                <?php 
                                                echo( get_the_post_thumbnail($product->get_id()).esc_html( $product->get_name() ) );
                                                ?>
                                            </a>
                                            <?php
                                            // Display product attributes/variations
                                            if ( $product && $product->is_type( 'variation' ) ) {
                                                $attributes = $product->get_variation_attributes();
                                                if ( ! empty( $attributes ) ) {
                                                    echo '<div class="phplugins-lc-product-attributes">';
                                                    foreach ( $attributes as $attr_name => $attr_value ) {
                                                        if ( $attr_value ) {
                                                            $taxonomy = str_replace( 'attribute_', '', $attr_name );
                                                            $term = get_term_by( 'slug', $attr_value, $taxonomy );
                                                            $label = wc_attribute_label( $taxonomy );
                                                            $value = $term ? $term->name : $attr_value;
                                                            echo '<span class="phplugins-lc-attribute">';
                                                            echo '<strong>' . esc_html( $label ) . ':</strong> ';
                                                            echo esc_html( $value );
                                                            echo '</span>';
                                                        }
                                                    }
                                                    echo '</div>';
                                                }
                                            }
                                            ?>
                                        <?php } ?>
                                    </td>
                                    <td><?php if ( isset( $item['quantity'] ) ) {
                                            echo( (float) $item['quantity'] );
                                        } ?></td>
                                    <td><?php if ( isset( $item['line_subtotal'] ) ) {
											// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- html output
                                            echo( wc_price( $item['line_subtotal'] ) );
                                        } ?></td>
                                </tr>

                            <?php } ?>

                            </tbody>
                            <tfoot>
                                <tr>
                                    <td>Subtotal:</td>
                                    <td></td>
                                    <td>
                                        <p class="phplugins-lc-total">
                                        <?php
										
										// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- html output
										echo( wc_price( $cartSubtotal ) );
										?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Discount:</td>
                                    <td></td>
                                    <td>
                                        <p class="phplugins-lc-total">
                                        <?php
										
										// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- html output
										echo( wc_price( $cartDiscount ) );
										?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Total:</td>
                                    <td></td>
                                    <td>
                                        <p class="phplugins-lc-total">
                                        <?php
										
										// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- html output
										echo( wc_price( $this->cartData->value ) );
										?>
                                        </p>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

			<?php } else
				
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- html output from hook
					echo($contentsOverride); ?>
					
					

				<?php $dateFormat = get_option('date_format'); $timeFormat = get_option('time_format'); $utc = new \DateTimeZone('UTC');?>

					<span class="berrypress-seperator"></span>
                    <div class="phplugins-lc-revisions">
                        <h2><?php echo(esc_html(sprintf( /* translators: %d = number of revisions */ _n('History (%d revision)', 'History (%d revisions)', count($history), 'live-carts-for-woocommerce'), count($history)))); ?></h2>

                        <?php foreach ($history as $revision) { ?>
                            <div class="phplugins-lc-revision-item">
                            <h3><?php echo(esc_html(mysql2date($dateFormat.' '.$timeFormat, $revision[0]))); ?></h3>
                            <ol class="phplugins-lc-diffs">
                            <?php foreach ($revision[1] as $diff) { ?>
                                <li class="phplugins-lc-diff-<?php echo(esc_attr($diff[0])); ?>">
                                    <?php
                                        switch ($diff[0]) {
                                            case 'add':
                                                echo(esc_html(sprintf(
                                                    /* translators: %1$s = product name, %2$d = quantity */
                                                    __('Added "%1$s" x %2$d', 'live-carts-for-woocommerce'),
                                                    $diff[1] ? $diff[1]->get_name() : __('(unknown product)', 'live-carts-for-woocommerce'),
                                                    $diff[2]
                                                )));
                                                break;
                                            case 'remove':
                                                echo(esc_html(sprintf(
                                                    /* translators: %s = product name */
                                                    __('Removed "%s"', 'live-carts-for-woocommerce'),
                                                    $diff[1] ? $diff[1]->get_name() : __('(unknown product)', 'live-carts-for-woocommerce')
                                                )));
                                                break;
                                            case 'change-quantity':
                                                echo(esc_html(sprintf(
                                                    /* translators: %1$s = product name, %2$d = old quantity, %3$d = new quantity */
                                                    __('Changed quantity of "%1$s" from %2$d to %3$d', 'live-carts-for-woocommerce'),
                                                    $diff[1] ? $diff[1]->get_name() : __('(unknown product)', 'live-carts-for-woocommerce'),
                                                    $diff[2],
                                                    $diff[3]
                                                )));
                                                break;
                                        }
                                        do_action('phplugins_live_carts_revision_diff_meta', $diff);
                                    ?>
                                </li>
                            <?php } ?>
                            </ol>
                            </div>
                        <?php } ?>
                    </div>
                <?php } ?>
                <?php do_action( 'phplugins_live_carts_admin_cart_details', $this->cartData->cart_id ); ?>
            </div>
		<?php } ?>
        <p>
            <a href="<?php echo( esc_url( remove_query_arg( 'cart_id' ) ) ); ?>"
               class="berrypress-btn berrypress-btn-secondary"><i
                        class="berrypress-icon-keyboard_arrow_left"></i><?php esc_html_e( 'Back to carts list', 'live-carts-for-woocommerce' ); ?>
            </a></p>
        </div>
		<?php
	}

	function getNav() {

		$nav = [
			[
				'link'   => self::getUrl(),
				'icon'   => 'berrypress-icon-cart',
				'title'  => __( 'Live Carts', 'live-carts-for-woocommerce' ),
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
				'active' => ! isset( $_GET['settings'] ) && ! isset( $_GET['cart_id'] ) && ! isset( $_GET['addons']) && ! isset( $_GET['activation']) && ! isset( $_GET['status'] )
			],
			[
				'link'   => self::getUrl( [ 'settings' => 1 ] ),
				'icon'   => 'berrypress-icon-settings',
				'title'  => __( 'Settings', 'live-carts-for-woocommerce' ),

				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
				'active' => isset( $_GET['settings'] ),
			],
			[
				'link'   => self::getUrl( [ 'healthstatus' => 1 ] ),
				'icon'   => 'berrypress-icon-help',
				'title'  => __( 'Status', 'live-carts-for-woocommerce' ),

				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
				'active' => isset( $_GET['healthstatus'] ),
			],
			//			[
			//				'link'     => self::getUrl(['table_settings' => 1]),
			//				'icon'     => 'berrypress-icon-settings',
			//				'title'    => __('Table Settings', 'live-carts-for-woocommerce'),
			//				'link_id'  => 'berrypress-show-settings-link',
			//			],
			[
				'link'   => admin_url( 'admin.php?page=wc-admin&path=/analytics/phplugins-carts' ),
				'icon'   => 'berrypress-icon-bar-chart',
				'title'  => __( 'Analytics', 'live-carts-for-woocommerce' ),

				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
				'active' => isset( $_GET['page'] ) && $_GET['page'] === 'wc-admin' && isset( $_GET['path'] ) && $_GET['path'] === '/analytics/phplugins-carts',
			],
		];
		
		if ($this->showExternalLinks) {
			$nav[] = [
				'link'   =>  self::getUrl( [ 'addons' => 1 ] ),
				'icon'   => 'berrypress-icon-addons',
				'title'  => __( 'Addons', 'live-carts-for-woocommerce' ),
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- just checking which page we're on
				'active' => isset( $_GET['addons'] )
			];
		}

		return $nav;
	}

	function getLogoUrl() {
		return plugin_dir_url( dirname( __DIR__ ) . '/live-carts-for-woocommerce.php' ) .
		       'assets/img/product-logo.svg';
	}

	function getProductUrl() {
        return 'https://wordpress.org/plugins/live-carts-for-woocommerce/';
	}

	function getHeaderText() {
		return __( 'Live Carts For WooCommerce', 'live-carts-for-woocommerce' );
	}

	function getAboveHeaderHtml() {

		$product_url = 'https://berrypress.com/live-carts/';

		// Check for Black Friday promotion
		$black_friday_notice = AdminPage::get_black_friday_notice( 'https://berrypress.com/shop/', 'Live Carts' );
		if ( !empty( $black_friday_notice ) ) {
			return $black_friday_notice;
		}

		// Default upgrade notice
		return sprintf(
			'<div class="berrypress-top-bar"><h2>%s <a class="berrypress-link" href="%s">%s<i class="berrypress-icon-filled berrypress-icon-keyboard_double_arrow_right"></i></a></h2></div>',
			esc_html__( 'Upgrade to Live Carts Pro to edit cart contents, create recovery URLs, and convert carts to orders with one click.', 'live-carts-for-woocommerce' ),
			esc_url( $product_url ),
			esc_html__( 'Upgrade', 'live-carts-for-woocommerce' )
		);
	}
}
