<?php
if ($lastid) {
	global $wpdb;
	$voucher_table = $wpdb->prefix . 'giftvouchers_list';

	$query = $wpdb->prepare("SELECT * FROM `$voucher_table` WHERE id = %d", $lastid);
	$result = $wpdb->get_row($query);
}

// Ensure commonly used variables are defined to avoid PHP notices when this template is included
$invoice_color = (isset($invoice_color) && is_array($invoice_color) && count($invoice_color) >= 3) ? $invoice_color : array(0,0,0);
$seller_company_name = isset($seller_company_name) ? $seller_company_name : '';
$seller_addr_line1 = isset($seller_addr_line1) ? $seller_addr_line1 : '';
$seller_addr_line2 = isset($seller_addr_line2) ? $seller_addr_line2 : '';
$seller_addr_line3 = isset($seller_addr_line3) ? $seller_addr_line3 : '';
$seller_addr_line4 = isset($seller_addr_line4) ? $seller_addr_line4 : '';
$formtype = isset($formtype) ? $formtype : '';
$special_price = isset($special_price) ? $special_price : 0;

// Use safe PDF creation to prevent conflicts with other plugins
$invoice = wpgv_create_pdf_safe('P', 'pt', array(595, 900));
$invoice->SetAutoPageBreak(0);
$invoice->AddPage();
if (get_locale() == "el") {
	wpgv_add_font_safe($invoice, 'Arial_Greek', '', 'Arial_Greek.php');
	$invoice->SetFont('Arial_Greek', '', 10);
}
$invoice->SetTextColor(0, 0, 0);

if (get_locale() != "el") {
	$invoice->SetFont('Arial', '');
}
$invoice->SetFontSize(10);

// Defensive defaults for invoice options (avoid notices when DB row is missing)
$invoice_color = (isset($invoice_color) && is_array($invoice_color) && count($invoice_color) >= 3) ? $invoice_color : array(0,0,0);
$invoice->SetTextColor($invoice_color[0], $invoice_color[1], $invoice_color[2]);

$invoice_company_logo = (is_object($invoice_options) && !empty($invoice_options->company_logo)) ? $invoice_options->company_logo : '';

// Validate logo value: accept only a readable filesystem path, a valid uploads URL that maps to a file,
// a reachable remote URL (will attempt download earlier), or a WP attachment ID.
$validated_logo = '';
if (!empty($invoice_company_logo)) {
	// If it's a numeric attachment ID, try to get the file path
	if (is_numeric($invoice_company_logo) && function_exists('get_attached_file')) {
		$att_path = get_attached_file(intval($invoice_company_logo));
		if ($att_path && file_exists($att_path)) {
			$validated_logo = $att_path;
		}
	}

	// If still empty and it's an absolute file path
	if (empty($validated_logo) && file_exists($invoice_company_logo)) {
		$validated_logo = $invoice_company_logo;
	}

	// If still empty and it's a URL, we'll keep it for mapping/download logic below
	if (empty($validated_logo) && filter_var($invoice_company_logo, FILTER_VALIDATE_URL)) {
		$validated_logo = $invoice_company_logo; // will be resolved/mapped later
	}

	// If value is trivial (like 'test' or other non-path/non-url), ignore it to avoid printing raw text
	if (!empty($validated_logo)) {
		$invoice_company_logo = $validated_logo;
	} else {
		// clear invalid logo values
		$invoice_company_logo = '';
	}
}
$invoice_company_name = (is_object($invoice_options) && isset($invoice_options->company_name)) ? $invoice_options->company_name : '';
$invoice_address_line1 = (is_object($invoice_options) && isset($invoice_options->address_line1)) ? $invoice_options->address_line1 : '';
$invoice_address_line2 = (is_object($invoice_options) && isset($invoice_options->address_line2)) ? $invoice_options->address_line2 : '';
$invoice_address_line3 = (is_object($invoice_options) && isset($invoice_options->address_line3)) ? $invoice_options->address_line3 : '';
$invoice_address_line4 = (is_object($invoice_options) && isset($invoice_options->address_line4)) ? $invoice_options->address_line4 : '';
$invoice_bill_number = (is_object($invoice_options) && isset($invoice_options->bill_number)) ? $invoice_options->bill_number : '';
$invoice_current_number_format = (is_object($invoice_options) && isset($invoice_options->current_number_format)) ? $invoice_options->current_number_format : '';
$invoice_bottom_line = (is_object($invoice_options) && isset($invoice_options->bottom_line)) ? $invoice_options->bottom_line : '';
$invoice_bottom_line_2 = (is_object($invoice_options) && isset($invoice_options->bottom_line_2)) ? $invoice_options->bottom_line_2 : '';

if ($invoice_company_logo != '') {

	// If stored logo is a uploads URL, map it to the uploads filesystem path so getimagesize()/FPDF can read it
	$invoice_company_logo_path = $invoice_company_logo;
	if (strpos($invoice_company_logo, 'http') === 0) {
		$uploads = wp_upload_dir();
		if (!empty($uploads['baseurl']) && strpos($invoice_company_logo, $uploads['baseurl']) === 0) {
			// convert uploads URL -> uploads path
			$invoice_company_logo_path = str_replace($uploads['baseurl'], $uploads['basedir'], $invoice_company_logo);
		}
	}

		// Debug: (removed) original logging disabled in production

		// If the mapped path does not exist but the logo value is a remote URL, try to download it to a temp uploads folder
		if (!file_exists($invoice_company_logo_path) && strpos($invoice_company_logo, 'http') === 0) {
			// Prefer WP HTTP API when available
			if (function_exists('wp_remote_get')) {
				$response = wp_remote_get($invoice_company_logo, array('timeout' => 8));
				if (!is_wp_error($response) && !empty($response['body'])) {
					$uploads = wp_upload_dir();
					$temp_dir = rtrim($uploads['basedir'], '/\\') . DIRECTORY_SEPARATOR . 'wpgv_temp_logos';
					if (!file_exists($temp_dir)) @mkdir($temp_dir, 0755, true);
					$ext = pathinfo(parse_url($invoice_company_logo, PHP_URL_PATH), PATHINFO_EXTENSION);
					if (!$ext) $ext = 'png';
					$tmpfile = $temp_dir . DIRECTORY_SEPARATOR . 'wpgv_logo_' . md5($invoice_company_logo) . '.' . $ext;
					@file_put_contents($tmpfile, $response['body']);
					if (file_exists($tmpfile)) {
						$invoice_company_logo_path = $tmpfile;
					}
				}
			} else {
				// Fallback to file_get_contents if WP HTTP API not available
				$body = @file_get_contents($invoice_company_logo);
				if ($body !== false) {
					$uploads = wp_upload_dir();
					$temp_dir = rtrim($uploads['basedir'], '/\\') . DIRECTORY_SEPARATOR . 'wpgv_temp_logos';
					if (!file_exists($temp_dir)) @mkdir($temp_dir, 0755, true);
					$ext = pathinfo(parse_url($invoice_company_logo, PHP_URL_PATH), PATHINFO_EXTENSION);
					if (!$ext) $ext = 'png';
					$tmpfile = $temp_dir . DIRECTORY_SEPARATOR . 'wpgv_logo_' . md5($invoice_company_logo) . '.' . $ext;
					@file_put_contents($tmpfile, $body);
					if (file_exists($tmpfile)) {
						$invoice_company_logo_path = $tmpfile;
					}
				}
			}
		}

		// Use @getimagesize to avoid warnings if path is invalid; validate returned value
		$image_size = @getimagesize($invoice_company_logo_path);

	if ($image_size !== false && !empty($image_size[0])) {
		$width = $image_size[0];
		$height = $image_size[1];

		$maxSize = 80; // Fixed size for the bounding box

		if ($width > $height) {
			$scale = $maxSize / $width;
		} else {
			$scale = $maxSize / $height;
		}

		$newWidth = $width * $scale;
		$newHeight = $height * $scale;

		// Calculate positions to center the image within the 60x60 box
		$posX = 30; // X position (left-aligned)
		$posY = 30 + (60 - $newHeight) / 2; // Y position (top-aligned)

	// Use filesystem path if available, otherwise attempt original value (may be a URL)
	$image_for_pdf = (file_exists($invoice_company_logo_path)) ? $invoice_company_logo_path : $invoice_company_logo;
	$invoice->Image($image_for_pdf, $posX, $posY, $newWidth, $newHeight);
	} else {
		$invoice->SetXY(82, 80);
		$invoice->Cell(0, 0, wpgv_em($invoice_company_name), 0, 1, 'L', 0);
	}
} else {
	$invoice->SetXY(82, 80);
	$invoice->Cell(0, 0, wpgv_em($invoice_company_name), 0, 1, 'L', 0);
}

$invoice->SetFont('Arial', 'B', 16);
$invoice->SetXY(30, 160);
$invoice->Cell(0, 0, strtoupper(wpgv_em(__('Invoice', 'gift-voucher'))), 0, 1, 'L', 0);

/* Admin Details */

	$invoice->SetXY(350, 45);
	$invoice->SetTextColor(0, 0, 0);
	$invoice->SetFont('Arial', 'B', 10);
	// Use MultiCell so long company names wrap
	$invoice->MultiCell(200, 12, wpgv_em($invoice_company_name), 0, 'L', 0);

	$invoice->SetXY(350, 60);
	$invoice->SetFont('Arial', '', 10);
	// Use MultiCell for address lines to allow wrapping
	$invoice->MultiCell(200, 10, wpgv_em($invoice_address_line1), 0, 'L', 0);
	$invoice->SetX(350);
	$invoice->MultiCell(200, 10, wpgv_em($invoice_address_line2), 0, 'L', 0);
	$invoice->SetX(350);
	$invoice->MultiCell(200, 10, wpgv_em($invoice_address_line3), 0, 'L', 0);
	$invoice->SetX(350);
	$invoice->MultiCell(200, 10, wpgv_em($invoice_address_line4), 0, 'L', 0);



// Left column: seller / from details - use MultiCell so long text wraps
$invoice->SetXY(30, 200);
$display_from = !empty($seller_company_name) ? $seller_company_name : (isset($result->from_name) ? $result->from_name : '');
$invoice->MultiCell(150, 10, wpgv_em($display_from), 0, 'L', 0);

$invoice->SetX(30);
$display_addr1 = !empty($seller_addr_line1) ? $seller_addr_line1 : (isset($result->email) ? $result->email : '');
$invoice->MultiCell(150, 8, wpgv_em($display_addr1), 0, 'L', 0);

$invoice->SetX(30);
$invoice->MultiCell(150, 8, wpgv_em($seller_addr_line2), 0, 'L', 0);

$invoice->SetX(30);
$invoice->MultiCell(150, 8, wpgv_em($seller_addr_line3), 0, 'L', 0);

$invoice->SetX(30);
$invoice->MultiCell(150, 8, wpgv_em($seller_addr_line4), 0, 'L', 0);


// center
$invoice->SetFont('Arial', 'B', 10);
	$invoice->SetXY(170, 200);
	// Use MultiCell for the shipping block so it wraps
	$invoice->MultiCell(150, 10, wpgv_em(__('Shipping to:', 'gift-voucher')), 0, 'L', 0);

	$invoice->SetX(170);
	$display_ship = !empty($seller_company_name) ? $seller_company_name : (isset($result->from_name) ? $result->from_name : '');
	$invoice->MultiCell(150, 8, wpgv_em($display_ship), 0, 'L', 0);

	$invoice->SetX(170);
	$display_ship_addr1 = !empty($seller_addr_line1) ? $seller_addr_line1 : (isset($result->email) ? $result->email : '');
	$invoice->MultiCell(150, 8, wpgv_em($display_ship_addr1), 0, 'L', 0);

	$invoice->SetX(170);
	$invoice->MultiCell(150, 8, wpgv_em($seller_addr_line2), 0, 'L', 0);


/* Voucher Details */

$invoice->SetXY(350, 200);
$invoice->writeHTML('<b>' . wpgv_em(__('Invoice number', 'gift-voucher')) . ':</b>');

$invoice->SetXY(450, 200);
$current_year = date('Y');
if ($invoice_bill_number) {
	$invoice->Cell(0, 0, ' ' . wpgv_em($invoice_bill_number . "-" . $current_year . "/" . $invoice_current_number_format), 0, 1, 1);
} else {
	$invoice->Cell(0, 0, ' ' . wpgv_em($result->id), 0, 1, 1);
}


if ($buyingfor != 'yourself') {
	$invoice->SetXY(350, 215);
	$current_day = date('Y-m-d');
	$invoice->writeHTML('<b>' . wpgv_em(__('Invoice date', 'gift-voucher')) . ':</b>');

	$invoice->SetXY(450, 215);
	$invoice->Cell(0, 0, wpgv_em(__($current_day, 'gift-voucher')), 0, 1, 'L', 0);
}

$invoice->SetXY(350, 230);
$invoice->writeHTML('<b>' . wpgv_em(__('Order number', 'gift-voucher')) . ':</b>');

$invoice->SetXY(450, 230);
$invoice->Cell(0, 0, wpgv_em($result->id), 0, 1, 1);

$invoice->SetXY(350, 245);
$invoice->writeHTML('<b>' . wpgv_em(__('Order date', 'gift-voucher')) . ':</b>');

$invoice->SetXY(450, 245);
$date_part = explode(' ', $result->voucheradd_time)[0];
$invoice->writeHTML(wpgv_em($date_part));

$invoice->SetXY(350, 260);
$invoice->writeHTML('<b>' . wpgv_em(__('Payment method', 'gift-voucher')) . ':</b>');

$invoice->SetXY(450, 260);
$invoice->writeHTML(wpgv_em($result->pay_method));
// end right

// line black
$invoice->SetXY(30, 290);
$invoice->SetFillColor($invoice_color[0], $invoice_color[1], $invoice_color[2]);
$invoice->Cell(530, 25, '', 0, 1, 'L', 1);

$invoice->SetTextColor(255, 255, 255);
$invoice->SetXY(30, 290);
$invoice->Cell(530, 25, wpgv_em(__('Voucher Name', 'gift-voucher')), 0, 1, 'L', 0);


$invoice->SetTextColor(255, 255, 255);
$invoice->SetXY(350, 290);
$invoice->Cell(530, 25, wpgv_em(__('Quantity', 'gift-voucher')), 0, 1, 'L', 0);


$invoice->SetTextColor(0, 0, 0);
$invoice->SetXY(350, 320);
$invoice->Cell(530, 25, wpgv_em(__('1', 'gift-voucher')), 0, 1, 'L', 0);

$invoice->SetTextColor(255, 255, 255);
$invoice->SetXY(510, 290);
$invoice->Cell(530, 25, wpgv_em(__('Price', 'gift-voucher')), 0, 1, 'L', 0);
// end line black

// voucher name
$invoice->SetTextColor(0, 0, 0);
if ($formtype == 'item') {
	//Title
	$invoice->SetFillColor(0, 0, 0);
	$invoice->SetXY(30, 320);
	$invoice->MultiCell(300, 25, wpgv_em(get_the_title($itemid)), 0, 'L');
} else {
	//Voucher
	$invoice->SetFillColor(0, 0, 0);
	$invoice->SetXY(30, 320);
	$invoice->MultiCell(300, 25, wpgv_em(get_the_title($template)), 0, 'L');
}
// end voucher name

// value Price
$invoice->SetTextColor(0, 0, 0);
// Ensure price strings are encoded to CP1252 for FPDF (prevents UTF-8 mojibake for symbols like €)
$invoice_price_raw = ($special_price) ? wpgv_price_format($special_price) : $currency;
$invoice_price = @iconv('UTF-8', 'CP1252//IGNORE', $invoice_price_raw);
$invoice->SetXY(510, 320);
$invoice->MultiCell(900, 25, $invoice_price, 0, 1, 0);
// end value Price

$invoice->SetXY(30, 350);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(530, 0.5, '', 0, 1, 'L', 0);

//box line

$invoice->SetXY(350, 375);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(210, 0.5, '', 0, 1, 'L', 0);

$invoice->SetXY(350, 375);
$invoice->MultiCell(900, 25, wpgv_em(__('Sub Total:', 'gift-voucher')), 0, 1, 0);

$invoice->SetXY(510, 375);
$invoice->MultiCell(900, 25, $invoice_price, 0, 1, 0);

$invoice->SetXY(350, 400);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(210, 0.5, '', 0, 1, 'L', 0);

$invoice->SetXY(350, 400);
$invoice->MultiCell(900, 25, wpgv_em(__('Charges: +', 'gift-voucher')), 0, 1, 0);
if ($wpgv_add_extra_charges > 0) {
	$invoice->SetXY(510, 400);
	$invoice->MultiCell(300, 25, @iconv('UTF-8', 'CP1252//IGNORE', wpgv_price_format($wpgv_add_extra_charges)), 0, 1, 0);
} else {
	$invoice->SetXY(510, 400);
	$invoice->MultiCell(300, 25, @iconv('UTF-8', 'CP1252//IGNORE', wpgv_price_format("0.00")), 0, 1, 0);
}

$invoice->SetXY(350, 425);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(210, 0.5, '', 0, 1, 'L', 0);

$invoice->SetXY(350, 425);
$invoice->MultiCell(900, 25, wpgv_em(__('Shipping: +', 'gift-voucher')), 0, 1, 0);
if ($shipping_charges > 0) {
	$invoice->SetXY(510, 425);
	$invoice->MultiCell(300, 25, @iconv('UTF-8', 'CP1252//IGNORE', wpgv_price_format($shipping_charges)), 0, 1, 0);
} else {
	$invoice->SetXY(510, 425);
	$invoice->MultiCell(300, 25, @iconv('UTF-8', 'CP1252//IGNORE', wpgv_price_format("0.00")), 0, 1, 0);
}

$invoice->SetXY(350, 450);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(210, 0.5, '', 0, 1, 'L', 0);

/* Total */
$invoice->SetXY(350, 450);
$invoice->MultiCell(900, 25, wpgv_em(__('Total:', 'gift-voucher')), 0, 1, 0);

$invoice->SetXY(510, 450);
$invoice->MultiCell(300, 25, @iconv('UTF-8', 'CP1252//IGNORE', wpgv_price_format($value)), 0, 1, 0);

$invoice->SetXY(350, 475);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(210, 0.5, '', 0, 1, 'L', 0);

//end box line

/* Footer */

$invoice->SetXY(30, 800);
$invoice->SetFillColor(0, 0, 0);
$invoice->MultiCell(530, 0.5, '', 0, 1, 'L', 0);

$invoice->SetXY(0, 810);
$invoice->SetTextColor(0, 0, 0);
$invoice->SetFontSize(10);
$margin = 50;
$textWidth = 595 - 2 * $margin;

$invoice->SetX($margin);
$invoice->MultiCell($textWidth, 20, wpgv_em(__($invoice_bottom_line, 'gift-voucher')), 0, 'C', 0);

$invoice->SetXY(0, 860);
$invoice->SetTextColor(0, 0, 0);
$invoice->SetFontSize(10);
$invoice->Cell(595, 0, wpgv_em(__($invoice_bottom_line_2, 'gift-voucher')), 0, 1, 'C', 0);
