<?php
/**
 * Download Media Library module settings template.
 *
 * @package DownloadMediaLibrary
 */

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'download-media-library' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Download Media Library requires an active license. Activate your license to export your media as ZIP archives.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

$module_id = $module_id ?? 'download-media-library';
$nonce     = wp_create_nonce( 'wpps_download_media_library' );
$ajax_url  = admin_url( 'admin-ajax.php' );
?>
<div class="wp-powersuite-module-settings wpps-dml-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description"><?php esc_html_e( 'Package your media library into downloadable ZIP files — entire library, specific months, or folders (when Categorize Media is enabled). ZIPs auto-expire after 24 hours.', 'wp-powersuite' ); ?></p>

	<div class="wpps-dml-stats wpps-dml-card">
		<h3><?php esc_html_e( 'Overview', 'wp-powersuite' ); ?></h3>
		<div class="wpps-dml-stat-row">
			<span class="wpps-dml-stat-label"><?php esc_html_e( 'Total size', 'wp-powersuite' ); ?>:</span>
			<span class="wpps-dml-stat-value" id="wpps-dml-total-size"><?php esc_html_e( 'Loading…', 'wp-powersuite' ); ?></span>
			<span class="wpps-dml-stat-sep">|</span>
			<span class="wpps-dml-stat-label"><?php esc_html_e( 'Total files', 'wp-powersuite' ); ?>:</span>
			<span class="wpps-dml-stat-value" id="wpps-dml-total-count">—</span>
		</div>
	</div>

	<div class="wpps-dml-download-options wpps-dml-card">
		<h3><?php esc_html_e( 'Download Options', 'wp-powersuite' ); ?></h3>
		<div class="wpps-dml-option-full">
			<button type="button" class="button button-primary" id="wpps-dml-download-all">
				<?php esc_html_e( 'Download All', 'wp-powersuite' ); ?>
			</button>
			<span class="wpps-dml-estimate" id="wpps-dml-estimate-full"></span>
			<span class="description"><?php esc_html_e( 'Entire library — all files in wp-content/uploads', 'wp-powersuite' ); ?></span>
		</div>

		<div class="wpps-dml-months-box wpps-dml-sub-card">
			<h4><?php esc_html_e( 'By Month', 'wp-powersuite' ); ?></h4>
			<p class="description"><?php esc_html_e( 'Select one or more months to download.', 'wp-powersuite' ); ?></p>
			<div id="wpps-dml-months-wrap" style="display: none;">
				<ul id="wpps-dml-months-list" class="wpps-dml-list wpps-dml-checkbox-list"></ul>
				<div class="wpps-dml-months-actions">
					<button type="button" class="button button-small" id="wpps-dml-download-selected" disabled>
						<?php esc_html_e( 'Download selected', 'wp-powersuite' ); ?>
					</button>
					<span class="wpps-dml-estimate" id="wpps-dml-estimate-months"></span>
				</div>
			</div>
		</div>

		<div class="wpps-dml-folders-box wpps-dml-sub-card">
			<h4><?php esc_html_e( 'By Folder', 'wp-powersuite' ); ?></h4>
			<p class="description"><?php esc_html_e( 'Download media from a folder (requires Categorize Media module).', 'wp-powersuite' ); ?></p>
			<div id="wpps-dml-folders-wrap" style="display: none;">
				<ul id="wpps-dml-folders-list" class="wpps-dml-list"></ul>
			</div>
		</div>
	</div>

	<div id="wpps-dml-progress-wrap" class="wpps-dml-progress-wrap" style="display: none;">
		<div class="wpps-dml-progress-bar">
			<div class="wpps-dml-progress-fill" id="wpps-dml-progress-fill"></div>
		</div>
		<p class="wpps-dml-progress-text" id="wpps-dml-progress-text"><?php esc_html_e( 'Creating ZIP… please wait. Do not close this window.', 'wp-powersuite' ); ?></p>
	</div>

	<div class="wpps-dml-generated wpps-dml-card">
		<h3><?php esc_html_e( 'Generated ZIPs', 'wp-powersuite' ); ?></h3>
		<p class="description"><?php esc_html_e( 'ZIPs auto-delete after 24 hours.', 'wp-powersuite' ); ?></p>
		<ul id="wpps-dml-zips-list" class="wpps-dml-zips-list"></ul>
		<p id="wpps-dml-no-zips" class="wpps-dml-no-zips description" style="display: none;"><?php esc_html_e( 'No ZIPs generated yet.', 'wp-powersuite' ); ?></p>
	</div>

	<div class="wpps-dml-info-box wpps-module-callout">
		<p>
			<strong><?php esc_html_e( 'Note', 'wp-powersuite' ); ?></strong><br>
			<?php esc_html_e( 'For very large libraries, consider downloading by month to avoid timeouts. ZIP creation may take several minutes — do not close the modal while processing.', 'wp-powersuite' ); ?>
		</p>
	</div>
</div>



<script>
(function() {
	'use strict';
	var container = document.querySelector('.wpps-dml-settings');
	if (!container) return;

	var totalSizeEl = container.querySelector('#wpps-dml-total-size');
	var totalCountEl = container.querySelector('#wpps-dml-total-count');
	var downloadAllBtn = container.querySelector('#wpps-dml-download-all');
	var estimateFullEl = container.querySelector('#wpps-dml-estimate-full');
	var monthsWrap = container.querySelector('#wpps-dml-months-wrap');
	var monthsList = container.querySelector('#wpps-dml-months-list');
	var downloadSelectedBtn = container.querySelector('#wpps-dml-download-selected');
	var estimateMonthsEl = container.querySelector('#wpps-dml-estimate-months');
	var foldersWrap = container.querySelector('#wpps-dml-folders-wrap');
	var foldersList = container.querySelector('#wpps-dml-folders-list');
	var progressWrap = container.querySelector('#wpps-dml-progress-wrap');
	var progressFill = container.querySelector('#wpps-dml-progress-fill');
	var zipsList = container.querySelector('#wpps-dml-zips-list');
	var noZipsEl = container.querySelector('#wpps-dml-no-zips');

	var nonce = <?php echo wp_json_encode( $nonce ); ?>;
	var ajaxUrl = <?php echo wp_json_encode( $ajax_url ); ?>;

	var state = { stats: null, creating: false };

	function clearChildren(el) {
		while (el.firstChild) {
			el.removeChild(el.firstChild);
		}
	}

	function formatBytes(bytes) {
		var b = Number(bytes);
		if (isNaN(b) || b < 0) return '0 B';
		if (b === 0) return '0 B';
		var k = 1024, s = ['B','KB','MB','GB'];
		var i = Math.min(Math.floor(Math.log(b) / Math.log(k)), s.length - 1);
		return parseFloat((b / Math.pow(k, i)).toFixed(2)) + ' ' + s[i];
	}

	function downloadZip(filename) {
		var fd = new FormData();
		fd.append('action', 'wpps_dml_download_zip');
		fd.append('nonce', nonce);
		fd.append('wpps_dml_file', filename);
		return fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) {
				if (!r.ok) throw new Error('download failed');
				return r.blob();
			})
			.then(function(blob) {
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = filename;
				a.style.display = 'none';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
				URL.revokeObjectURL(url);
			});
	}

	function loadStats() {
		var fd = new FormData();
		fd.append('action', 'wpps_dml_get_stats');
		fd.append('nonce', nonce);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (data.success && data.data) {
					state.stats = data.data;
					renderStats();
					renderMonths();
					renderFolders();
					renderZips();
				} else {
					totalSizeEl.textContent = '—';
					if (totalCountEl) totalCountEl.textContent = '—';
				}
			})
			.catch(function() {
				totalSizeEl.textContent = '—';
				if (totalCountEl) totalCountEl.textContent = '—';
			});
	}

	function renderStats() {
		if (!state.stats || !totalSizeEl) return;
		var sz = state.stats.total_size;
		totalSizeEl.textContent = (sz != null && !isNaN(Number(sz))) ? formatBytes(Number(sz)) : '—';
		if (totalCountEl) totalCountEl.textContent = (state.stats.total_count != null) ? state.stats.total_count.toLocaleString() : '—';
		if (estimateFullEl) estimateFullEl.textContent = state.stats.total_size ? ' (~' + formatBytes(state.stats.total_size) + ')' : '';
	}

	function renderMonths() {
		if (!state.stats || !state.stats.months || state.stats.months.length === 0) {
			monthsWrap.style.display = 'none';
			return;
		}
		monthsWrap.style.display = 'block';
		clearChildren(monthsList);
		state.stats.months.forEach(function(m) {
			var key = (m.year || '') + '-' + (m.month || '');
			var li = document.createElement('li');
			var cb = document.createElement('input');
			cb.type = 'checkbox';
			cb.id = 'wpps-dml-m-' + key.replace(/-/g,'');
			cb.value = key;
			cb.className = 'wpps-dml-month-cb';
			cb.addEventListener('change', updateMonthsSelection);
			var label = document.createElement('label');
			label.htmlFor = cb.id;
			label.textContent = key + ' — ' + (m.count || 0) + ' <?php echo esc_js( __( 'files', 'wp-powersuite' ) ); ?>, ' + formatBytes(m.size);
			label.className = 'description';
			li.appendChild(cb);
			li.appendChild(label);
			monthsList.appendChild(li);
		});
		updateMonthsSelection();
	}

	function updateMonthsSelection() {
		var checked = container.querySelectorAll('.wpps-dml-month-cb:checked');
		if (downloadSelectedBtn) downloadSelectedBtn.disabled = checked.length === 0;
		var est = 0;
		checked.forEach(function(cb) {
			var key = cb.value;
			var m = (state.stats.months || []).find(function(x) { return (x.year + '-' + x.month) === key; });
			if (m) est += m.size || 0;
		});
		if (estimateMonthsEl) estimateMonthsEl.textContent = est ? ' (~' + formatBytes(est) + ')' : '';
	}

	function renderFolders() {
		if (!state.stats || !state.stats.folders || state.stats.folders.length === 0) {
			foldersWrap.style.display = 'none';
			return;
		}
		foldersWrap.style.display = 'block';
		clearChildren(foldersList);
		state.stats.folders.forEach(function(f) {
			var li = document.createElement('li');
			var wrap = document.createElement('div');
			wrap.style.display = 'flex';
			wrap.style.flexWrap = 'wrap';
			wrap.style.alignItems = 'center';
			wrap.style.gap = '8px';
			var cbSub = document.createElement('input');
			cbSub.type = 'checkbox';
			cbSub.id = 'wpps-dml-sub-' + f.term_id;
			cbSub.className = 'wpps-dml-include-subfolders';
			var labelSub = document.createElement('label');
			labelSub.htmlFor = cbSub.id;
			labelSub.textContent = '<?php echo esc_js( __( 'Include subfolders', 'wp-powersuite' ) ); ?>';
			labelSub.className = 'description';
			var btn = document.createElement('button');
			btn.type = 'button';
			btn.className = 'button button-small';
			btn.textContent = '<?php echo esc_js( __( 'Download', 'wp-powersuite' ) ); ?> ' + (f.name || '');
			btn.dataset.type = 'folder';
			btn.dataset.folderId = f.term_id;
			btn.addEventListener('click', function(e) {
				var incl = document.getElementById('wpps-dml-sub-' + f.term_id);
				handleDownloadClick(e, incl && incl.checked);
			});
			var span = document.createElement('span');
			span.className = 'description';
			span.textContent = (f.count || 0) + ' <?php echo esc_js( __( 'items', 'wp-powersuite' ) ); ?>';
			wrap.appendChild(btn);
			wrap.appendChild(cbSub);
			wrap.appendChild(labelSub);
			wrap.appendChild(span);
			li.appendChild(wrap);
			foldersList.appendChild(li);
		});
	}

	function renderZips() {
		if (!state.stats || !state.stats.zips || state.stats.zips.length === 0) {
			clearChildren(zipsList);
			noZipsEl.style.display = 'block';
			return;
		}
		noZipsEl.style.display = 'none';
		clearChildren(zipsList);
		var expiryHours = state.stats.zip_expiry_hours || 24;
		state.stats.zips.forEach(function(z) {
			var li = document.createElement('li');
			var left = document.createElement('div');
			var created = z.created ? new Date(z.created * 1000).toLocaleString() : '';
			var expiryTs = z.expiry_ts || (z.created + expiryHours * 3600);
			var hoursLeft = Math.max(0, Math.floor((expiryTs - Date.now()/1000) / 3600));
			var expiresText = hoursLeft > 0 ? '<?php echo esc_js( __( 'Expires in', 'wp-powersuite' ) ); ?> ' + hoursLeft + ' <?php echo esc_js( __( 'hours', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Expired', 'wp-powersuite' ) ); ?>';
			var nameEl = document.createElement('strong');
			nameEl.textContent = z.filename || '';
			var metaEl = document.createElement('span');
			metaEl.className = 'description';
			metaEl.textContent = formatBytes(z.size) + (created ? ' • ' + created : '') + ' • ' + expiresText;
			left.appendChild(nameEl);
			left.appendChild(document.createElement('br'));
			left.appendChild(metaEl);
			var actions = document.createElement('div');
			actions.className = 'wpps-dml-zip-actions';
			var dlBtn = document.createElement('button');
			dlBtn.type = 'button';
			dlBtn.className = 'button button-small button-primary';
			dlBtn.textContent = '<?php echo esc_js( __( 'Download', 'wp-powersuite' ) ); ?>';
			dlBtn.dataset.filename = z.filename;
			dlBtn.addEventListener('click', function(e) {
				e.preventDefault();
				downloadZip(z.filename).catch(function() {
					alert('<?php echo esc_js( __( 'Download failed.', 'wp-powersuite' ) ); ?>');
				});
			});
			var delBtn = document.createElement('button');
			delBtn.type = 'button';
			delBtn.className = 'button button-small';
			delBtn.textContent = '<?php echo esc_js( __( 'Delete', 'wp-powersuite' ) ); ?>';
			delBtn.dataset.filename = z.filename;
			delBtn.addEventListener('click', handleDeleteZip);
			actions.appendChild(dlBtn);
			actions.appendChild(delBtn);
			li.appendChild(left);
			li.appendChild(actions);
			zipsList.appendChild(li);
		});
	}

	function setCreating(creating) {
		state.creating = creating;
		downloadAllBtn.disabled = creating;
		if (downloadSelectedBtn) downloadSelectedBtn.disabled = creating || container.querySelectorAll('.wpps-dml-month-cb:checked').length === 0;
		container.querySelectorAll('.wpps-dml-list button').forEach(function(b) { b.disabled = creating; });
		progressWrap.style.display = creating ? 'block' : 'none';
		progressFill.style.width = creating ? '30%' : '0%';
	}

	function createZip(fd) {
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				setCreating(false);
				if (data.success && data.data) {
					state.stats.zips = state.stats.zips || [];
					state.stats.zips.unshift({
						filename: data.data.filename,
						size: data.data.size,
						created: data.data.created,
						expiry_ts: data.data.expiry_ts || data.data.created + (state.stats.zip_expiry_hours || 24) * 3600
					});
					renderZips();
					if (data.data.filename) {
						downloadZip(data.data.filename).catch(function() {
							alert('<?php echo esc_js( __( 'ZIP created but download failed. Use the list below to retry.', 'wp-powersuite' ) ); ?>');
						});
					}
				} else {
					alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'An error occurred.', 'wp-powersuite' ) ); ?>');
				}
			})
			.catch(function() {
				setCreating(false);
				alert('<?php echo esc_js( __( 'Request failed. The library may be too large — try downloading by month.', 'wp-powersuite' ) ); ?>');
			});
	}

	function handleDownloadClick(e, includeSubfolders) {
		if (state.creating) return;
		var btn = e.target;
		if (btn.tagName === 'LABEL' || btn.type === 'checkbox') return;
		var type = btn.dataset.type;
		var month = btn.dataset.month || '';
		var folderId = btn.dataset.folderId || '0';
		includeSubfolders = !!includeSubfolders;

		if (type === 'full' && !confirm('<?php echo esc_js( __( 'Download entire media library? This may take several minutes for large libraries.', 'wp-powersuite' ) ); ?>')) return;
		if (type === 'month' && !confirm('<?php echo esc_js( __( 'Create ZIP for this month?', 'wp-powersuite' ) ); ?>')) return;
		if (type === 'folder' && !confirm('<?php echo esc_js( __( 'Create ZIP for this folder?', 'wp-powersuite' ) ); ?>' + (includeSubfolders ? ' <?php echo esc_js( __( 'Including subfolders.', 'wp-powersuite' ) ); ?>' : ''))) return;

		setCreating(true);
		var fd = new FormData();
		fd.append('action', 'wpps_dml_create_zip');
		fd.append('nonce', nonce);
		fd.append('type', type);
		if (type === 'month') fd.append('month', month);
		if (type === 'folder') {
			fd.append('folder_id', folderId);
			if (includeSubfolders) fd.append('include_subfolders', '1');
		}
		createZip(fd);
	}

	function handleDownloadSelected() {
		if (state.creating) return;
		var checked = container.querySelectorAll('.wpps-dml-month-cb:checked');
		if (checked.length === 0) return;
		if (!confirm('<?php echo esc_js( __( 'Create ZIP for selected months?', 'wp-powersuite' ) ); ?>')) return;

		setCreating(true);
		var fd = new FormData();
		fd.append('action', 'wpps_dml_create_zip');
		fd.append('nonce', nonce);
		fd.append('type', 'months');
		checked.forEach(function(cb) { fd.append('months[]', cb.value); });
		createZip(fd);
	}

	function handleDeleteZip(e) {
		var filename = e.target.dataset.filename;
		if (!filename || !confirm('<?php echo esc_js( __( 'Delete this ZIP file?', 'wp-powersuite' ) ); ?>')) return;

		var fd = new FormData();
		fd.append('action', 'wpps_dml_delete_zip');
		fd.append('nonce', nonce);
		fd.append('filename', filename);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (data.success && state.stats && state.stats.zips) {
					state.stats.zips = state.stats.zips.filter(function(z) { return z.filename !== filename; });
					renderZips();
				}
			});
	}

	downloadAllBtn.addEventListener('click', function() {
		if (state.creating) return;
		downloadAllBtn.dataset.type = 'full';
		handleDownloadClick({ target: downloadAllBtn }, false);
	});

	if (downloadSelectedBtn) downloadSelectedBtn.addEventListener('click', handleDownloadSelected);

	loadStats();
})();
</script>
