<?php
namespace Veno\QrCdr\Lib;

/**
 * QR Code Generator Tools (Generic PHP Version)
 *
 * Helper methods for data binarization, logging, and file saving.
 * 
 * @package   QrCdr
 */

// Sicurezza: Blocca accesso diretto se siamo in WP, ma permette uso esterno se definito QRCDR_OPEN_ACCESS
if ( ! defined( 'ABSPATH' ) && ! defined( 'QRCDR_OPEN_ACCESS' ) ) {
	exit;
}

class QrcdrTools {

	/**
	 * Binarize frame data.
	 *
	 * @param array $frame The data frame.
	 * @return array The binarized frame.
	 */
	public static function binarize( $frame ) {
		$len = count( $frame );
		foreach ( $frame as &$frame_line ) {
			for ( $i = 0; $i < $len; $i++ ) {
				$frame_line[ $i ] = ( ord( $frame_line[ $i ] ) & 1 ) ? '1' : '0';
			}
		}
		return $frame;
	}

	/**
	 * Generates a barcode array for TCPDF.
	 *
	 * @param string $code
	 * @param string|array $mode
	 * @param string $tcPdfVersion (Unused)
	 * @return array
	 */
	public static function tcpdfBarcodeArray( $code, $mode = 'QR,L', $tcPdfVersion = '4.5.037' ) {
		$barcode_array = array();

		if ( ! is_array( $mode ) ) {
			$mode = explode( ',', $mode );
		}

		$ecc_level = 'L';
		if ( count( $mode ) > 1 ) {
			$ecc_level = $mode[1];
		}

		// Chiama la classe QrcdrCode (che deve essere nel namespace corrente o importata)
		$qr_tab = QrcdrCode::text( $code, false, $ecc_level );
		$size   = count( $qr_tab );

		$barcode_array['num_rows'] = $size;
		$barcode_array['num_cols'] = $size;
		$barcode_array['bcode']    = array();

		foreach ( $qr_tab as $line ) {
			$arr_add = array();
			foreach ( str_split( $line ) as $char ) {
				$arr_add[] = ( '1' == $char ) ? 1 : 0;
			}
			$barcode_array['bcode'][] = $arr_add;
		}

		return $barcode_array;
	}

	/**
	 * Log helper (Generic PHP).
	 *
	 * @param string|false $outfile Unused but kept for signature compatibility.
	 * @param string       $err     The error message.
	 */
	public static function log( $outfile, $err ) {
		// if ( '' !== $err ) {
		// 	// Usa il log di errore nativo del server/PHP
		// 	error_log( '[QR Code Lib Error] ' . $err );
		// }
	}

	/**
	 * Save content to file (Generic PHP).
	 *
	 * @param string $content       Content to save.
	 * @param string $filename_path Full path.
	 * @return bool|int False on failure, bytes written on success.
	 */
	public static function save( $content, $filename_path ) {
		// Implementazione PHP standard
		return file_put_contents( $filename_path, $content );
	}
}
