<?php
/**
 * Plugin Name: Zoventic Invoices
 * Plugin URI:  https://wordpress.org/plugins/zoventic-invoices/
 * Description: Create professional invoices & estimates, accept PayPal payments, manage clients, and auto-generate PDFs directly inside WordPress.
 * Version:     1.0.2
 * Author:      Zoventic
 * Author URI:  https://zoventic.com/
 * License:     GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: zoventic-invoices
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 7.1
 * Requires PHP: 8.0
 */

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

// Plugin constants.
if ( ! defined( 'ZINV_VERSION' ) ) {
	define( 'ZINV_VERSION', '1.0.2' );
}
if ( ! defined( 'ZINV_PLUGIN_FILE' ) ) {
	define( 'ZINV_PLUGIN_FILE', __FILE__ );
}
if ( ! defined( 'ZINV_PLUGIN_DIR' ) ) {
	define( 'ZINV_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'ZINV_PLUGIN_URL' ) ) {
	define( 'ZINV_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'ZINV_PLUGIN_BASENAME' ) ) {
	define( 'ZINV_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}

/**
 * Custom autoloader: maps ZINV_Class_Name / Zoventic_Invoices → includes/dir/class-class-name.php.
 */
function zinv_autoloader( string $class ): void {
	static $resolved = [];

	if ( ! preg_match( '/^[a-zA-Z0-9_]+$/', $class ) ) {
		return;
	}

	if ( 0 !== strpos( $class, 'ZINV_' ) && 'Zoventic_Invoices' !== $class ) {
		return;
	}

	if ( isset( $resolved[ $class ] ) ) {
		require $resolved[ $class ];
		return;
	}

	if ( 'Zoventic_Invoices' === $class ) {
		$file = 'class-zoventic-invoices.php';
	} elseif ( 0 === strpos( $class, 'ZINV_' ) ) {
		$short = substr( $class, 5 );
		$file  = 'class-' . str_replace( '_', '-', strtolower( $short ) ) . '.php';
	} else {
		$short = $class;
		$file  = 'class-' . str_replace( '_', '-', strtolower( $short ) ) . '.php';
	}

	$dirs = [
		'',
		'admin/',
		'core/',
		'api/',
		'integrations/',
		'pdf/',
		'cron/',
		'utils/',
		'emails/',
	];

	foreach ( $dirs as $dir ) {
		$path = ZINV_PLUGIN_DIR . 'includes/' . $dir . $file;
		if ( file_exists( $path ) ) {
			$resolved[ $class ] = $path;
			require $path;
			return;
		}
	}
}
spl_autoload_register( 'zinv_autoloader' );

/**
 * Initialize plugin.
 */
function zinv_init(): void {
	if ( class_exists( 'Zoventic_Invoices' ) ) {
		Zoventic_Invoices::get_instance()->init();
	}
}
add_action( 'plugins_loaded', 'zinv_init' );

// Activation hook.
function zinv_activate(): void {
	require_once ZINV_PLUGIN_DIR . 'includes/class-activator.php';
	if ( class_exists( 'ZINV_Activator' ) ) {
		ZINV_Activator::activate();
	}
}
register_activation_hook( __FILE__, 'zinv_activate' );

// Deactivation hook.
function zinv_deactivate(): void {
	require_once ZINV_PLUGIN_DIR . 'includes/class-deactivator.php';
	if ( class_exists( 'ZINV_Deactivator' ) ) {
		ZINV_Deactivator::deactivate();
	}
}
register_deactivation_hook( __FILE__, 'zinv_deactivate' );

