<?php
/**
 * PDF invoice rendering via vendored tFPDF with embedded DejaVu TTF fonts
 * (embedded fonts are REQUIRED for PDF/A-3 conformance — FPDF core fonts fail).
 *
 * tFPDF generates font metric files at runtime next to the TTFs, so fonts are
 * copied on first use into a writable uploads subdirectory.
 *
 * @package FEPW
 */

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

/**
 * Class FEPW_PDF
 */
class FEPW_PDF {

	/**
	 * Ensure writable font dir and load tFPDF.
	 *
	 * @return bool
	 */
	public static function bootstrap() {
		if ( class_exists( 'tFPDF' ) ) {
			return true;
		}

		$uploads  = wp_upload_dir();
		$font_dir = trailingslashit( $uploads['basedir'] ) . 'fepw-fonts/';
		if ( ! is_dir( $font_dir . 'unifont' ) ) {
			wp_mkdir_p( $font_dir . 'unifont' );
			file_put_contents( $font_dir . 'index.html', '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- directory listing guard.
			file_put_contents( $font_dir . '.htaccess', "Require all denied\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- font metrics are only read server-side by the PDF renderer.
		}
		// Copy core font metrics + DejaVu TTFs on first run.
		$src = FEPW_DIR . 'vendor/tfpdf/font/';
		$copies = array_merge(
			glob( $src . '*.php' ) ? glob( $src . '*.php' ) : array(),
			glob( $src . 'unifont/*.php' ) ? glob( $src . 'unifont/*.php' ) : array(),
			glob( $src . 'unifont/*.ttf' ) ? glob( $src . 'unifont/*.ttf' ) : array()
		);
		foreach ( $copies as $file ) {
			$rel  = str_replace( $src, '', $file );
			$dest = $font_dir . $rel;
			if ( ! file_exists( $dest ) ) {
				copy( $file, $dest ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- local file copy into uploads.
			}
		}

		require_once FEPW_DIR . 'vendor/tfpdf/tFPDF.php';
		return class_exists( 'tFPDF' );
	}

	/**
	 * Render the invoice/credit-note PDF.
	 *
	 * @param array $d Assembled invoice data (FEPW_Builder::assemble()).
	 * @return string|WP_Error Binary PDF string.
	 */
	public static function render( $d ) {
		if ( ! self::bootstrap() ) {
			return new WP_Error( 'fepw_pdf', 'tFPDF could not be loaded.' );
		}

		try {
			$pdf = new tFPDF( 'P', 'mm', 'A4' );
			// Per-instance font path (writable uploads dir; tFPDF writes TTF metrics there).
			$uploads       = wp_upload_dir();
			$pdf->fontpath = trailingslashit( $uploads['basedir'] ) . 'fepw-fonts/';
			$pdf->AddFont( 'DejaVu', '', 'DejaVuSans.ttf', true );
			$pdf->AddFont( 'DejaVu', 'B', 'DejaVuSans-Bold.ttf', true );
			$pdf->AddPage();

			$is_credit = '381' === $d['type_code'];
			$fmt_date  = function ( $ymd ) {
				return substr( $ymd, 6, 2 ) . '/' . substr( $ymd, 4, 2 ) . '/' . substr( $ymd, 0, 4 );
			};
			$eur = function ( $n ) {
				return number_format( (float) $n, 2, ',', ' ' ) . ' €';
			};

			// Header.
			$pdf->SetFont( 'DejaVu', 'B', 18 );
			$pdf->Cell( 0, 10, $is_credit ? 'AVOIR' : 'FACTURE', 0, 1 );
			$pdf->SetFont( 'DejaVu', '', 10 );
			$pdf->Cell( 0, 6, ( $is_credit ? 'Avoir n° ' : 'Facture n° ' ) . $d['number'] . '    Date : ' . $fmt_date( $d['issue_date'] ), 0, 1 );
			if ( '' !== $d['ref_number'] ) {
				$pdf->Cell( 0, 6, 'Fait référence à la facture n° ' . $d['ref_number'], 0, 1 );
			}
			$pdf->Cell( 0, 6, 'Commande : ' . $d['order_ref'] . ( $is_credit ? '' : '    Échéance : ' . $fmt_date( $d['due_date'] ) ), 0, 1 );
			$pdf->Ln( 4 );

			// Parties.
			$y = $pdf->GetY();
			$pdf->SetFont( 'DejaVu', 'B', 10 );
			$pdf->Cell( 95, 6, 'Émetteur', 0, 0 );
			$pdf->Cell( 95, 6, 'Client', 0, 1 );
			$pdf->SetFont( 'DejaVu', '', 9 );
			$seller_lines = array_filter( array(
				$d['seller']['name'],
				$d['seller']['address'],
				trim( $d['seller']['postcode'] . ' ' . $d['seller']['city'] ),
				'' !== $d['seller']['siren'] ? 'SIREN : ' . $d['seller']['siren'] : '',
				'' !== $d['seller']['tva'] ? 'TVA : ' . $d['seller']['tva'] : '',
				$d['seller']['legal'],
			) );
			$buyer_lines  = array_filter( array(
				$d['buyer']['name'],
				$d['buyer']['address'],
				trim( $d['buyer']['postcode'] . ' ' . $d['buyer']['city'] ),
				'' !== $d['buyer']['siren'] ? 'SIREN : ' . $d['buyer']['siren'] : '',
				'' !== $d['buyer']['tva'] ? 'TVA : ' . $d['buyer']['tva'] : '',
			) );
			$rows = max( count( $seller_lines ), count( $buyer_lines ) );
			$seller_lines = array_values( $seller_lines );
			$buyer_lines  = array_values( $buyer_lines );
			for ( $i = 0; $i < $rows; $i++ ) {
				$pdf->Cell( 95, 5, isset( $seller_lines[ $i ] ) ? $seller_lines[ $i ] : '', 0, 0 );
				$pdf->Cell( 95, 5, isset( $buyer_lines[ $i ] ) ? $buyer_lines[ $i ] : '', 0, 1 );
			}
			$pdf->Ln( 5 );

			// Lines table.
			$pdf->SetFont( 'DejaVu', 'B', 9 );
			$pdf->SetFillColor( 240, 240, 241 );
			$pdf->Cell( 90, 7, 'Désignation', 1, 0, 'L', true );
			$pdf->Cell( 20, 7, 'Qté', 1, 0, 'C', true );
			$pdf->Cell( 30, 7, 'PU HT', 1, 0, 'R', true );
			$pdf->Cell( 20, 7, 'TVA %', 1, 0, 'C', true );
			$pdf->Cell( 30, 7, 'Total HT', 1, 1, 'R', true );
			$pdf->SetFont( 'DejaVu', '', 9 );
			foreach ( $d['lines'] as $line ) {
				$name = mb_strlen( $line['name'] ) > 52 ? mb_substr( $line['name'], 0, 50 ) . '…' : $line['name'];
				$pdf->Cell( 90, 7, $name, 1, 0 );
				$pdf->Cell( 20, 7, (string) $line['qty'], 1, 0, 'C' );
				$pdf->Cell( 30, 7, $eur( $line['unit_net'] ), 1, 0, 'R' );
				$pdf->Cell( 20, 7, number_format( $line['rate'], 1, ',', '' ), 1, 0, 'C' );
				$pdf->Cell( 30, 7, $eur( $line['net'] ), 1, 1, 'R' );
			}
			$pdf->Ln( 3 );

			// VAT breakdown + totals.
			$pdf->SetFont( 'DejaVu', 'B', 9 );
			$pdf->Cell( 0, 6, 'Récapitulatif TVA', 0, 1 );
			$pdf->SetFont( 'DejaVu', '', 9 );
			foreach ( $d['breakdown'] as $b ) {
				$pdf->Cell( 60, 6, 'Taux ' . number_format( $b['rate'], 1, ',', '' ) . ' %', 0, 0 );
				$pdf->Cell( 60, 6, 'Base HT : ' . $eur( $b['base'] ), 0, 0 );
				$pdf->Cell( 60, 6, 'TVA : ' . $eur( $b['tax'] ), 0, 1 );
			}
			$pdf->Ln( 2 );
			$pdf->SetFont( 'DejaVu', 'B', 11 );
			$pdf->Cell( 130, 7, 'Total HT', 0, 0, 'R' );
			$pdf->Cell( 60, 7, $eur( $d['total_ht'] ), 0, 1, 'R' );
			$pdf->Cell( 130, 7, 'Total TVA', 0, 0, 'R' );
			$pdf->Cell( 60, 7, $eur( $d['total_tva'] ), 0, 1, 'R' );
			$pdf->Cell( 130, 8, 'Total TTC', 0, 0, 'R' );
			$pdf->Cell( 60, 8, $eur( $d['total_ttc'] ), 0, 1, 'R' );
			$pdf->Ln( 4 );

			// Mandatory mentions.
			$pdf->SetFont( 'DejaVu', '', 8 );
			foreach ( $d['notes'] as $note ) {
				$pdf->Cell( 0, 5, $note, 0, 1 );
			}
			$pdf->Cell( 0, 5, 'Pénalités de retard : taux légal en vigueur. Indemnité forfaitaire pour frais de recouvrement : 40 €.', 0, 1 );

			return $pdf->Output( '', 'S' ); // FPDF 1.7-era signature: ($name, $dest).
		} catch ( Throwable $e ) {
			return new WP_Error( 'fepw_pdf', $e->getMessage() );
		}
	}
}
