<?php
/**
 * The Template for displaying all single products
 *
 * This template can be overridden by copying it to yourtheme storeengine/single-product.php.
 *
 * the readme will list any important changes.
 *
 * @version     1.0.0
 */

use StoreEngine\Utils\Helper;
use StoreEnginePro\Addons\LicenseManagement\Classes\DeploymentVersion;
use StoreEnginePro\Addons\LicenseManagement\Classes\License;
use StoreEnginePro\Addons\LicenseManagement\Classes\Utils;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.WP.GlobalVariablesOverride.Prohibited

$paged                    = max( 1, get_query_var( 'paged' ) );
$downloadable_permissions = Helper::get_download_permissions_by_customer_id( $paged );
$hasAnyItems              = [ ! empty( $downloadable_permissions ) ];
$licensedDownloads        = false;

if ( Helper::get_addon_active_status( 'license-management', true ) ) {
	global $wpdb;
	// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$limit             = 10;
	$offset            = absint( ( $paged - 1 ) * $limit );
	$licensedDownloads = $wpdb->get_results(
		$wpdb->prepare( "
			SELECT SQL_CALC_FOUND_ROWS v.id version_id, l.id license_id
			FROM {$wpdb->prefix}storeengine_licenses l
			JOIN {$wpdb->prefix}storeengine_deployment_versions v
			  ON v.deployment_id = l.product_id
			WHERE l.customer_id = %d
			  AND l.status = 'active'
			  AND l.product_id <> ''
			  AND v.status = 'released'
			  AND v.deployed_at = (
				SELECT MAX(v2.deployed_at)
				FROM {$wpdb->prefix}storeengine_deployment_versions v2
				WHERE v2.deployment_id = l.product_id
				  AND v2.status = 'released'
			  )
			GROUP BY l.product_id
			ORDER BY MAX(l.created_at) DESC
			LIMIT {$offset}, {$limit};",
			get_current_user_id()
		)
	);
	$found_rows        = (int) $wpdb->get_var( 'SELECT FOUND_ROWS()' );
	$max_num_pages     = (int) ceil( $found_rows / $limit );
	$hasAnyItems[]     = ! empty( $licensedDownloads );
	// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
}

?>
<div class="storeengine-dashboard__section">
	<?php if ( ! empty( $downloadable_permissions ) ) { ?>
		<div class="storeengine-dashboard__downloads">
			<?php
			foreach ( $downloadable_permissions as $downloadable_permission ) {
				$product      = Helper::get_product( $downloadable_permission->get_product_id() );
				$file_data    = array_find( $product->get_downloadable_files(), fn( $download ) => $download['id'] === $downloadable_permission->get_download_id() );
				$data         = $file_data ? wp_get_attachment_metadata( $file_data['attachment_id'] ) : [];
				$package_size = $data['filesize'] ?? 0;
				$package_size = $package_size ? size_format( $package_size, 2 ) : __( 'N/A', 'storeengine' );
				// translators: %s: File size (formatted).
				$file_size = sprintf( __( 'File Size: %s', 'storeengine' ), $package_size );
				// translators: %s: File name.
				$file_name = sprintf( __( 'File Name: %s', 'storeengine' ), $downloadable_permission->get_file_name() );
				?>
				<div class="storeengine-dashboard__downloads-item storeengine-row storeengine-flex-align-center">
					<div class="storeengine-col-12 storeengine-col-md-6 storeengine-col-lg-9">
						<div class="storeengine-col-12 storeengine-col-sm-3 storeengine-col-md-3 package-preview">
							<?php storeengine_product_image( 'thumbnail', $downloadable_permission->get_product_id() ); ?>
						</div>
						<div class="storeengine-col-12 storeengine-col-sm-9 storeengine-col-md-9 package-info">
							<h4 class="product-name">
								<a href="<?php echo esc_html( get_permalink( $downloadable_permission->get_product_id() ) ); ?>"><?php echo esc_html( $downloadable_permission->get_product_title() ); ?></a>
							</h4>
							<div class="file-info">
								<div class="package-file-name storeengine-my-1 storeengine-mx-0"><?php echo esc_html( $file_name ); ?></div>
								<div class="package-type-size storeengine-mb-1 storeengine-mx-0"><?php echo esc_html( $file_size ); ?></div>
							</div>
						</div>
					</div>
					<div class="storeengine-col-12 storeengine-col-md-6 storeengine-col-lg-3 storeengine-flex">
						<a class="storeengine-btn storeengine-btn--download storeengine-btn--preset-blue" href="<?php echo esc_attr( $downloadable_permission->get_download_url() ); ?>">
							<?php storeengine_render_icon( 'download' ); ?>
							<span><?php esc_html_e( 'Download', 'storeengine' ); ?></span>
						</a>
					</div>
				</div>
			<?php } ?>
			<?php do_action( 'storeengine/templates/dashboard_downloads_pagination', $downloadable_permissions ); ?>
		</div>
	<?php } ?>
	<?php if ( $licensedDownloads ) { ?>
		<div class="storeengine-dashboard__downloads">
			<?php
			foreach ( $licensedDownloads as $download ) {
				$license    = new License( absint( $download->license_id ) );
				$deployment = new DeploymentVersion( absint( $download->version_id ) );

				// Prepare info.
				[
					'filename'     => $original_filename,
					'package_type' => $package_type,
					'package_size' => $package_size,
					'thumbnail'    => [ 'url' => $thumbnail ],
				] = $deployment->get_file_info();

				// translators: %s: File name.
				$file_name = sprintf( __( 'File Name: %s', 'storeengine' ), $original_filename );
				// translators: %s: Package type (Plugin, Theme, etc.).
				$package_type = sprintf( __( 'Package Type: %s', 'storeengine' ), $package_type );
				// translators: %s: File size (formatted).
				$file_size = sprintf( __( 'File Size: %s', 'storeengine' ), $package_size );
				// translators: %s: Package last updated.
				$updated_at   = sprintf( __( 'Last updated: %s', 'storeengine' ), human_time_diff( $deployment->get_updated_at()->getTimestamp() ) );
				$download_url = Utils::get_secure_download_link( $deployment );
				$title = get_the_title( $deployment->get_deployment_id() );
				?>
				<div class="storeengine-dashboard__downloads-item storeengine-row storeengine-flex-align-center">
					<div class="storeengine-col-12 storeengine-col-md-6 storeengine-col-lg-9">
						<div class="storeengine-row">
							<div class="storeengine-col-12 storeengine-col-sm-3 storeengine-col-md-3 package-preview">
								<?php
								if ( $thumbnail ) {
									?>
									<img class="wp-post-image" src="<?php echo esc_url( $thumbnail ); ?>" alt="<?php echo esc_attr( $title ); ?>"/>
									<?php
								} else {
									storeengine_product_image( 'thumbnail', $deployment->get_deployment_id() );
								}
								?>
							</div>
							<div class="storeengine-col-12 storeengine-col-sm-9 storeengine-col-md-9 package-info">
								<h4 class="product-name">
									<a href="<?php echo esc_url( get_permalink( $deployment->get_deployment_id() ) ); ?>"><?php echo esc_html( $title ); ?></a>
									<span class="current-version">
										<span class="screen-reader-text"><?php esc_html_e( 'Current Version', 'storeengine' ); ?></span>
										<span><?php echo esc_html( $deployment->get_version() ); ?></span>
									</span>
								</h4>
								<div class="file-info">
									<div class="package-file-name storeengine-my-1 storeengine-mx-0"><?php echo esc_html( $file_name ); ?></div>
									<div class="package-type storeengine-mb-1 storeengine-mx-0"><?php echo esc_html( $package_type ); ?></div>
									<div class="package-type-size storeengine-mb-1 storeengine-mx-0"><?php echo esc_html( $file_size ); ?></div>
									<div class="package-last-updated storeengine-mb-1 storeengine-mx-0"><?php echo esc_html( $updated_at ); ?></div>
								</div>
							</div>
						</div>
					</div>
					<div class="storeengine-col-12 storeengine-col-md-6 storeengine-col-lg-3 storeengine-flex">
						<a class="storeengine-btn storeengine-btn--download storeengine-btn--preset-blue" href="<?php echo esc_url( $download_url ); ?>">
							<?php storeengine_render_icon( 'download' ); ?>
							<span><?php esc_html_e( 'Download', 'storeengine' ); ?></span>
						</a>
					</div>
				</div>
			<?php } ?>
		</div>
	<?php } ?>
	<?php if ( empty( array_filter( $hasAnyItems ) ) ) { ?>
		<div class="storeengine-dashboard__downloads">
			<?php storeengine_oops_message( [
				'classes' => 'storeengine-my-5',
				'title'   => __( 'No Downloads Found!', 'storeengine' ),
				'message' => __( 'No downloads available. You haven’t purchased any downloadable products yet.', 'storeengine' ),
			] ); ?>
		</div>
	<?php } ?>
</div>
