<?php
/**
 * LeadMagnets
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

use setasign\Fpdi\Fpdi;
use chillerlan\QRCode\QROptions;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\Common\EccLevel;
use chillerlan\QRCode\Output\QRFpdf;

/**
 * Creates the CommonFrameworkPlugin post type and shortcodes to output them.
 */
class LeadMagnets extends \CommonFrameworkPlugin\Module {
	/**
	 * Only register if on an admin page and if fieldmanager plugin is active.
	 *
	 * @return bool
	 */
	public function can_register() {
		return true;
	}

	/**
	 * Register our hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'admin_menu', [ $this, 'add_cf_tools_page' ] );
		add_action( 'admin_post_generate_lead_magnets', [ $this, 'create_lead_magnet_pdfs' ] );
	}

	/**
	 * Adds network admin page which will be used to import Lead Magnets.
	 */
	public function add_cf_tools_page() {
		if ( empty( $GLOBALS['admin_page_hooks']['cf_tools'] ) ) {
			add_menu_page(
				'CF Tools',
				'CF Tools',
				'manage_options',
				'cf_tools',
				[ $this, 'cf_tools_page' ],
				'dashicons-admin-network',
				2
			);
		}
	}

	/**
	 * Displays the data on the Common Framework Network Admin Page.
	 */
	public function cf_tools_page() {
		include COMMON_FRAMEWORK_PLUGIN_INC . 'pages/tools.php';
	}

	/**
	 * Creates dynamic Lead Magnet PDFs based on template.
	 *
	 * @return void
	 */
	public function create_lead_magnet_pdfs() {
		$pdf_directory = COMMON_FRAMEWORK_PLUGIN_PATH . 'pdfs/';

		// New lead magnets get added to this array.
		$lead_magnets = [
			[
				'file_name' => 'components-in-a-data-center-that-need-monitoring.pdf',
				'black_box_copy' => 'Every device in your data center needs to be monitored to optimize performance and prevent downtime. [company_name] provides cost savings with our monitoring and management solutions for every facility. Contact us today to start today!',
			],
			[
				'file_name' => 'how-to-pick-a-ups.pdf',
				'black_box_copy' => 'Choosing the right UPS can be complex-we make it simple. Let [company_name] help you find the perfect fit for your data center. Contact us today to speak with an expert and ensure your operations stay powered, no matter what.',
			],
			[
				'file_name' => 'how-to-find-the-right-rack-size.pdf',
				'black_box_copy' => "Finding the right rack for your data center can be confusing. It's difficult to figure out how to start, let alone find the right product. [company_name] can deliver the perfect rack for your facility. Contact us today so your data center stays secure and organized.",
			],
			[
				'file_name' => 'integrated-solutions-guide.pdf',
				'black_box_copy' => 'Contact us today to get more information on our Integrated Solutions or traditional data center equipment. One of our team members will be happy to help you find the right devices to suit your specific needs.',
			],
			[
				'file_name' => 'running-smoothly-with-it-management.pdf',
				'black_box_copy' => 'IT management gives you the power to control every piece of equipment in your facility so you can improve efficiency and prevent downtime. However, this checklist might not include all the equipment in your unique location. We can help you find the right IT management equipment to keep your facility running smoothly.',
			],
			[
				'file_name' => 'what-kind-of-pdu-do-you-need.pdf',
				'black_box_copy' => 'Your data center needs a PDU that will fit all your needs so your equipment can run no matter what. While this guide is a good starting point, there is so much more that goes into picking the right PDU for your facility. Contact us today to talk to our team of experts and ensure you get the perfect PDU for your data center needs.',
			],
			[
				'file_name' => 'which-cooling-solution-does-your-facility-need.pdf',
				'black_box_copy' => 'Your data center needs a reliable cooling system that will prevent dangerous overheating and downtime. While this guide is a good starting point, there is much more that goes into selecting the right cooling solution for your unique facility. Contact us today to talk to our team of experts and ensure you get the perfect cooling system for your data center needs.',
			],
			[
				'file_name' => 'how-to-select-the-right-busway.pdf',
				'black_box_copy' => 'Contact us today to talk to our team of experts and learn which busway will best meet your data center’s needs.',
			],
		];

		foreach ( $lead_magnets as $lead_magnet ) {
			$this->create_pdf_from_source( $pdf_directory . $lead_magnet['file_name'], pathinfo( $lead_magnet['file_name'], PATHINFO_FILENAME ), $lead_magnet['black_box_copy'] );
		}

		// Exits admin_post action when manually running the cron from the admin page.
		if ( ! empty( $_POST['action'] ) && 'generate_lead_magnets' === $_POST['action'] ) {
			$redirect_url = get_site_url() . '/wp-admin/admin.php?page=cf_tools';
			wp_safe_redirect( $redirect_url );
			exit;
		}
	}

	/**
	 * Creates a Lead Magnet PDF from a template file.
	 *
	 * @param string $source_file      Path to the source PDF template file.
	 * @param string $new_file_name    Base name for the new generated PDF.
	 * @param string $black_box_copy   Custom text to display in the black callout box on the final page.
	 *
	 * @return void
	 */
	public function create_pdf_from_source( $source_file, $new_file_name, $black_box_copy ) {
		if ( ! defined( 'FPDF_FONTPATH' ) ) {
			define( 'FPDF_FONTPATH', COMMON_FRAMEWORK_PLUGIN_PATH . 'fonts/' );
		}

		// Sets, checks, and creates directory for Lead Magnet PDFs
		$upload_dir = wp_upload_dir();
		$document_directory = $upload_dir['basedir'] . '/lead-magnets';
		$document_directory_uri = $document_directory . '/';

		if ( ! file_exists( $document_directory ) ) {
			wp_mkdir_p( $document_directory );
		}

		$this->create_pdf( $document_directory_uri, $source_file, $new_file_name, $black_box_copy );
	}

	/**
	 * Generates and saves the Lead Magnet PDF, inserting dynamic content including logo, contact info, and custom messaging.
	 *
	 * @param string   $document_directory_uri Directory path to save the generated PDF.
	 * @param string   $source_file            Path to the source PDF template file.
	 * @param string   $new_file_name          Base name for the output PDF file.
	 * @param string   $black_box_copy         Custom message for the black callout box on the final page.
	 * @param int|null $blog_id                (Optional) Blog ID when running in a multisite context.
	 *
	 * @return void
	 */
	private function create_pdf( $document_directory_uri, $source_file, $new_file_name, $black_box_copy, $blog_id = null ) {
		// Get the custom logo and contact information

		$image      = '';
		$white_logo = get_field( 'white_logo', 'option' );
		if ( ! empty( $white_logo ) ) {
			if ( ! empty( $white_logo['url'] ) ) {
				$image = $white_logo['url'];
			}
		} else {
			$custom_logo_id = get_theme_mod( 'custom_logo' );
			$image          = wp_get_attachment_image_src( $custom_logo_id, 'full' );
			if ( ! empty( $image[0] ) ) {
				$image = $image[0];
			}
		}
		if ( empty( $image ) ) {
			$image = 'https://placehold.co/50x50.png';
		}

		$company_name = get_field( 'company_name', 'option' );
		$phone_number = get_field( 'phone_number', 'option' );
		$primary_email = get_field( 'primary_email', 'option' );
		$parsed_url = parse_url( home_url() );
		$domain = $parsed_url['host'];

		// Create QR code URL
		$qr_code_url = home_url( '/contact-us/?utm_source=pdf&utm_medium=qr-code&utm_campaign=leadmagnet&utm_content=footer_link' );
		$qr_code = $this->generate_qr_code( $qr_code_url );

		$pdf = new Fpdi();

		$page_count = $pdf->setSourceFile( $source_file );
		$pdf->AddFont( 'Lato-Regular', 'R', 'Lato-Regular.php' );
		$pdf->SetFont( 'Lato-Regular', 'R', 18 );

		// Track the last page number manually
		$last_page = $page_count;

		for ( $page_no = 1; $page_no <= $page_count; $page_no++ ) {
			$template_id = $pdf->importPage( $page_no );
			$pdf->AddPage();
			$pdf->useTemplate( $template_id, [ 'adjustPageSize' => true ] );

			// Add logo to the first page header
			if ( 1 === $page_no ) {
				// 210 by 30 pixels
				$pdf->Image(
					$image,
					10,
					10,
					0,
					10,       // 49px ≈ 13mm
					'',
					home_url( '/contact-us/?utm_source=pdf&utm_medium=image&utm_campaign=leadmagnet&utm_content=logo' )
				);
			}

			$pdf->SetTextColor( 254, 91, 27 );

			$pdf->SetFont( 'Lato-Regular', 'R', 9 );
			$pdf->Text( 12, 268, $domain );
			$width = $pdf->GetStringWidth( $domain );
			$pdf->Link( 12, 266, $width, 2, home_url( '/contact-us/?utm_source=pdf&utm_medium=text&utm_campaign=leadmagnet&utm_content=footer_domain' ) );
			$pdf->SetDrawColor( 254, 91, 27 );
			$pdf->Line( 12, 269, $pdf->GetStringWidth( $domain ) + 12, 269 );

			$pdf->SetFont( 'Lato-Regular', 'R', 9 );
			$pdf->Text( 12, 274, $phone_number );
			$width = $pdf->GetStringWidth( $phone_number );
			$pdf->Link( 12, 272, $width, 2, 'tel:' . $phone_number );
			$pdf->SetDrawColor( 254, 91, 27 );
			$pdf->Line( 12, 275, $pdf->GetStringWidth( $phone_number ) + 12, 275 );

			$pdf->SetY( -15 );

			// Insert QR code
			$pdf->Image(
				$qr_code, // QR code image
				$pdf->GetX() + 180,
				$pdf->GetY() - 8,
				20, // size
				20, // size
				'PNG' // type
			);

			// Logo height in mm for 24px
			$logo_footer_height_mm = 6.35;
			$right_margin = 28;

			// Use real aspect ratio if available
			list($img_width, $img_height) = @getimagesize( $image );
			$aspect_ratio = $img_width && $img_height ? $img_width / $img_height : 1;
			$logo_footer_width_mm = $logo_footer_height_mm * $aspect_ratio;

			// Right-align it
			$logo_x = $pdf->GetPageWidth() - $logo_footer_width_mm - $right_margin;
			$logo_y = $pdf->GetY() - 1; // fine-tune this if it's overlapping

			$pdf->Image(
				$image,
				$logo_x,
				$logo_y,
				$logo_footer_width_mm,
				$logo_footer_height_mm,
				'PNG',
				home_url( '/contact-us/?utm_source=pdf&utm_medium=image&utm_campaign=leadmagnet&utm_content=footer_logo' )
			);

			if ( $last_page === $page_no ) {
				// Black box content
				$full_text = str_replace( '[company_name]', $company_name, $black_box_copy );

				$x = 50;
				$y = 212;
				$box_width = 130;
				$line_height = 4;

				$pdf->SetFont( 'Lato-Regular', 'R', 9 );
				$pdf->SetTextColor( 255, 255, 255 );
				$pdf->SetXY( $x, $y );

				// $wrapped_text = wordwrap($full_text, 100, "\n", true);
				$pdf->MultiCell( $box_width, $line_height, $full_text, 0, 'L' );

				// Common styling
				$pdf->SetFont( 'Lato-Regular', 'R', 10 );
				$label_color = [ 255, 255, 255 ];
				$link_color = [ 254, 91, 27 ];
				$link_y_offset = 5;  // Controls how close the underline is to the text
				$link_height = 5;      // Height of the clickable area

				// Website
				$domain = parse_url( home_url(), PHP_URL_HOST );
				$pdf->SetY( 228 );
				$pdf->SetTextColor( ...$label_color );
				$pdf->SetXY( 75, $pdf->GetY() );
				$pdf->Cell( 0, 6, 'Website:', 0, 0, 'L' );
				$label_width = $pdf->GetStringWidth( 'Website:' );

				$pdf->SetTextColor( ...$link_color );
				$link_x = 75 + $label_width + 1;
				$link_y = $pdf->GetY();
				$link_width = $pdf->GetStringWidth( $domain );
				$pdf->SetXY( $link_x, $pdf->GetY() );
				$pdf->Cell( 0, 6, $domain, 0, 0, 'L' );

				$pdf->SetDrawColor( ...$link_color );
				$pdf->Line( $link_x + 1, $link_y + $link_y_offset, $link_x + $link_width + 1, $link_y + $link_y_offset );
				$pdf->Link( $link_x + 1, $link_y, $link_width, $link_height, home_url() );

				// Phone
				$pdf->SetY( 234 );
				$pdf->SetTextColor( ...$label_color );
				$pdf->SetXY( 75, $pdf->GetY() );
				$pdf->Cell( 0, 6, 'Phone:', 0, 0, 'L' );
				$label_width = $pdf->GetStringWidth( 'Phone:' );

				$pdf->SetTextColor( ...$link_color );
				$link_x = 75 + $label_width + 1;
				$link_y = $pdf->GetY();
				$link_width = $pdf->GetStringWidth( $phone_number );
				$pdf->SetXY( $link_x, $pdf->GetY() );
				$pdf->Cell( 0, 6, $phone_number, 0, 0, 'L' );

				$pdf->SetDrawColor( ...$link_color );
				$pdf->Line( $link_x + 1, $link_y + $link_y_offset, $link_x + $link_width + 1, $link_y + $link_y_offset );
				$pdf->Link( $link_x + 1, $link_y, $link_width, $link_height, 'tel:' . $phone_number );

				// Email
				$pdf->SetY( 240 );
				$pdf->SetTextColor( ...$label_color );
				$pdf->SetXY( 75, $pdf->GetY() );
				$pdf->Cell( 0, 6, 'Email:', 0, 0, 'L' );
				$label_width = $pdf->GetStringWidth( 'Email:' );

				$pdf->SetTextColor( ...$link_color );
				$link_x = 75 + $label_width + 1;
				$link_y = $pdf->GetY();
				$link_width = $pdf->GetStringWidth( $primary_email );
				$pdf->SetXY( $link_x, $pdf->GetY() );
				$pdf->Cell( 0, 6, $primary_email, 0, 0, 'L' );

				$pdf->SetDrawColor( ...$link_color );
				$pdf->Line( $link_x + 1, $link_y + $link_y_offset, $link_x + $link_width + 1, $link_y + $link_y_offset );
				$pdf->Link( $link_x + 1, $link_y, $link_width, $link_height, 'mailto:' . $primary_email );
			}
		}

		// Output PDF to the specified directory
		$blog_id = is_null( $blog_id ) ? 1 : $blog_id;
		$pdf->Output( 'F', $document_directory_uri . $new_file_name . '-' . $blog_id . '.pdf' );
	}

	/**
	 * Generate a QR code for a URL.
	 *
	 * @param string $url URL to generate QR code for.
	 * @return string Path to the generated QR code image.
	 */
	private function generate_qr_code( $url ) {

		$options = new QROptions(
			[
				'version'    => 10,
				'outputType' => 'png',
				'eccLevel'   => QRCode::ECC_L,
			]
		);

		$qrcode = new QRCode( $options );
		return $qrcode->render( $url );
	}
}
