<?php
/**
 * Review landing page helper functions.
 *
 * @package ProofWP
 */
declare(strict_types=1);

defined('ABSPATH') || exit;

/**
 * Render the review page controller.
 */
function dsproofwp_render_review_landing_page(): void
{
	$token = sanitize_text_field(get_query_var('proofwp_review_token', ''));

	if (empty($token)) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('Invalid token.', 'proofwp'),
			__('The review link is invalid. Please verify your email or contact support.', 'proofwp')
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	if (!function_exists('wc_get_order')) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('WooCommerce Required', 'proofwp'),
			__('WooCommerce is required to display the review page.', 'proofwp')
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	global $wpdb;
	$review_request_repo = new DSProofwp_Review_Request_Repository($wpdb);
	$request = $review_request_repo->get_request_by_token($token);

	if (empty($request) || empty($request['order_id'])) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('Invalid or Expired Link', 'proofwp'),
			__('The review link you clicked is invalid or has expired. Please check your email or contact support.', 'proofwp')
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	$order = wc_get_order((int) $request['order_id']);

	if (!$order) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('Order Not Found', 'proofwp'),
			__('The order associated with this review link could not be found. Please contact support.', 'proofwp')
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	$order_status = $order->get_status();
	if (in_array($order_status, ['cancelled', 'refunded'], true)) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('Order Not Eligible', 'proofwp'),
			sprintf(
				/* translators: %s: order status */
				__('This order has been %s and is no longer eligible for review. If you believe this is an error, please contact support.', 'proofwp'),
				esc_html($order_status)
			)
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	$order_items = $order->get_items();
	if (empty($order_items)) {
		dsproofwp_render_review_page_header();
		dsproofwp_render_review_error(
			__('No Products Found', 'proofwp'),
			__('This order has no products to review. If you believe this is an error, please contact support.', 'proofwp')
		);
		dsproofwp_render_review_page_footer();
		return;
	}

	// Ensure form renderer is available (split into its own file).
	require_once dirname(__DIR__) . '/includes/one-page-review-form.php';

	$page_data = [
		'errors' => [],
		'posted_rating' => [],
		'posted_review' => [],
		'has_submitted' => false,
	];

	if ('POST' === $_SERVER['REQUEST_METHOD'] && isset($_POST['proofwp_review_nonce'])) {
		require_once dirname(__DIR__) . '/includes/one-page-review-form-handler.php';
		$page_data = dsproofwp_handle_review_form_submission($order, $order_items, $review_request_repo);
	}

	dsproofwp_render_review_page_header();

	if (!empty($page_data['success']) && $page_data['success'] === true) {
		dsproofwp_render_review_success($order);
	} elseif (!empty($page_data['errors'])) {
		require_once dirname(__DIR__) . '/includes/one-page-review-form.php'; 
		dsproofwp_render_review_form($order, $order_items, $request, $page_data);
	} elseif (isset($_GET['success']) && '1' === $_GET['success']) {
		dsproofwp_render_review_success($order);
	} else {
		dsproofwp_render_review_form($order, $order_items, $request, $page_data);
	}

	dsproofwp_render_review_page_footer();
}

/**
 * Render page header.
 */
function dsproofwp_render_review_page_header(): void
{
	require_once __DIR__ . '/one-page-review-form-handler.php';
	$settings = dsproofwp_get_form_settings();

	wp_enqueue_style(
		'dsproofwp-one-page-review-form',
		plugins_url('assets/css/one-page-review-form.css', dirname(__DIR__) . '/proofwp.php'),
		[],
		time()
	);
	wp_enqueue_script(
		'dsproofwp-one-page-review-form',
		plugins_url('assets/js/one-page-review-form.js', dirname(__DIR__) . '/proofwp.php'),
		[],
		time(),
		true
	);
	wp_localize_script(
		'dsproofwp-one-page-review-form',
		'dsproofwpFormSettings',
		[
			'image_max_size_mb'    => $settings['image_max_size_mb'],
			'video_max_size_mb'    => $settings['video_max_size_mb'],
			'image_max_count'      => $settings['image_max_count'],
			'video_max_count'      => $settings['video_max_count'],
			'image_upload_enabled' => $settings['image_upload_enabled'],
			'video_upload_enabled' => $settings['video_upload_enabled'],
			'allowed_image_types'  => $settings['allowed_image_types'],
			'allowed_video_types'  => $settings['allowed_video_types'],
			'recaptcha_enabled'    => $settings['recaptcha_enabled'],
			'recaptcha_site_key'   => $settings['recaptcha_site_key'],
			'recaptcha_secret_key_set' => $settings['recaptcha_secret_key_set'],
			'i18n' => [
				'unsupported_type'  => __('Unsupported or disabled file type.', 'proofwp'),
				'mixed_media'       => __('Only one type of media (images or videos) is allowed per review. Mixed media was ignored.', 'proofwp'),
				'large_images'      => sprintf(__('Some images exceeded the maximum size limit of %dMB and were ignored.', 'proofwp'), $settings['image_max_size_mb']),
				'large_videos'      => sprintf(__('Some videos exceeded the maximum size limit of %dMB and were ignored.', 'proofwp'), $settings['video_max_size_mb']),
				'max_images_limit'  => sprintf(__('You can only upload up to %d image(s). Extra images were ignored.', 'proofwp'), $settings['image_max_count']),
				'max_videos_limit'  => sprintf(__('You can only upload up to %d video(s). Extra videos were ignored.', 'proofwp'), $settings['video_max_count']),
				'submit_rating'     => __('Please submit at least one rating before submitting.', 'proofwp'),
				'recaptcha_required' => __('Please complete the reCAPTCHA challenge.', 'proofwp'),
			]
		]
	);

	if (function_exists('get_header')) {
		get_header();
		return;
	}

	echo '<!DOCTYPE html><html lang="' . esc_attr(get_bloginfo('language')) . '"><head>';
	echo '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
	echo '<title>' . esc_html__('Leave a Review', 'proofwp') . '</title>';
	echo '<style>body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;background:#f4f6fb;color:#333;}#proofwp-review-root{padding:20px;}a{color:#5b4dd3;text-decoration:none;}a:hover{text-decoration:underline;}</style>';
	echo wp_head();
	echo '</head><body><div id="proofwp-review-root">';
}

/**
 * Render page footer.
 */
function dsproofwp_render_review_page_footer(): void
{
	if (function_exists('get_footer')) {
		get_footer();
		return;
	}

	echo '</div>';
	echo wp_footer();
	echo '</body></html>';
}



/**
 * Handle a single upload for review media.
 */
function dsproofwp_handle_review_file_upload(array $file, int $product_id): int|WP_Error
{

	$file['error'] = $file['error'] ?? 0;

	$overrides = [
		'test_form' => false,
		'test_type' => false,
	];

	if ( ! function_exists( 'wp_handle_sideload' ) ) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }

	$sideload = wp_handle_sideload($file, $overrides, current_time('mysql'));
	if (isset($sideload['error'])) {
		return new WP_Error('upload_error', $sideload['error']);
	}

	$attachment = [
		'post_mime_type' => $sideload['type'],
		'guid'           => $sideload['url'],
		'post_parent'    => 0,
		'post_title'     => sanitize_file_name(pathinfo($file['name'], PATHINFO_FILENAME)),
		'post_content'   => sprintf(__('Review media for product %d', 'proofwp'), $product_id),
	];

	$attachment_id = wp_insert_attachment($attachment, $sideload['file'], 0, true);
	if (is_wp_error($attachment_id)) {
		return $attachment_id;
	}

	if (!function_exists('wp_generate_attachment_metadata')) {
		require_once ABSPATH . 'wp-admin/includes/image.php';
	}

	wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $sideload['file']));

	return (int) $attachment_id;
}

/**
 * Determine media type from file extension.
 */
function dsproofwp_determine_media_type(string $filename): string
{
	$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
	if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif','webp'], true)) {
		return 'image';
	}
	if (in_array($extension, ['mp4', 'webm', 'ogg', 'mov', 'avi'], true)) {
		return 'video';
	}
	return 'unknown';
}

/**
 * Render the success panel.
 */
function dsproofwp_render_review_success(WC_Order $order): void
{
	$site_url = home_url();
	?>
	<section class="proofwp-review-page">
		<div class="proofwp-review-shell proofwp-success-shell">
			<h1><?php esc_html_e('Thank you for your feedback!', 'proofwp'); ?></h1>
			<p><?php esc_html_e('Your review has been submitted successfully. We appreciate your input.', 'proofwp'); ?></p>
			<div class="proofwp-success-actions">
				<a class="proofwp-button proofwp-button-primary" href="<?php echo esc_url($site_url); ?>"><?php esc_html_e('Continue Shopping', 'proofwp'); ?></a>
				<?php if (function_exists('wc_get_page_permalink')): ?>
					<a class="proofwp-button proofwp-button-secondary" href="<?php echo esc_url(wc_get_page_permalink('myaccount')); ?>"><?php esc_html_e('View My Account', 'proofwp'); ?></a>
				<?php endif; ?>
			</div>
		</div>
	</section>
	<style>
		.proofwp-success-shell{padding:50px;text-align:center;}
		.proofwp-success-shell h1{font-size:36px;margin-bottom:18px;color:#1f255d;}
		.proofwp-success-shell p{margin-bottom:28px;color:#5e6480;font-size:16px;line-height:1.7;}
		.proofwp-success-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:14px;}
		.proofwp-button-secondary{background:#f4f5ff;color:#2f334d;border:1px solid #d9d9e6;}
	</style>
	<?php
}

/**
 * Render an error panel.
 */
function dsproofwp_render_review_error(string $title, string $message): void
{
	?>
	<section class="proofwp-review-page">
		<div class="proofwp-review-shell proofwp-error-shell">
			<h1><?php echo esc_html($title); ?></h1>
			<p><?php echo esc_html($message); ?></p>
			<a class="proofwp-button proofwp-button-primary" href="<?php echo esc_url(home_url('/')); ?>"><?php esc_html_e('Return Home', 'proofwp'); ?></a>
		</div>
	</section>
	<style>
		.proofwp-error-shell{padding:50px;text-align:center;}
		.proofwp-error-shell h1{font-size:32px;margin-bottom:16px;color:#c73737;}
		.proofwp-error-shell p{margin-bottom:24px;color:#5e6480;font-size:15px;line-height:1.7;}
	</style>
	<?php
}

/**
 * Return the current URL.
 */
function dsproofwp_get_current_url(): string
{
	$protocol = is_ssl() ? 'https://' : 'http://';
	$host = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'] ?? ''));
	$uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'] ?? ''));
	return $protocol . $host . $uri;
}
