<?php
/**
 * Exception handler class for logging and reporting plugin-specific errors.
 *
 * This class provides centralized error handling for the miniOrange WooCommerce Product Sync plugin.
 * It logs errors to debug log and optionally to a custom logger, ensuring consistent and traceable exception handling.
 *
 * @package    Exception
 * @subpackage Exception
 * @author     miniOrange <info@miniorange.com>
 * @link       https://miniorange.com
 */

namespace MOWCPS\Common\Exception;

use MOWCPS\Common\Services\Logging\Supplier_Logger;
use MOWCPS\Common\Models\Sync_Details_DAO;

/**
 * A custom exception handler for the miniOrange WooCommerce Product Sync plugin.
 */
class Exception extends \Exception {
	/**
	 * Summary of __construct
	 */
	public function __construct() {
	}

	/**
	 * Handles and logs exceptions.
	 *
	 * @param \Throwable $e               The exception to handle.
	 * @param string     $attribute         Additional attribute like function/class name.
	 * @param string     $connection_name (Optional) If applicable.
	 */
	public static function handle( \Throwable $e, string $attribute = '', $connection_id = null ) {
		$supplier_id = Sync_Details_DAO::get_instance()->get_supplier_id();

		// Build detailed error message
		$message = 'Sync error occurred';
		if ( ! empty( $attribute ) ) {
			$message .= ' while processing ' . $attribute;
		}
		if ( $connection_id ) {
			$message .= ' for connection ID: ' . $connection_id;
		}

		// Log the main error
		Supplier_Logger::debug( $supplier_id, $message );
		Supplier_Logger::debug( $supplier_id, 'Error details: ' . $e->getMessage() );
		Supplier_Logger::debug( $supplier_id, 'Error location: ' . $e->getFile() . ' on line ' . $e->getLine() );

		// Add context if available
		if ( method_exists( $e, 'getTrace' ) ) {
			$trace = $e->getTrace();
			if ( ! empty( $trace[0]['function'] ) ) {
				Supplier_Logger::debug( $supplier_id, 'Error occurred in function: ' . $trace[0]['function'] );
			}
		}
	}
}
